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

lightningnetwork / lnd / 16569502135

28 Jul 2025 12:50PM UTC coverage: 67.251% (+0.02%) from 67.227%
16569502135

Pull #9455

github

web-flow
Merge b3899c4fd into 2e36f9b8b
Pull Request #9455: discovery+lnwire: add support for DNS host name in NodeAnnouncement msg

179 of 208 new or added lines in 6 files covered. (86.06%)

105 existing lines in 23 files now uncovered.

135676 of 201746 relevant lines covered (67.25%)

21711.59 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

173✔
233
        return g, nil
173✔
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) {
148✔
251

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

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

591✔
263
                        return nil
591✔
264
                }
591✔
265

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

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

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

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

999✔
285
                switch {
999✔
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
999✔
303

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

310
        return channelMap, nil
148✔
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 {
173✔
325
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
346✔
326
                for _, tlb := range graphTopLevelBuckets {
856✔
327
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
683✔
328
                                return err
×
329
                        }
×
330
                }
331

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

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

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

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

369
        return nil
173✔
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) {
6✔
379

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

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

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

395
        return true, node.Addresses, nil
5✔
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 {
10✔
410

10✔
411
        return forEachChannel(c.db, cb, reset)
10✔
412
}
10✔
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 {
10✔
426

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

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

440
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
10✔
441
                if edgeIndex == nil {
10✔
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(
10✔
448
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
115✔
449
                                var chanID [8]byte
105✔
450
                                copy(chanID[:], k)
105✔
451

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

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

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

105✔
470
                                return cb(&info, policy1, policy2)
105✔
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 {
141✔
491

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

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

505
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
141✔
506
                if edgeIndex == nil {
141✔
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(
141✔
513
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
540✔
514
                                var chanID [8]byte
399✔
515
                                copy(chanID[:], k)
399✔
516

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

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

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

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

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

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

557
                                return cb(
399✔
558
                                        models.NewCachedEdge(&info),
399✔
559
                                        cachedPolicy1, cachedPolicy2,
399✔
560
                                )
399✔
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 {
265✔
580

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

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

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

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

689✔
609
                if p1 != nil {
1,377✔
610
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
1,024✔
611
                                directedChannel.InboundFee = fee
336✔
612
                        })
336✔
613
                }
614

615
                if node == e.NodeKey2Bytes {
1,035✔
616
                        directedChannel.OtherNode = e.NodeKey1Bytes
346✔
617
                }
346✔
618

619
                return cb(directedChannel)
689✔
620
        }
621

622
        return nodeTraversal(tx, node[:], c.db, dbCallback, reset)
265✔
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) {
710✔
630

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

638
        // If we couldn't find a node announcement, populate a blank feature
639
        // vector.
640
        case errors.Is(err, ErrGraphNodeNotFound):
11✔
641
                return lnwire.EmptyFeatureVector(), nil
11✔
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 {
26✔
659

26✔
660
        return c.forEachNodeDirectedChannel(nil, nodePub, cb, reset)
26✔
661
}
26✔
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) {
4✔
669

4✔
670
        return c.fetchNodeFeatures(nil, nodePub)
4✔
671
}
4✔
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(_ context.Context,
678
        cb func(node route.Vertex, chans map[uint64]*DirectedChannel) error,
679
        reset func()) error {
1✔
680

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

20✔
688
                channels := make(map[uint64]*DirectedChannel)
20✔
689

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

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

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

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

190✔
725
                                if node.PubKeyBytes == e.NodeKey2Bytes {
285✔
726
                                        directedChannel.OtherNode =
95✔
727
                                                e.NodeKey1Bytes
95✔
728
                                }
95✔
729

730
                                channels[e.ChannelID] = directedChannel
190✔
731

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

739
                return cb(node.PubKeyBytes, channels)
20✔
740
        }, reset)
741
}
742

743
// DisabledChannelIDs returns the channel ids of disabled channels.
744
// A channel is disabled when two of the associated ChanelEdgePolicies
745
// have their disabled bit on.
746
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
6✔
747
        var disabledChanIDs []uint64
6✔
748
        var chanEdgeFound map[uint64]struct{}
6✔
749

6✔
750
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
751
                edges := tx.ReadBucket(edgeBucket)
6✔
752
                if edges == nil {
6✔
753
                        return ErrGraphNoEdgesFound
×
754
                }
×
755

756
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
757
                        disabledEdgePolicyBucket,
6✔
758
                )
6✔
759
                if disabledEdgePolicyIndex == nil {
7✔
760
                        return nil
1✔
761
                }
1✔
762

763
                // We iterate over all disabled policies and we add each channel
764
                // that has more than one disabled policy to disabledChanIDs
765
                // array.
766
                return disabledEdgePolicyIndex.ForEach(
5✔
767
                        func(k, v []byte) error {
16✔
768
                                chanID := byteOrder.Uint64(k[:8])
11✔
769
                                _, edgeFound := chanEdgeFound[chanID]
11✔
770
                                if edgeFound {
15✔
771
                                        delete(chanEdgeFound, chanID)
4✔
772
                                        disabledChanIDs = append(
4✔
773
                                                disabledChanIDs, chanID,
4✔
774
                                        )
4✔
775

4✔
776
                                        return nil
4✔
777
                                }
4✔
778

779
                                chanEdgeFound[chanID] = struct{}{}
7✔
780

7✔
781
                                return nil
7✔
782
                        },
783
                )
784
        }, func() {
6✔
785
                disabledChanIDs = nil
6✔
786
                chanEdgeFound = make(map[uint64]struct{})
6✔
787
        })
6✔
788
        if err != nil {
6✔
789
                return nil, err
×
790
        }
×
791

792
        return disabledChanIDs, nil
6✔
793
}
794

795
// ForEachNode iterates through all the stored vertices/nodes in the graph,
796
// executing the passed callback with each node encountered. If the callback
797
// returns an error, then the transaction is aborted and the iteration stops
798
// early. Any operations performed on the NodeTx passed to the call-back are
799
// executed under the same read transaction and so, methods on the NodeTx object
800
// _MUST_ only be called from within the call-back.
801
func (c *KVStore) ForEachNode(_ context.Context,
802
        cb func(tx NodeRTx) error, reset func()) error {
131✔
803

131✔
804
        return forEachNode(c.db, func(tx kvdb.RTx,
131✔
805
                node *models.LightningNode) error {
1,292✔
806

1,161✔
807
                return cb(newChanGraphNodeTx(tx, c, node))
1,161✔
808
        }, reset)
1,161✔
809
}
810

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

132✔
821
        traversal := func(tx kvdb.RTx) error {
264✔
822
                // First grab the nodes bucket which stores the mapping from
132✔
823
                // pubKey to node information.
132✔
824
                nodes := tx.ReadBucket(nodeBucket)
132✔
825
                if nodes == nil {
132✔
826
                        return ErrGraphNotFound
×
827
                }
×
828

829
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,574✔
830
                        // If this is the source key, then we skip this
1,442✔
831
                        // iteration as the value for this key is a pubKey
1,442✔
832
                        // rather than raw node information.
1,442✔
833
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
1,706✔
834
                                return nil
264✔
835
                        }
264✔
836

837
                        nodeReader := bytes.NewReader(nodeBytes)
1,181✔
838
                        node, err := deserializeLightningNode(nodeReader)
1,181✔
839
                        if err != nil {
1,181✔
840
                                return err
×
841
                        }
×
842

843
                        // Execute the callback, the transaction will abort if
844
                        // this returns an error.
845
                        return cb(tx, &node)
1,181✔
846
                })
847
        }
848

849
        return kvdb.View(db, traversal, reset)
132✔
850
}
851

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

142✔
860
        traversal := func(tx kvdb.RTx) error {
284✔
861
                // First grab the nodes bucket which stores the mapping from
142✔
862
                // pubKey to node information.
142✔
863
                nodes := tx.ReadBucket(nodeBucket)
142✔
864
                if nodes == nil {
142✔
865
                        return ErrGraphNotFound
×
866
                }
×
867

868
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
543✔
869
                        // If this is the source key, then we skip this
401✔
870
                        // iteration as the value for this key is a pubKey
401✔
871
                        // rather than raw node information.
401✔
872
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
682✔
873
                                return nil
281✔
874
                        }
281✔
875

876
                        nodeReader := bytes.NewReader(nodeBytes)
123✔
877
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
123✔
878
                                nodeReader,
123✔
879
                        )
123✔
880
                        if err != nil {
123✔
881
                                return err
×
882
                        }
×
883

884
                        // Execute the callback, the transaction will abort if
885
                        // this returns an error.
886
                        return cb(node, features)
123✔
887
                })
888
        }
889

890
        return kvdb.View(c.db, traversal, reset)
142✔
891
}
892

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

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

913
                node, err := sourceNodeWithTx(nodes)
241✔
914
                if err != nil {
245✔
915
                        return err
4✔
916
                }
4✔
917
                source = node
240✔
918

240✔
919
                return nil
240✔
920
        }, func() {
241✔
921
                source = nil
241✔
922
        })
241✔
923
        if err != nil {
245✔
924
                return nil, err
4✔
925
        }
4✔
926

927
        return source, nil
240✔
928
}
929

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

940
        // With the pubKey of the source node retrieved, we're able to
941
        // fetch the full node information.
942
        node, err := fetchLightningNode(nodes, selfPub)
504✔
943
        if err != nil {
504✔
944
                return nil, err
×
945
        }
×
946

947
        return &node, nil
504✔
948
}
949

950
// SetSourceNode sets the source node within the graph database. The source
951
// node is to be used as the center of a star-graph within path finding
952
// algorithms.
953
func (c *KVStore) SetSourceNode(_ context.Context,
954
        node *models.LightningNode) error {
117✔
955

117✔
956
        nodePubBytes := node.PubKeyBytes[:]
117✔
957

117✔
958
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
234✔
959
                // First grab the nodes bucket which stores the mapping from
117✔
960
                // pubKey to node information.
117✔
961
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
117✔
962
                if err != nil {
117✔
963
                        return err
×
964
                }
×
965

966
                // Next we create the mapping from source to the targeted
967
                // public key.
968
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
117✔
969
                        return err
×
970
                }
×
971

972
                // Finally, we commit the information of the lightning node
973
                // itself.
974
                return addLightningNode(tx, node)
117✔
975
        }, func() {})
117✔
976
}
977

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

715✔
989
        r := &batch.Request[kvdb.RwTx]{
715✔
990
                Opts: batch.NewSchedulerOptions(opts...),
715✔
991
                Do: func(tx kvdb.RwTx) error {
1,430✔
992
                        return addLightningNode(tx, node)
715✔
993
                },
715✔
994
        }
995

996
        return c.nodeScheduler.Execute(ctx, r)
715✔
997
}
998

999
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
914✔
1000
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
914✔
1001
        if err != nil {
914✔
1002
                return err
×
1003
        }
×
1004

1005
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
914✔
1006
        if err != nil {
914✔
1007
                return err
×
1008
        }
×
1009

1010
        updateIndex, err := nodes.CreateBucketIfNotExists(
914✔
1011
                nodeUpdateIndexBucket,
914✔
1012
        )
914✔
1013
        if err != nil {
914✔
1014
                return err
×
1015
        }
×
1016

1017
        return putLightningNode(nodes, aliases, updateIndex, node)
914✔
1018
}
1019

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

5✔
1025
        var alias string
5✔
1026

5✔
1027
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
1028
                nodes := tx.ReadBucket(nodeBucket)
5✔
1029
                if nodes == nil {
5✔
1030
                        return ErrGraphNodesNotFound
×
1031
                }
×
1032

1033
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
5✔
1034
                if aliases == nil {
5✔
1035
                        return ErrGraphNodesNotFound
×
1036
                }
×
1037

1038
                nodePub := pub.SerializeCompressed()
5✔
1039
                a := aliases.Get(nodePub)
5✔
1040
                if a == nil {
6✔
1041
                        return ErrNodeAliasNotFound
1✔
1042
                }
1✔
1043

1044
                // TODO(roasbeef): should actually be using the utf-8
1045
                // package...
1046
                alias = string(a)
4✔
1047

4✔
1048
                return nil
4✔
1049
        }, func() {
5✔
1050
                alias = ""
5✔
1051
        })
5✔
1052
        if err != nil {
6✔
1053
                return "", err
1✔
1054
        }
1✔
1055

1056
        return alias, nil
4✔
1057
}
1058

1059
// DeleteLightningNode starts a new database transaction to remove a vertex/node
1060
// from the database according to the node's public key.
1061
func (c *KVStore) DeleteLightningNode(_ context.Context,
1062
        nodePub route.Vertex) error {
4✔
1063

4✔
1064
        // TODO(roasbeef): ensure dangling edges are removed...
4✔
1065
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
8✔
1066
                nodes := tx.ReadWriteBucket(nodeBucket)
4✔
1067
                if nodes == nil {
4✔
1068
                        return ErrGraphNodeNotFound
×
1069
                }
×
1070

1071
                return c.deleteLightningNode(nodes, nodePub[:])
4✔
1072
        }, func() {})
4✔
1073
}
1074

1075
// deleteLightningNode uses an existing database transaction to remove a
1076
// vertex/node from the database according to the node's public key.
1077
func (c *KVStore) deleteLightningNode(nodes kvdb.RwBucket,
1078
        compressedPubKey []byte) error {
72✔
1079

72✔
1080
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
72✔
1081
        if aliases == nil {
72✔
1082
                return ErrGraphNodesNotFound
×
1083
        }
×
1084

1085
        if err := aliases.Delete(compressedPubKey); err != nil {
72✔
1086
                return err
×
1087
        }
×
1088

1089
        // Before we delete the node, we'll fetch its current state so we can
1090
        // determine when its last update was to clear out the node update
1091
        // index.
1092
        node, err := fetchLightningNode(nodes, compressedPubKey)
72✔
1093
        if err != nil {
73✔
1094
                return err
1✔
1095
        }
1✔
1096

1097
        if err := nodes.Delete(compressedPubKey); err != nil {
71✔
1098
                return err
×
1099
        }
×
1100

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

1109
        // In order to delete the entry, we'll need to reconstruct the key for
1110
        // its last update.
1111
        updateUnix := uint64(node.LastUpdate.Unix())
71✔
1112
        var indexKey [8 + 33]byte
71✔
1113
        byteOrder.PutUint64(indexKey[:8], updateUnix)
71✔
1114
        copy(indexKey[8:], compressedPubKey)
71✔
1115

71✔
1116
        return nodeUpdateIndex.Delete(indexKey[:])
71✔
1117
}
1118

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

1,724✔
1128
        var alreadyExists bool
1,724✔
1129
        r := &batch.Request[kvdb.RwTx]{
1,724✔
1130
                Opts: batch.NewSchedulerOptions(opts...),
1,724✔
1131
                Reset: func() {
3,448✔
1132
                        alreadyExists = false
1,724✔
1133
                },
1,724✔
1134
                Do: func(tx kvdb.RwTx) error {
1,724✔
1135
                        err := c.addChannelEdge(tx, edge)
1,724✔
1136

1,724✔
1137
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,724✔
1138
                        // succeed, but propagate the error via local state.
1,724✔
1139
                        if errors.Is(err, ErrEdgeAlreadyExist) {
1,961✔
1140
                                alreadyExists = true
237✔
1141
                                return nil
237✔
1142
                        }
237✔
1143

1144
                        return err
1,487✔
1145
                },
1146
                OnCommit: func(err error) error {
1,724✔
1147
                        switch {
1,724✔
1148
                        case err != nil:
×
1149
                                return err
×
1150
                        case alreadyExists:
237✔
1151
                                return ErrEdgeAlreadyExist
237✔
1152
                        default:
1,487✔
1153
                                c.rejectCache.remove(edge.ChannelID)
1,487✔
1154
                                c.chanCache.remove(edge.ChannelID)
1,487✔
1155
                                return nil
1,487✔
1156
                        }
1157
                },
1158
        }
1159

1160
        return c.chanScheduler.Execute(ctx, r)
1,724✔
1161
}
1162

1163
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1164
// utilize an existing db transaction.
1165
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
1166
        edge *models.ChannelEdgeInfo) error {
1,724✔
1167

1,724✔
1168
        // Construct the channel's primary key which is the 8-byte channel ID.
1,724✔
1169
        var chanKey [8]byte
1,724✔
1170
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,724✔
1171

1,724✔
1172
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,724✔
1173
        if err != nil {
1,724✔
1174
                return err
×
1175
        }
×
1176
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,724✔
1177
        if err != nil {
1,724✔
1178
                return err
×
1179
        }
×
1180
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,724✔
1181
        if err != nil {
1,724✔
1182
                return err
×
1183
        }
×
1184
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,724✔
1185
        if err != nil {
1,724✔
1186
                return err
×
1187
        }
×
1188

1189
        // First, attempt to check if this edge has already been created. If
1190
        // so, then we can exit early as this method is meant to be idempotent.
1191
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
1,961✔
1192
                return ErrEdgeAlreadyExist
237✔
1193
        }
237✔
1194

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

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

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

1238
        // Mark edge policies for both sides as unknown. This is to enable
1239
        // efficient incoming channel lookup for a node.
1240
        keys := []*[33]byte{
1,487✔
1241
                &edge.NodeKey1Bytes,
1,487✔
1242
                &edge.NodeKey2Bytes,
1,487✔
1243
        }
1,487✔
1244
        for _, key := range keys {
4,458✔
1245
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,971✔
1246
                if err != nil {
2,971✔
1247
                        return err
×
1248
                }
×
1249
        }
1250

1251
        // Finally we add it to the channel index which maps channel points
1252
        // (outpoints) to the shorter channel ID's.
1253
        var b bytes.Buffer
1,487✔
1254
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
1,487✔
1255
                return err
×
1256
        }
×
1257

1258
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,487✔
1259
}
1260

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

212✔
1270
        var (
212✔
1271
                upd1Time time.Time
212✔
1272
                upd2Time time.Time
212✔
1273
                exists   bool
212✔
1274
                isZombie bool
212✔
1275
        )
212✔
1276

212✔
1277
        // We'll query the cache with the shared lock held to allow multiple
212✔
1278
        // readers to access values in the cache concurrently if they exist.
212✔
1279
        c.cacheMu.RLock()
212✔
1280
        if entry, ok := c.rejectCache.get(chanID); ok {
283✔
1281
                c.cacheMu.RUnlock()
71✔
1282
                upd1Time = time.Unix(entry.upd1Time, 0)
71✔
1283
                upd2Time = time.Unix(entry.upd2Time, 0)
71✔
1284
                exists, isZombie = entry.flags.unpack()
71✔
1285

71✔
1286
                return upd1Time, upd2Time, exists, isZombie, nil
71✔
1287
        }
71✔
1288
        c.cacheMu.RUnlock()
144✔
1289

144✔
1290
        c.cacheMu.Lock()
144✔
1291
        defer c.cacheMu.Unlock()
144✔
1292

144✔
1293
        // The item was not found with the shared lock, so we'll acquire the
144✔
1294
        // exclusive lock and check the cache again in case another method added
144✔
1295
        // the entry to the cache while no lock was held.
144✔
1296
        if entry, ok := c.rejectCache.get(chanID); ok {
151✔
1297
                upd1Time = time.Unix(entry.upd1Time, 0)
7✔
1298
                upd2Time = time.Unix(entry.upd2Time, 0)
7✔
1299
                exists, isZombie = entry.flags.unpack()
7✔
1300

7✔
1301
                return upd1Time, upd2Time, exists, isZombie, nil
7✔
1302
        }
7✔
1303

1304
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
280✔
1305
                edges := tx.ReadBucket(edgeBucket)
140✔
1306
                if edges == nil {
140✔
1307
                        return ErrGraphNoEdgesFound
×
1308
                }
×
1309
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
140✔
1310
                if edgeIndex == nil {
140✔
1311
                        return ErrGraphNoEdgesFound
×
1312
                }
×
1313

1314
                var channelID [8]byte
140✔
1315
                byteOrder.PutUint64(channelID[:], chanID)
140✔
1316

140✔
1317
                // If the edge doesn't exist, then we'll also check our zombie
140✔
1318
                // index.
140✔
1319
                if edgeIndex.Get(channelID[:]) == nil {
231✔
1320
                        exists = false
91✔
1321
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
91✔
1322
                        if zombieIndex != nil {
182✔
1323
                                isZombie, _, _ = isZombieEdge(
91✔
1324
                                        zombieIndex, chanID,
91✔
1325
                                )
91✔
1326
                        }
91✔
1327

1328
                        return nil
91✔
1329
                }
1330

1331
                exists = true
52✔
1332
                isZombie = false
52✔
1333

52✔
1334
                // If the channel has been found in the graph, then retrieve
52✔
1335
                // the edges itself so we can return the last updated
52✔
1336
                // timestamps.
52✔
1337
                nodes := tx.ReadBucket(nodeBucket)
52✔
1338
                if nodes == nil {
52✔
1339
                        return ErrGraphNodeNotFound
×
1340
                }
×
1341

1342
                e1, e2, err := fetchChanEdgePolicies(
52✔
1343
                        edgeIndex, edges, channelID[:],
52✔
1344
                )
52✔
1345
                if err != nil {
52✔
1346
                        return err
×
1347
                }
×
1348

1349
                // As we may have only one of the edges populated, only set the
1350
                // update time if the edge was found in the database.
1351
                if e1 != nil {
73✔
1352
                        upd1Time = e1.LastUpdate
21✔
1353
                }
21✔
1354
                if e2 != nil {
71✔
1355
                        upd2Time = e2.LastUpdate
19✔
1356
                }
19✔
1357

1358
                return nil
52✔
1359
        }, func() {}); err != nil {
140✔
1360
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1361
        }
×
1362

1363
        c.rejectCache.insert(chanID, rejectCacheEntry{
140✔
1364
                upd1Time: upd1Time.Unix(),
140✔
1365
                upd2Time: upd2Time.Unix(),
140✔
1366
                flags:    packRejectFlags(exists, isZombie),
140✔
1367
        })
140✔
1368

140✔
1369
        return upd1Time, upd2Time, exists, isZombie, nil
140✔
1370
}
1371

1372
// AddEdgeProof sets the proof of an existing edge in the graph database.
1373
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1374
        proof *models.ChannelAuthProof) error {
5✔
1375

5✔
1376
        // Construct the channel's primary key which is the 8-byte channel ID.
5✔
1377
        var chanKey [8]byte
5✔
1378
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
5✔
1379

5✔
1380
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
10✔
1381
                edges := tx.ReadWriteBucket(edgeBucket)
5✔
1382
                if edges == nil {
5✔
1383
                        return ErrEdgeNotFound
×
1384
                }
×
1385

1386
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
5✔
1387
                if edgeIndex == nil {
5✔
1388
                        return ErrEdgeNotFound
×
1389
                }
×
1390

1391
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
5✔
1392
                if err != nil {
5✔
1393
                        return err
×
1394
                }
×
1395

1396
                edge.AuthProof = proof
5✔
1397

5✔
1398
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
5✔
1399
        }, func() {})
5✔
1400
}
1401

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

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

243✔
1423
        c.cacheMu.Lock()
243✔
1424
        defer c.cacheMu.Unlock()
243✔
1425

243✔
1426
        var (
243✔
1427
                chansClosed []*models.ChannelEdgeInfo
243✔
1428
                prunedNodes []route.Vertex
243✔
1429
        )
243✔
1430

243✔
1431
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
486✔
1432
                // First grab the edges bucket which houses the information
243✔
1433
                // we'd like to delete
243✔
1434
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
243✔
1435
                if err != nil {
243✔
1436
                        return err
×
1437
                }
×
1438

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

1460
                // For each of the outpoints that have been spent within the
1461
                // block, we attempt to delete them from the graph as if that
1462
                // outpoint was a channel, then it has now been closed.
1463
                for _, chanPoint := range spentOutputs {
373✔
1464
                        // TODO(roasbeef): load channel bloom filter, continue
130✔
1465
                        // if NOT if filter
130✔
1466

130✔
1467
                        var opBytes bytes.Buffer
130✔
1468
                        err := WriteOutpoint(&opBytes, chanPoint)
130✔
1469
                        if err != nil {
130✔
1470
                                return err
×
1471
                        }
×
1472

1473
                        // First attempt to see if the channel exists within
1474
                        // the database, if not, then we can exit early.
1475
                        chanID := chanIndex.Get(opBytes.Bytes())
130✔
1476
                        if chanID == nil {
237✔
1477
                                continue
107✔
1478
                        }
1479

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

1492
                        chansClosed = append(chansClosed, edgeInfo)
23✔
1493
                }
1494

1495
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
243✔
1496
                if err != nil {
243✔
1497
                        return err
×
1498
                }
×
1499

1500
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
243✔
1501
                        pruneLogBucket,
243✔
1502
                )
243✔
1503
                if err != nil {
243✔
1504
                        return err
×
1505
                }
×
1506

1507
                // With the graph pruned, add a new entry to the prune log,
1508
                // which can be used to check if the graph is fully synced with
1509
                // the current UTXO state.
1510
                var blockHeightBytes [4]byte
243✔
1511
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
243✔
1512

243✔
1513
                var newTip [pruneTipBytes]byte
243✔
1514
                copy(newTip[:], blockHash[:])
243✔
1515

243✔
1516
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
243✔
1517
                if err != nil {
243✔
1518
                        return err
×
1519
                }
×
1520

1521
                // Now that the graph has been pruned, we'll also attempt to
1522
                // prune any nodes that have had a channel closed within the
1523
                // latest block.
1524
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
243✔
1525

243✔
1526
                return err
243✔
1527
        }, func() {
243✔
1528
                chansClosed = nil
243✔
1529
                prunedNodes = nil
243✔
1530
        })
243✔
1531
        if err != nil {
243✔
1532
                return nil, nil, err
×
1533
        }
×
1534

1535
        for _, channel := range chansClosed {
266✔
1536
                c.rejectCache.remove(channel.ChannelID)
23✔
1537
                c.chanCache.remove(channel.ChannelID)
23✔
1538
        }
23✔
1539

1540
        return chansClosed, prunedNodes, nil
243✔
1541
}
1542

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

1563
                var err error
26✔
1564
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
26✔
1565
                if err != nil {
26✔
1566
                        return err
×
1567
                }
×
1568

1569
                return nil
26✔
1570
        }, func() {
26✔
1571
                prunedNodes = nil
26✔
1572
        })
26✔
1573

1574
        return prunedNodes, err
26✔
1575
}
1576

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

266✔
1583
        log.Trace("Pruning nodes from graph with no open channels")
266✔
1584

266✔
1585
        // We'll retrieve the graph's source node to ensure we don't remove it
266✔
1586
        // even if it no longer has any open channels.
266✔
1587
        sourceNode, err := sourceNodeWithTx(nodes)
266✔
1588
        if err != nil {
266✔
1589
                return nil, err
×
1590
        }
×
1591

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

1604
                var nodePub [33]byte
512✔
1605
                copy(nodePub[:], pubKey)
512✔
1606
                nodeRefCounts[nodePub] = 0
512✔
1607

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

1614
        // To ensure we never delete the source node, we'll start off by
1615
        // bumping its ref count to 1.
1616
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
266✔
1617

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

198✔
1629
                // With the nodes extracted, we'll increase the ref count of
198✔
1630
                // each of the nodes.
198✔
1631
                nodeRefCounts[node1]++
198✔
1632
                nodeRefCounts[node2]++
198✔
1633

198✔
1634
                return nil
198✔
1635
        })
198✔
1636
        if err != nil {
266✔
1637
                return nil, err
×
1638
        }
×
1639

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

1651
                // If we reach this point, then there are no longer any edges
1652
                // that connect this node, so we can delete it.
1653
                err := c.deleteLightningNode(nodes, nodePubKey[:])
68✔
1654
                if err != nil {
68✔
1655
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1656
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1657

×
1658
                                log.Warnf("Unable to prune node %x from the "+
×
1659
                                        "graph: %v", nodePubKey, err)
×
1660
                                continue
×
1661
                        }
1662

1663
                        return nil, err
×
1664
                }
1665

1666
                log.Infof("Pruned unconnected node %x from channel graph",
68✔
1667
                        nodePubKey[:])
68✔
1668

68✔
1669
                pruned = append(pruned, nodePubKey)
68✔
1670
        }
1671

1672
        if len(pruned) > 0 {
318✔
1673
                log.Infof("Pruned %v unconnected nodes from the channel graph",
52✔
1674
                        len(pruned))
52✔
1675
        }
52✔
1676

1677
        return pruned, err
266✔
1678
}
1679

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

157✔
1690
        // Every channel having a ShortChannelID starting at 'height'
157✔
1691
        // will no longer be confirmed.
157✔
1692
        startShortChanID := lnwire.ShortChannelID{
157✔
1693
                BlockHeight: height,
157✔
1694
        }
157✔
1695

157✔
1696
        // Delete everything after this height from the db up until the
157✔
1697
        // SCID alias range.
157✔
1698
        endShortChanID := aliasmgr.StartingAlias
157✔
1699

157✔
1700
        // The block height will be the 3 first bytes of the channel IDs.
157✔
1701
        var chanIDStart [8]byte
157✔
1702
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
157✔
1703
        var chanIDEnd [8]byte
157✔
1704
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
157✔
1705

157✔
1706
        c.cacheMu.Lock()
157✔
1707
        defer c.cacheMu.Unlock()
157✔
1708

157✔
1709
        // Keep track of the channels that are removed from the graph.
157✔
1710
        var removedChans []*models.ChannelEdgeInfo
157✔
1711

157✔
1712
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
314✔
1713
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
157✔
1714
                if err != nil {
157✔
1715
                        return err
×
1716
                }
×
1717
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
157✔
1718
                if err != nil {
157✔
1719
                        return err
×
1720
                }
×
1721
                chanIndex, err := edges.CreateBucketIfNotExists(
157✔
1722
                        channelPointBucket,
157✔
1723
                )
157✔
1724
                if err != nil {
157✔
1725
                        return err
×
1726
                }
×
1727
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
157✔
1728
                if err != nil {
157✔
1729
                        return err
×
1730
                }
×
1731

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

157✔
1741
                //nolint:ll
157✔
1742
                for k, _ := cursor.Seek(chanIDStart[:]); k != nil &&
157✔
1743
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, _ = cursor.Next() {
248✔
1744
                        keys = append(keys, k)
91✔
1745
                }
91✔
1746

1747
                for _, k := range keys {
248✔
1748
                        edgeInfo, err := c.delChannelEdgeUnsafe(
91✔
1749
                                edges, edgeIndex, chanIndex, zombieIndex,
91✔
1750
                                k, false, false,
91✔
1751
                        )
91✔
1752
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
91✔
1753
                                return err
×
1754
                        }
×
1755

1756
                        removedChans = append(removedChans, edgeInfo)
91✔
1757
                }
1758

1759
                // Delete all the entries in the prune log having a height
1760
                // greater or equal to the block disconnected.
1761
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
157✔
1762
                if err != nil {
157✔
1763
                        return err
×
1764
                }
×
1765

1766
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
157✔
1767
                        pruneLogBucket,
157✔
1768
                )
157✔
1769
                if err != nil {
157✔
1770
                        return err
×
1771
                }
×
1772

1773
                var pruneKeyStart [4]byte
157✔
1774
                byteOrder.PutUint32(pruneKeyStart[:], height)
157✔
1775

157✔
1776
                var pruneKeyEnd [4]byte
157✔
1777
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
157✔
1778

157✔
1779
                // To avoid modifying the bucket while traversing, we delete
157✔
1780
                // the keys in a second loop.
157✔
1781
                var pruneKeys [][]byte
157✔
1782
                pruneCursor := pruneBucket.ReadWriteCursor()
157✔
1783
                //nolint:ll
157✔
1784
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
157✔
1785
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
252✔
1786
                        pruneKeys = append(pruneKeys, k)
95✔
1787
                }
95✔
1788

1789
                for _, k := range pruneKeys {
252✔
1790
                        if err := pruneBucket.Delete(k); err != nil {
95✔
1791
                                return err
×
1792
                        }
×
1793
                }
1794

1795
                return nil
157✔
1796
        }, func() {
157✔
1797
                removedChans = nil
157✔
1798
        }); err != nil {
157✔
1799
                return nil, err
×
1800
        }
×
1801

1802
        for _, channel := range removedChans {
248✔
1803
                c.rejectCache.remove(channel.ChannelID)
91✔
1804
                c.chanCache.remove(channel.ChannelID)
91✔
1805
        }
91✔
1806

1807
        return removedChans, nil
157✔
1808
}
1809

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

56✔
1820
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
112✔
1821
                graphMeta := tx.ReadBucket(graphMetaBucket)
56✔
1822
                if graphMeta == nil {
56✔
1823
                        return ErrGraphNotFound
×
1824
                }
×
1825
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
56✔
1826
                if pruneBucket == nil {
56✔
1827
                        return ErrGraphNeverPruned
×
1828
                }
×
1829

1830
                pruneCursor := pruneBucket.ReadCursor()
56✔
1831

56✔
1832
                // The prune key with the largest block height will be our
56✔
1833
                // prune tip.
56✔
1834
                k, v := pruneCursor.Last()
56✔
1835
                if k == nil {
77✔
1836
                        return ErrGraphNeverPruned
21✔
1837
                }
21✔
1838

1839
                // Once we have the prune tip, the value will be the block hash,
1840
                // and the key the block height.
1841
                copy(tipHash[:], v)
38✔
1842
                tipHeight = byteOrder.Uint32(k)
38✔
1843

38✔
1844
                return nil
38✔
1845
        }, func() {})
56✔
1846
        if err != nil {
77✔
1847
                return nil, 0, err
21✔
1848
        }
21✔
1849

1850
        return &tipHash, tipHeight, nil
38✔
1851
}
1852

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

150✔
1864
        // TODO(roasbeef): possibly delete from node bucket if node has no more
150✔
1865
        // channels
150✔
1866
        // TODO(roasbeef): don't delete both edges?
150✔
1867

150✔
1868
        c.cacheMu.Lock()
150✔
1869
        defer c.cacheMu.Unlock()
150✔
1870

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

1894
                var rawChanID [8]byte
150✔
1895
                for _, chanID := range chanIDs {
239✔
1896
                        byteOrder.PutUint64(rawChanID[:], chanID)
89✔
1897
                        edgeInfo, err := c.delChannelEdgeUnsafe(
89✔
1898
                                edges, edgeIndex, chanIndex, zombieIndex,
89✔
1899
                                rawChanID[:], markZombie, strictZombiePruning,
89✔
1900
                        )
89✔
1901
                        if err != nil {
150✔
1902
                                return err
61✔
1903
                        }
61✔
1904

1905
                        infos = append(infos, edgeInfo)
28✔
1906
                }
1907

1908
                return nil
89✔
1909
        }, func() {
150✔
1910
                infos = nil
150✔
1911
        })
150✔
1912
        if err != nil {
211✔
1913
                return nil, err
61✔
1914
        }
61✔
1915

1916
        for _, chanID := range chanIDs {
117✔
1917
                c.rejectCache.remove(chanID)
28✔
1918
                c.chanCache.remove(chanID)
28✔
1919
        }
28✔
1920

1921
        return infos, nil
89✔
1922
}
1923

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

1939
        return chanID, nil
4✔
1940
}
1941

1942
// getChanID returns the assigned channel ID for a given channel point.
1943
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
4✔
1944
        var b bytes.Buffer
4✔
1945
        if err := WriteOutpoint(&b, chanPoint); err != nil {
4✔
1946
                return 0, err
×
1947
        }
×
1948

1949
        edges := tx.ReadBucket(edgeBucket)
4✔
1950
        if edges == nil {
4✔
1951
                return 0, ErrGraphNoEdgesFound
×
1952
        }
×
1953
        chanIndex := edges.NestedReadBucket(channelPointBucket)
4✔
1954
        if chanIndex == nil {
4✔
1955
                return 0, ErrGraphNoEdgesFound
×
1956
        }
×
1957

1958
        chanIDBytes := chanIndex.Get(b.Bytes())
4✔
1959
        if chanIDBytes == nil {
7✔
1960
                return 0, ErrEdgeNotFound
3✔
1961
        }
3✔
1962

1963
        chanID := byteOrder.Uint64(chanIDBytes)
4✔
1964

4✔
1965
        return chanID, nil
4✔
1966
}
1967

1968
// TODO(roasbeef): allow updates to use Batch?
1969

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

6✔
1976
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
1977
                edges := tx.ReadBucket(edgeBucket)
6✔
1978
                if edges == nil {
6✔
1979
                        return ErrGraphNoEdgesFound
×
1980
                }
×
1981
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
6✔
1982
                if edgeIndex == nil {
6✔
1983
                        return ErrGraphNoEdgesFound
×
1984
                }
×
1985

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

6✔
1990
                lastChanID, _ := cidCursor.Last()
6✔
1991

6✔
1992
                // If there's no key, then this means that we don't actually
6✔
1993
                // know of any channels, so we'll return a predicable error.
6✔
1994
                if lastChanID == nil {
10✔
1995
                        return ErrGraphNoEdgesFound
4✔
1996
                }
4✔
1997

1998
                // Otherwise, we'll de serialize the channel ID and return it
1999
                // to the caller.
2000
                cid = byteOrder.Uint64(lastChanID)
5✔
2001

5✔
2002
                return nil
5✔
2003
        }, func() {
6✔
2004
                cid = 0
6✔
2005
        })
6✔
2006
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
6✔
2007
                return 0, err
×
2008
        }
×
2009

2010
        return cid, nil
6✔
2011
}
2012

2013
// ChannelEdge represents the complete set of information for a channel edge in
2014
// the known channel graph. This struct couples the core information of the
2015
// edge as well as each of the known advertised edge policies.
2016
type ChannelEdge struct {
2017
        // Info contains all the static information describing the channel.
2018
        Info *models.ChannelEdgeInfo
2019

2020
        // Policy1 points to the "first" edge policy of the channel containing
2021
        // the dynamic information required to properly route through the edge.
2022
        Policy1 *models.ChannelEdgePolicy
2023

2024
        // Policy2 points to the "second" edge policy of the channel containing
2025
        // the dynamic information required to properly route through the edge.
2026
        Policy2 *models.ChannelEdgePolicy
2027

2028
        // Node1 is "node 1" in the channel. This is the node that would have
2029
        // produced Policy1 if it exists.
2030
        Node1 *models.LightningNode
2031

2032
        // Node2 is "node 2" in the channel. This is the node that would have
2033
        // produced Policy2 if it exists.
2034
        Node2 *models.LightningNode
2035
}
2036

2037
// ChanUpdatesInHorizon returns all the known channel edges which have at least
2038
// one edge that has an update timestamp within the specified horizon.
2039
func (c *KVStore) ChanUpdatesInHorizon(startTime,
2040
        endTime time.Time) ([]ChannelEdge, error) {
144✔
2041

144✔
2042
        // To ensure we don't return duplicate ChannelEdges, we'll use an
144✔
2043
        // additional map to keep track of the edges already seen to prevent
144✔
2044
        // re-adding it.
144✔
2045
        var edgesSeen map[uint64]struct{}
144✔
2046
        var edgesToCache map[uint64]ChannelEdge
144✔
2047
        var edgesInHorizon []ChannelEdge
144✔
2048

144✔
2049
        c.cacheMu.Lock()
144✔
2050
        defer c.cacheMu.Unlock()
144✔
2051

144✔
2052
        var hits int
144✔
2053
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
288✔
2054
                edges := tx.ReadBucket(edgeBucket)
144✔
2055
                if edges == nil {
144✔
2056
                        return ErrGraphNoEdgesFound
×
2057
                }
×
2058
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
144✔
2059
                if edgeIndex == nil {
144✔
2060
                        return ErrGraphNoEdgesFound
×
2061
                }
×
2062
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
144✔
2063
                if edgeUpdateIndex == nil {
144✔
2064
                        return ErrGraphNoEdgesFound
×
2065
                }
×
2066

2067
                nodes := tx.ReadBucket(nodeBucket)
144✔
2068
                if nodes == nil {
144✔
2069
                        return ErrGraphNodesNotFound
×
2070
                }
×
2071

2072
                // We'll now obtain a cursor to perform a range query within
2073
                // the index to find all channels within the horizon.
2074
                updateCursor := edgeUpdateIndex.ReadCursor()
144✔
2075

144✔
2076
                var startTimeBytes, endTimeBytes [8 + 8]byte
144✔
2077
                byteOrder.PutUint64(
144✔
2078
                        startTimeBytes[:8], uint64(startTime.Unix()),
144✔
2079
                )
144✔
2080
                byteOrder.PutUint64(
144✔
2081
                        endTimeBytes[:8], uint64(endTime.Unix()),
144✔
2082
                )
144✔
2083

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

49✔
2095
                        // If we've already retrieved the info and policies for
49✔
2096
                        // this edge, then we can skip it as we don't need to do
49✔
2097
                        // so again.
49✔
2098
                        chanIDInt := byteOrder.Uint64(chanID)
49✔
2099
                        if _, ok := edgesSeen[chanIDInt]; ok {
68✔
2100
                                continue
19✔
2101
                        }
2102

2103
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
42✔
2104
                                hits++
12✔
2105
                                edgesSeen[chanIDInt] = struct{}{}
12✔
2106
                                edgesInHorizon = append(edgesInHorizon, channel)
12✔
2107

12✔
2108
                                continue
12✔
2109
                        }
2110

2111
                        // First, we'll fetch the static edge information.
2112
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
21✔
2113
                        if err != nil {
21✔
2114
                                chanID := byteOrder.Uint64(chanID)
×
2115
                                return fmt.Errorf("unable to fetch info for "+
×
2116
                                        "edge with chan_id=%v: %v", chanID, err)
×
2117
                        }
×
2118

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

2131
                        node1, err := fetchLightningNode(
21✔
2132
                                nodes, edgeInfo.NodeKey1Bytes[:],
21✔
2133
                        )
21✔
2134
                        if err != nil {
21✔
2135
                                return err
×
2136
                        }
×
2137

2138
                        node2, err := fetchLightningNode(
21✔
2139
                                nodes, edgeInfo.NodeKey2Bytes[:],
21✔
2140
                        )
21✔
2141
                        if err != nil {
21✔
2142
                                return err
×
2143
                        }
×
2144

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

2159
                return nil
144✔
2160
        }, func() {
144✔
2161
                edgesSeen = make(map[uint64]struct{})
144✔
2162
                edgesToCache = make(map[uint64]ChannelEdge)
144✔
2163
                edgesInHorizon = nil
144✔
2164
        })
144✔
2165
        switch {
144✔
2166
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2167
                fallthrough
×
2168
        case errors.Is(err, ErrGraphNodesNotFound):
×
2169
                break
×
2170

2171
        case err != nil:
×
2172
                return nil, err
×
2173
        }
2174

2175
        // Insert any edges loaded from disk into the cache.
2176
        for chanid, channel := range edgesToCache {
165✔
2177
                c.chanCache.insert(chanid, channel)
21✔
2178
        }
21✔
2179

2180
        if len(edgesInHorizon) > 0 {
152✔
2181
                log.Debugf("ChanUpdatesInHorizon hit percentage: %.2f (%d/%d)",
8✔
2182
                        float64(hits)*100/float64(len(edgesInHorizon)), hits,
8✔
2183
                        len(edgesInHorizon))
8✔
2184
        } else {
147✔
2185
                log.Debugf("ChanUpdatesInHorizon returned no edges in "+
139✔
2186
                        "horizon (%s, %s)", startTime, endTime)
139✔
2187
        }
139✔
2188

2189
        return edgesInHorizon, nil
144✔
2190
}
2191

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

11✔
2199
        var nodesInHorizon []models.LightningNode
11✔
2200

11✔
2201
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
22✔
2202
                nodes := tx.ReadBucket(nodeBucket)
11✔
2203
                if nodes == nil {
11✔
2204
                        return ErrGraphNodesNotFound
×
2205
                }
×
2206

2207
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
11✔
2208
                if nodeUpdateIndex == nil {
11✔
2209
                        return ErrGraphNodesNotFound
×
2210
                }
×
2211

2212
                // We'll now obtain a cursor to perform a range query within
2213
                // the index to find all node announcements within the horizon.
2214
                updateCursor := nodeUpdateIndex.ReadCursor()
11✔
2215

11✔
2216
                var startTimeBytes, endTimeBytes [8 + 33]byte
11✔
2217
                byteOrder.PutUint64(
11✔
2218
                        startTimeBytes[:8], uint64(startTime.Unix()),
11✔
2219
                )
11✔
2220
                byteOrder.PutUint64(
11✔
2221
                        endTimeBytes[:8], uint64(endTime.Unix()),
11✔
2222
                )
11✔
2223

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

2237
                        nodesInHorizon = append(nodesInHorizon, node)
32✔
2238
                }
2239

2240
                return nil
11✔
2241
        }, func() {
11✔
2242
                nodesInHorizon = nil
11✔
2243
        })
11✔
2244
        switch {
11✔
2245
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2246
                fallthrough
×
2247
        case errors.Is(err, ErrGraphNodesNotFound):
×
2248
                break
×
2249

2250
        case err != nil:
×
2251
                return nil, err
×
2252
        }
2253

2254
        return nodesInHorizon, nil
11✔
2255
}
2256

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

128✔
2266
        var (
128✔
2267
                newChanIDs   []uint64
128✔
2268
                knownZombies []ChannelUpdateInfo
128✔
2269
        )
128✔
2270

128✔
2271
        c.cacheMu.Lock()
128✔
2272
        defer c.cacheMu.Unlock()
128✔
2273

128✔
2274
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
256✔
2275
                edges := tx.ReadBucket(edgeBucket)
128✔
2276
                if edges == nil {
128✔
2277
                        return ErrGraphNoEdgesFound
×
2278
                }
×
2279
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
128✔
2280
                if edgeIndex == nil {
128✔
2281
                        return ErrGraphNoEdgesFound
×
2282
                }
×
2283

2284
                // Fetch the zombie index, it may not exist if no edges have
2285
                // ever been marked as zombies. If the index has been
2286
                // initialized, we will use it later to skip known zombie edges.
2287
                zombieIndex := edges.NestedReadBucket(zombieBucket)
128✔
2288

128✔
2289
                // We'll run through the set of chanIDs and collate only the
128✔
2290
                // set of channel that are unable to be found within our db.
128✔
2291
                var cidBytes [8]byte
128✔
2292
                for _, info := range chansInfo {
231✔
2293
                        scid := info.ShortChannelID.ToUint64()
103✔
2294
                        byteOrder.PutUint64(cidBytes[:], scid)
103✔
2295

103✔
2296
                        // If the edge is already known, skip it.
103✔
2297
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
123✔
2298
                                continue
20✔
2299
                        }
2300

2301
                        // If the edge is a known zombie, skip it.
2302
                        if zombieIndex != nil {
172✔
2303
                                isZombie, _, _ := isZombieEdge(
86✔
2304
                                        zombieIndex, scid,
86✔
2305
                                )
86✔
2306

86✔
2307
                                if isZombie {
126✔
2308
                                        knownZombies = append(
40✔
2309
                                                knownZombies, info,
40✔
2310
                                        )
40✔
2311

40✔
2312
                                        continue
40✔
2313
                                }
2314
                        }
2315

2316
                        newChanIDs = append(newChanIDs, scid)
46✔
2317
                }
2318

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

2333
                return ogChanIDs, nil, nil
×
2334

2335
        case err != nil:
×
2336
                return nil, nil, err
×
2337
        }
2338

2339
        return newChanIDs, knownZombies, nil
128✔
2340
}
2341

2342
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2343
// latest received channel updates for the channel.
2344
type ChannelUpdateInfo struct {
2345
        // ShortChannelID is the SCID identifier of the channel.
2346
        ShortChannelID lnwire.ShortChannelID
2347

2348
        // Node1UpdateTimestamp is the timestamp of the latest received update
2349
        // from the node 1 channel peer. This will be set to zero time if no
2350
        // update has yet been received from this node.
2351
        Node1UpdateTimestamp time.Time
2352

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

2359
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2360
// timestamps with zero seconds unix timestamp which equals
2361
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2362
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2363
        node2Timestamp time.Time) ChannelUpdateInfo {
199✔
2364

199✔
2365
        chanInfo := ChannelUpdateInfo{
199✔
2366
                ShortChannelID:       scid,
199✔
2367
                Node1UpdateTimestamp: node1Timestamp,
199✔
2368
                Node2UpdateTimestamp: node2Timestamp,
199✔
2369
        }
199✔
2370

199✔
2371
        if node1Timestamp.IsZero() {
388✔
2372
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
189✔
2373
        }
189✔
2374

2375
        if node2Timestamp.IsZero() {
388✔
2376
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
189✔
2377
        }
189✔
2378

2379
        return chanInfo
199✔
2380
}
2381

2382
// BlockChannelRange represents a range of channels for a given block height.
2383
type BlockChannelRange struct {
2384
        // Height is the height of the block all of the channels below were
2385
        // included in.
2386
        Height uint32
2387

2388
        // Channels is the list of channels identified by their short ID
2389
        // representation known to us that were included in the block height
2390
        // above. The list may include channel update timestamp information if
2391
        // requested.
2392
        Channels []ChannelUpdateInfo
2393
}
2394

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

14✔
2405
        startChanID := &lnwire.ShortChannelID{
14✔
2406
                BlockHeight: startHeight,
14✔
2407
        }
14✔
2408

14✔
2409
        endChanID := lnwire.ShortChannelID{
14✔
2410
                BlockHeight: endHeight,
14✔
2411
                TxIndex:     math.MaxUint32 & 0x00ffffff,
14✔
2412
                TxPosition:  math.MaxUint16,
14✔
2413
        }
14✔
2414

14✔
2415
        // As we need to perform a range scan, we'll convert the starting and
14✔
2416
        // ending height to their corresponding values when encoded using short
14✔
2417
        // channel ID's.
14✔
2418
        var chanIDStart, chanIDEnd [8]byte
14✔
2419
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
14✔
2420
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
14✔
2421

14✔
2422
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
14✔
2423
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
2424
                edges := tx.ReadBucket(edgeBucket)
14✔
2425
                if edges == nil {
14✔
2426
                        return ErrGraphNoEdgesFound
×
2427
                }
×
2428
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
2429
                if edgeIndex == nil {
14✔
2430
                        return ErrGraphNoEdgesFound
×
2431
                }
×
2432

2433
                cursor := edgeIndex.ReadCursor()
14✔
2434

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

2448
                        if edgeInfo.AuthProof == nil {
50✔
2449
                                continue
3✔
2450
                        }
2451

2452
                        // This channel ID rests within the target range, so
2453
                        // we'll add it to our returned set.
2454
                        rawCid := byteOrder.Uint64(k)
47✔
2455
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
47✔
2456

47✔
2457
                        chanInfo := NewChannelUpdateInfo(
47✔
2458
                                cid, time.Time{}, time.Time{},
47✔
2459
                        )
47✔
2460

47✔
2461
                        if !withTimestamps {
69✔
2462
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2463
                                        channelsPerBlock[cid.BlockHeight],
22✔
2464
                                        chanInfo,
22✔
2465
                                )
22✔
2466

22✔
2467
                                continue
22✔
2468
                        }
2469

2470
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
25✔
2471

25✔
2472
                        rawPolicy := edges.Get(node1Key)
25✔
2473
                        if len(rawPolicy) != 0 {
34✔
2474
                                r := bytes.NewReader(rawPolicy)
9✔
2475

9✔
2476
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2477
                                if err != nil && !errors.Is(
9✔
2478
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2479
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
9✔
2480

×
2481
                                        return err
×
2482
                                }
×
2483

2484
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2485
                        }
2486

2487
                        rawPolicy = edges.Get(node2Key)
25✔
2488
                        if len(rawPolicy) != 0 {
39✔
2489
                                r := bytes.NewReader(rawPolicy)
14✔
2490

14✔
2491
                                edge, err := deserializeChanEdgePolicyRaw(r)
14✔
2492
                                if err != nil && !errors.Is(
14✔
2493
                                        err, ErrEdgePolicyOptionalFieldNotFound,
14✔
2494
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
14✔
2495

×
2496
                                        return err
×
2497
                                }
×
2498

2499
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
14✔
2500
                        }
2501

2502
                        channelsPerBlock[cid.BlockHeight] = append(
25✔
2503
                                channelsPerBlock[cid.BlockHeight], chanInfo,
25✔
2504
                        )
25✔
2505
                }
2506

2507
                return nil
14✔
2508
        }, func() {
14✔
2509
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
14✔
2510
        })
14✔
2511

2512
        switch {
14✔
2513
        // If we don't know of any channels yet, then there's nothing to
2514
        // filter, so we'll return an empty slice.
2515
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
6✔
2516
                return nil, nil
6✔
2517

2518
        case err != nil:
×
2519
                return nil, err
×
2520
        }
2521

2522
        // Return the channel ranges in ascending block height order.
2523
        blocks := make([]uint32, 0, len(channelsPerBlock))
11✔
2524
        for block := range channelsPerBlock {
36✔
2525
                blocks = append(blocks, block)
25✔
2526
        }
25✔
2527
        sort.Slice(blocks, func(i, j int) bool {
41✔
2528
                return blocks[i] < blocks[j]
30✔
2529
        })
30✔
2530

2531
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
11✔
2532
        for _, block := range blocks {
36✔
2533
                channelRanges = append(channelRanges, BlockChannelRange{
25✔
2534
                        Height:   block,
25✔
2535
                        Channels: channelsPerBlock[block],
25✔
2536
                })
25✔
2537
        }
25✔
2538

2539
        return channelRanges, nil
11✔
2540
}
2541

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

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

7✔
2563
        var (
7✔
2564
                chanEdges []ChannelEdge
7✔
2565
                cidBytes  [8]byte
7✔
2566
        )
7✔
2567

7✔
2568
        fetchChanInfos := func(tx kvdb.RTx) error {
14✔
2569
                edges := tx.ReadBucket(edgeBucket)
7✔
2570
                if edges == nil {
7✔
2571
                        return ErrGraphNoEdgesFound
×
2572
                }
×
2573
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
7✔
2574
                if edgeIndex == nil {
7✔
2575
                        return ErrGraphNoEdgesFound
×
2576
                }
×
2577
                nodes := tx.ReadBucket(nodeBucket)
7✔
2578
                if nodes == nil {
7✔
2579
                        return ErrGraphNotFound
×
2580
                }
×
2581

2582
                for _, cid := range chanIDs {
21✔
2583
                        byteOrder.PutUint64(cidBytes[:], cid)
14✔
2584

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

2598
                        // With the static information obtained, we'll now
2599
                        // fetch the dynamic policy info.
2600
                        edge1, edge2, err := fetchChanEdgePolicies(
11✔
2601
                                edgeIndex, edges, cidBytes[:],
11✔
2602
                        )
11✔
2603
                        if err != nil {
11✔
2604
                                return err
×
2605
                        }
×
2606

2607
                        node1, err := fetchLightningNode(
11✔
2608
                                nodes, edgeInfo.NodeKey1Bytes[:],
11✔
2609
                        )
11✔
2610
                        if err != nil {
11✔
2611
                                return err
×
2612
                        }
×
2613

2614
                        node2, err := fetchLightningNode(
11✔
2615
                                nodes, edgeInfo.NodeKey2Bytes[:],
11✔
2616
                        )
11✔
2617
                        if err != nil {
11✔
2618
                                return err
×
2619
                        }
×
2620

2621
                        chanEdges = append(chanEdges, ChannelEdge{
11✔
2622
                                Info:    &edgeInfo,
11✔
2623
                                Policy1: edge1,
11✔
2624
                                Policy2: edge2,
11✔
2625
                                Node1:   &node1,
11✔
2626
                                Node2:   &node2,
11✔
2627
                        })
11✔
2628
                }
2629

2630
                return nil
7✔
2631
        }
2632

2633
        if tx == nil {
14✔
2634
                err := kvdb.View(c.db, fetchChanInfos, func() {
14✔
2635
                        chanEdges = nil
7✔
2636
                })
7✔
2637
                if err != nil {
7✔
2638
                        return nil, err
×
2639
                }
×
2640

2641
                return chanEdges, nil
7✔
2642
        }
2643

2644
        err := fetchChanInfos(tx)
×
2645
        if err != nil {
×
2646
                return nil, err
×
2647
        }
×
2648

2649
        return chanEdges, nil
×
2650
}
2651

2652
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2653
        edge1, edge2 *models.ChannelEdgePolicy) error {
137✔
2654

137✔
2655
        // First, we'll fetch the edge update index bucket which currently
137✔
2656
        // stores an entry for the channel we're about to delete.
137✔
2657
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
137✔
2658
        if updateIndex == nil {
137✔
2659
                // No edges in bucket, return early.
×
2660
                return nil
×
2661
        }
×
2662

2663
        // Now that we have the bucket, we'll attempt to construct a template
2664
        // for the index key: updateTime || chanid.
2665
        var indexKey [8 + 8]byte
137✔
2666
        byteOrder.PutUint64(indexKey[8:], chanID)
137✔
2667

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

2680
        // We'll also attempt to delete the entry that may have been created by
2681
        // the second edge.
2682
        if edge2 != nil {
152✔
2683
                byteOrder.PutUint64(
15✔
2684
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
15✔
2685
                )
15✔
2686
                if err := updateIndex.Delete(indexKey[:]); err != nil {
15✔
2687
                        return err
×
2688
                }
×
2689
        }
2690

2691
        return nil
137✔
2692
}
2693

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

198✔
2705
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
198✔
2706
        if err != nil {
259✔
2707
                return nil, err
61✔
2708
        }
61✔
2709

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

2723
        // The edge key is of the format pubKey || chanID. First we construct
2724
        // the latter half, populating the channel ID.
2725
        var edgeKey [33 + 8]byte
137✔
2726
        copy(edgeKey[33:], chanID)
137✔
2727

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

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

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

2769
        // Finally, we'll mark the edge as a zombie within our index if it's
2770
        // being removed due to the channel becoming a zombie. We do this to
2771
        // ensure we don't store unnecessary data for spent channels.
2772
        if !isZombie {
250✔
2773
                return &edgeInfo, nil
113✔
2774
        }
113✔
2775

2776
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
27✔
2777
        if strictZombie {
30✔
2778
                var e1UpdateTime, e2UpdateTime *time.Time
3✔
2779
                if edge1 != nil {
5✔
2780
                        e1UpdateTime = &edge1.LastUpdate
2✔
2781
                }
2✔
2782
                if edge2 != nil {
6✔
2783
                        e2UpdateTime = &edge2.LastUpdate
3✔
2784
                }
3✔
2785

2786
                nodeKey1, nodeKey2 = makeZombiePubkeys(
3✔
2787
                        &edgeInfo, e1UpdateTime, e2UpdateTime,
3✔
2788
                )
3✔
2789
        }
2790

2791
        return &edgeInfo, markEdgeZombie(
27✔
2792
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
27✔
2793
        )
27✔
2794
}
2795

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

3✔
2815
        switch {
3✔
2816
        // If we don't have either edge policy, we'll return both pubkeys so
2817
        // that the channel can be resurrected by either party.
UNCOV
2818
        case e1 == nil && e2 == nil:
×
UNCOV
2819
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2820

2821
        // If we're missing edge1, or if both edges are present but edge1 is
2822
        // older, we'll return edge1's pubkey and a blank pubkey for edge2. This
2823
        // means that only an update from edge1 will be able to resurrect the
2824
        // channel.
2825
        case e1 == nil || (e2 != nil && e1.Before(*e2)):
1✔
2826
                return info.NodeKey1Bytes, [33]byte{}
1✔
2827

2828
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2829
        // return a blank pubkey for edge1. In this case, only an update from
2830
        // edge2 can resurect the channel.
2831
        default:
2✔
2832
                return [33]byte{}, info.NodeKey2Bytes
2✔
2833
        }
2834
}
2835

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

2,675✔
2847
        var (
2,675✔
2848
                isUpdate1    bool
2,675✔
2849
                edgeNotFound bool
2,675✔
2850
                from, to     route.Vertex
2,675✔
2851
        )
2,675✔
2852

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

2871
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
2,674✔
2872
                        if err != nil {
2,678✔
2873
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
4✔
2874
                        }
4✔
2875

2876
                        // Silence ErrEdgeNotFound so that the batch can
2877
                        // succeed, but propagate the error via local state.
2878
                        if errors.Is(err, ErrEdgeNotFound) {
2,678✔
2879
                                edgeNotFound = true
4✔
2880
                                return nil
4✔
2881
                        }
4✔
2882

2883
                        return err
2,670✔
2884
                },
2885
                OnCommit: func(err error) error {
2,675✔
2886
                        switch {
2,675✔
2887
                        case err != nil:
1✔
2888
                                return err
1✔
2889
                        case edgeNotFound:
4✔
2890
                                return ErrEdgeNotFound
4✔
2891
                        default:
2,670✔
2892
                                c.updateEdgeCache(edge, isUpdate1)
2,670✔
2893
                                return nil
2,670✔
2894
                        }
2895
                },
2896
        }
2897

2898
        err := c.chanScheduler.Execute(ctx, r)
2,675✔
2899

2,675✔
2900
        return from, to, err
2,675✔
2901
}
2902

2903
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2904
        isUpdate1 bool) {
2,670✔
2905

2,670✔
2906
        // If an entry for this channel is found in reject cache, we'll modify
2,670✔
2907
        // the entry with the updated timestamp for the direction that was just
2,670✔
2908
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,670✔
2909
        // during the next query for this edge.
2,670✔
2910
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,678✔
2911
                if isUpdate1 {
14✔
2912
                        entry.upd1Time = e.LastUpdate.Unix()
6✔
2913
                } else {
11✔
2914
                        entry.upd2Time = e.LastUpdate.Unix()
5✔
2915
                }
5✔
2916
                c.rejectCache.insert(e.ChannelID, entry)
8✔
2917
        }
2918

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

2933
// updateEdgePolicy attempts to update an edge's policy within the relevant
2934
// buckets using an existing database transaction. The returned boolean will be
2935
// true if the updated policy belongs to node1, and false if the policy belonged
2936
// to node2.
2937
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
2938
        route.Vertex, route.Vertex, bool, error) {
2,674✔
2939

2,674✔
2940
        var noVertex route.Vertex
2,674✔
2941

2,674✔
2942
        edges := tx.ReadWriteBucket(edgeBucket)
2,674✔
2943
        if edges == nil {
2,674✔
2944
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2945
        }
×
2946
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,674✔
2947
        if edgeIndex == nil {
2,674✔
2948
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2949
        }
×
2950

2951
        // Create the channelID key be converting the channel ID
2952
        // integer into a byte slice.
2953
        var chanID [8]byte
2,674✔
2954
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,674✔
2955

2,674✔
2956
        // With the channel ID, we then fetch the value storing the two
2,674✔
2957
        // nodes which connect this channel edge.
2,674✔
2958
        nodeInfo := edgeIndex.Get(chanID[:])
2,674✔
2959
        if nodeInfo == nil {
2,678✔
2960
                return noVertex, noVertex, false, ErrEdgeNotFound
4✔
2961
        }
4✔
2962

2963
        // Depending on the flags value passed above, either the first
2964
        // or second edge policy is being updated.
2965
        var fromNode, toNode []byte
2,670✔
2966
        var isUpdate1 bool
2,670✔
2967
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
4,010✔
2968
                fromNode = nodeInfo[:33]
1,340✔
2969
                toNode = nodeInfo[33:66]
1,340✔
2970
                isUpdate1 = true
1,340✔
2971
        } else {
2,673✔
2972
                fromNode = nodeInfo[33:66]
1,333✔
2973
                toNode = nodeInfo[:33]
1,333✔
2974
                isUpdate1 = false
1,333✔
2975
        }
1,333✔
2976

2977
        // Finally, with the direction of the edge being updated
2978
        // identified, we update the on-disk edge representation.
2979
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,670✔
2980
        if err != nil {
2,670✔
2981
                return noVertex, noVertex, false, err
×
2982
        }
×
2983

2984
        var (
2,670✔
2985
                fromNodePubKey route.Vertex
2,670✔
2986
                toNodePubKey   route.Vertex
2,670✔
2987
        )
2,670✔
2988
        copy(fromNodePubKey[:], fromNode)
2,670✔
2989
        copy(toNodePubKey[:], toNode)
2,670✔
2990

2,670✔
2991
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
2,670✔
2992
}
2993

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

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

13✔
3010
                // If this edge doesn't extend to the source node, we'll
13✔
3011
                // terminate our search as we can now conclude that the node is
13✔
3012
                // publicly advertised within the graph due to the local node
13✔
3013
                // knowing of the current edge.
13✔
3014
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
13✔
3015
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
19✔
3016

6✔
3017
                        nodeIsPublic = true
6✔
3018
                        return errDone
6✔
3019
                }
6✔
3020

3021
                // Since the edge _does_ extend to the source node, we'll also
3022
                // need to ensure that this is a public edge.
3023
                if info.AuthProof != nil {
19✔
3024
                        nodeIsPublic = true
9✔
3025
                        return errDone
9✔
3026
                }
9✔
3027

3028
                // Otherwise, we'll continue our search.
3029
                return nil
4✔
3030
        }, func() {
×
3031
                nodeIsPublic = false
×
3032
        })
×
3033
        if err != nil && !errors.Is(err, errDone) {
16✔
3034
                return false, err
×
3035
        }
×
3036

3037
        return nodeIsPublic, nil
16✔
3038
}
3039

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

3,654✔
3047
        return c.fetchLightningNode(tx, nodePub)
3,654✔
3048
}
3,654✔
3049

3050
// FetchLightningNode attempts to look up a target node by its identity public
3051
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3052
// returned.
3053
func (c *KVStore) FetchLightningNode(_ context.Context,
3054
        nodePub route.Vertex) (*models.LightningNode, error) {
162✔
3055

162✔
3056
        return c.fetchLightningNode(nil, nodePub)
162✔
3057
}
162✔
3058

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

3,813✔
3066
        var node *models.LightningNode
3,813✔
3067
        fetch := func(tx kvdb.RTx) error {
7,626✔
3068
                // First grab the nodes bucket which stores the mapping from
3,813✔
3069
                // pubKey to node information.
3,813✔
3070
                nodes := tx.ReadBucket(nodeBucket)
3,813✔
3071
                if nodes == nil {
3,813✔
3072
                        return ErrGraphNotFound
×
3073
                }
×
3074

3075
                // If a key for this serialized public key isn't found, then
3076
                // the target node doesn't exist within the database.
3077
                nodeBytes := nodes.Get(nodePub[:])
3,813✔
3078
                if nodeBytes == nil {
3,831✔
3079
                        return ErrGraphNodeNotFound
18✔
3080
                }
18✔
3081

3082
                // If the node is found, then we can de deserialize the node
3083
                // information to return to the user.
3084
                nodeReader := bytes.NewReader(nodeBytes)
3,798✔
3085
                n, err := deserializeLightningNode(nodeReader)
3,798✔
3086
                if err != nil {
3,798✔
3087
                        return err
×
3088
                }
×
3089

3090
                node = &n
3,798✔
3091

3,798✔
3092
                return nil
3,798✔
3093
        }
3094

3095
        if tx == nil {
3,999✔
3096
                err := kvdb.View(
186✔
3097
                        c.db, fetch, func() {
372✔
3098
                                node = nil
186✔
3099
                        },
186✔
3100
                )
3101
                if err != nil {
193✔
3102
                        return nil, err
7✔
3103
                }
7✔
3104

3105
                return node, nil
182✔
3106
        }
3107

3108
        err := fetch(tx)
3,627✔
3109
        if err != nil {
3,638✔
3110
                return nil, err
11✔
3111
        }
11✔
3112

3113
        return node, nil
3,616✔
3114
}
3115

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

20✔
3124
        var (
20✔
3125
                updateTime time.Time
20✔
3126
                exists     bool
20✔
3127
        )
20✔
3128

20✔
3129
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
40✔
3130
                // First grab the nodes bucket which stores the mapping from
20✔
3131
                // pubKey to node information.
20✔
3132
                nodes := tx.ReadBucket(nodeBucket)
20✔
3133
                if nodes == nil {
20✔
3134
                        return ErrGraphNotFound
×
3135
                }
×
3136

3137
                // If a key for this serialized public key isn't found, we can
3138
                // exit early.
3139
                nodeBytes := nodes.Get(nodePub[:])
20✔
3140
                if nodeBytes == nil {
26✔
3141
                        exists = false
6✔
3142
                        return nil
6✔
3143
                }
6✔
3144

3145
                // Otherwise we continue on to obtain the time stamp
3146
                // representing the last time the data for this node was
3147
                // updated.
3148
                nodeReader := bytes.NewReader(nodeBytes)
17✔
3149
                node, err := deserializeLightningNode(nodeReader)
17✔
3150
                if err != nil {
17✔
3151
                        return err
×
3152
                }
×
3153

3154
                exists = true
17✔
3155
                updateTime = node.LastUpdate
17✔
3156

17✔
3157
                return nil
17✔
3158
        }, func() {
20✔
3159
                updateTime = time.Time{}
20✔
3160
                exists = false
20✔
3161
        })
20✔
3162
        if err != nil {
20✔
3163
                return time.Time{}, exists, err
×
3164
        }
×
3165

3166
        return updateTime, exists, nil
20✔
3167
}
3168

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

1,270✔
3179
        traversal := func(tx kvdb.RTx) error {
2,540✔
3180
                edges := tx.ReadBucket(edgeBucket)
1,270✔
3181
                if edges == nil {
1,270✔
3182
                        return ErrGraphNotFound
×
3183
                }
×
3184
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,270✔
3185
                if edgeIndex == nil {
1,270✔
3186
                        return ErrGraphNoEdgesFound
×
3187
                }
×
3188

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

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

3216
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,845✔
3217
                                edges, chanID, nodePub,
3,845✔
3218
                        )
3,845✔
3219
                        if err != nil {
3,845✔
3220
                                return err
×
3221
                        }
×
3222

3223
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,845✔
3224
                        if err != nil {
3,845✔
3225
                                return err
×
3226
                        }
×
3227

3228
                        incomingPolicy, err := fetchChanEdgePolicy(
3,845✔
3229
                                edges, chanID, otherNode[:],
3,845✔
3230
                        )
3,845✔
3231
                        if err != nil {
3,845✔
3232
                                return err
×
3233
                        }
×
3234

3235
                        // Finally, we execute the callback.
3236
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,845✔
3237
                        if err != nil {
3,857✔
3238
                                return err
12✔
3239
                        }
12✔
3240
                }
3241

3242
                return nil
1,261✔
3243
        }
3244

3245
        // If no transaction was provided, then we'll create a new transaction
3246
        // to execute the transaction within.
3247
        if tx == nil {
1,302✔
3248
                return kvdb.View(db, traversal, reset)
32✔
3249
        }
32✔
3250

3251
        // Otherwise, we re-use the existing transaction to execute the graph
3252
        // traversal.
3253
        return traversal(tx)
1,241✔
3254
}
3255

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

9✔
3268
        return nodeTraversal(
9✔
3269
                nil, nodePub[:], c.db, func(_ kvdb.RTx,
9✔
3270
                        info *models.ChannelEdgeInfo, policy,
9✔
3271
                        policy2 *models.ChannelEdgePolicy) error {
22✔
3272

13✔
3273
                        return cb(info, policy, policy2)
13✔
3274
                }, reset,
13✔
3275
        )
3276
}
3277

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

4✔
3286
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3287
                nodes := tx.ReadBucket(nodeBucket)
4✔
3288
                if nodes == nil {
4✔
3289
                        return ErrGraphNotFound
×
3290
                }
×
3291

3292
                node, err := sourceNodeWithTx(nodes)
4✔
3293
                if err != nil {
4✔
3294
                        return err
×
3295
                }
×
3296

3297
                return nodeTraversal(
4✔
3298
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
4✔
3299
                                info *models.ChannelEdgeInfo,
4✔
3300
                                policy, _ *models.ChannelEdgePolicy) error {
9✔
3301

5✔
3302
                                peer, err := c.fetchOtherNode(
5✔
3303
                                        tx, info, node.PubKeyBytes[:],
5✔
3304
                                )
5✔
3305
                                if err != nil {
5✔
3306
                                        return err
×
3307
                                }
×
3308

3309
                                return cb(
5✔
3310
                                        info.ChannelPoint, policy != nil, peer,
5✔
3311
                                )
5✔
3312
                        }, reset,
3313
                )
3314
        }, reset)
3315
}
3316

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

1,001✔
3337
        return nodeTraversal(tx, nodePub[:], c.db, cb, reset)
1,001✔
3338
}
1,001✔
3339

3340
// fetchOtherNode attempts to fetch the full LightningNode that's opposite of
3341
// the target node in the channel. This is useful when one knows the pubkey of
3342
// one of the nodes, and wishes to obtain the full LightningNode for the other
3343
// end of the channel.
3344
func (c *KVStore) fetchOtherNode(tx kvdb.RTx,
3345
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3346
        *models.LightningNode, error) {
5✔
3347

5✔
3348
        // Ensure that the node passed in is actually a member of the channel.
5✔
3349
        var targetNodeBytes [33]byte
5✔
3350
        switch {
5✔
3351
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
5✔
3352
                targetNodeBytes = channel.NodeKey2Bytes
5✔
3353
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3354
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3355
        default:
×
3356
                return nil, fmt.Errorf("node not participating in this channel")
×
3357
        }
3358

3359
        var targetNode *models.LightningNode
5✔
3360
        fetchNodeFunc := func(tx kvdb.RTx) error {
10✔
3361
                // First grab the nodes bucket which stores the mapping from
5✔
3362
                // pubKey to node information.
5✔
3363
                nodes := tx.ReadBucket(nodeBucket)
5✔
3364
                if nodes == nil {
5✔
3365
                        return ErrGraphNotFound
×
3366
                }
×
3367

3368
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
5✔
3369
                if err != nil {
5✔
3370
                        return err
×
3371
                }
×
3372

3373
                targetNode = &node
5✔
3374

5✔
3375
                return nil
5✔
3376
        }
3377

3378
        // If the transaction is nil, then we'll need to create a new one,
3379
        // otherwise we can use the existing db transaction.
3380
        var err error
5✔
3381
        if tx == nil {
5✔
3382
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3383
                        targetNode = nil
×
3384
                })
×
3385
        } else {
5✔
3386
                err = fetchNodeFunc(tx)
5✔
3387
        }
5✔
3388

3389
        return targetNode, err
5✔
3390
}
3391

3392
// computeEdgePolicyKeys is a helper function that can be used to compute the
3393
// keys used to index the channel edge policy info for the two nodes of the
3394
// edge. The keys for node 1 and node 2 are returned respectively.
3395
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
25✔
3396
        var (
25✔
3397
                node1Key [33 + 8]byte
25✔
3398
                node2Key [33 + 8]byte
25✔
3399
        )
25✔
3400

25✔
3401
        copy(node1Key[:], info.NodeKey1Bytes[:])
25✔
3402
        copy(node2Key[:], info.NodeKey2Bytes[:])
25✔
3403

25✔
3404
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
25✔
3405
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
25✔
3406

25✔
3407
        return node1Key[:], node2Key[:]
25✔
3408
}
25✔
3409

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

14✔
3419
        var (
14✔
3420
                edgeInfo *models.ChannelEdgeInfo
14✔
3421
                policy1  *models.ChannelEdgePolicy
14✔
3422
                policy2  *models.ChannelEdgePolicy
14✔
3423
        )
14✔
3424

14✔
3425
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
3426
                // First, grab the node bucket. This will be used to populate
14✔
3427
                // the Node pointers in each edge read from disk.
14✔
3428
                nodes := tx.ReadBucket(nodeBucket)
14✔
3429
                if nodes == nil {
14✔
3430
                        return ErrGraphNotFound
×
3431
                }
×
3432

3433
                // Next, grab the edge bucket which stores the edges, and also
3434
                // the index itself so we can group the directed edges together
3435
                // logically.
3436
                edges := tx.ReadBucket(edgeBucket)
14✔
3437
                if edges == nil {
14✔
3438
                        return ErrGraphNoEdgesFound
×
3439
                }
×
3440
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
3441
                if edgeIndex == nil {
14✔
3442
                        return ErrGraphNoEdgesFound
×
3443
                }
×
3444

3445
                // If the channel's outpoint doesn't exist within the outpoint
3446
                // index, then the edge does not exist.
3447
                chanIndex := edges.NestedReadBucket(channelPointBucket)
14✔
3448
                if chanIndex == nil {
14✔
3449
                        return ErrGraphNoEdgesFound
×
3450
                }
×
3451
                var b bytes.Buffer
14✔
3452
                if err := WriteOutpoint(&b, op); err != nil {
14✔
3453
                        return err
×
3454
                }
×
3455
                chanID := chanIndex.Get(b.Bytes())
14✔
3456
                if chanID == nil {
27✔
3457
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
13✔
3458
                }
13✔
3459

3460
                // If the channel is found to exists, then we'll first retrieve
3461
                // the general information for the channel.
3462
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
4✔
3463
                if err != nil {
4✔
3464
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3465
                }
×
3466
                edgeInfo = &edge
4✔
3467

4✔
3468
                // Once we have the information about the channels' parameters,
4✔
3469
                // we'll fetch the routing policies for each for the directed
4✔
3470
                // edges.
4✔
3471
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
4✔
3472
                if err != nil {
4✔
3473
                        return fmt.Errorf("failed to find policy: %w", err)
×
3474
                }
×
3475

3476
                policy1 = e1
4✔
3477
                policy2 = e2
4✔
3478

4✔
3479
                return nil
4✔
3480
        }, func() {
14✔
3481
                edgeInfo = nil
14✔
3482
                policy1 = nil
14✔
3483
                policy2 = nil
14✔
3484
        })
14✔
3485
        if err != nil {
27✔
3486
                return nil, nil, nil, err
13✔
3487
        }
13✔
3488

3489
        return edgeInfo, policy1, policy2, nil
4✔
3490
}
3491

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

2,692✔
3505
        var (
2,692✔
3506
                edgeInfo  *models.ChannelEdgeInfo
2,692✔
3507
                policy1   *models.ChannelEdgePolicy
2,692✔
3508
                policy2   *models.ChannelEdgePolicy
2,692✔
3509
                channelID [8]byte
2,692✔
3510
        )
2,692✔
3511

2,692✔
3512
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
5,384✔
3513
                // First, grab the node bucket. This will be used to populate
2,692✔
3514
                // the Node pointers in each edge read from disk.
2,692✔
3515
                nodes := tx.ReadBucket(nodeBucket)
2,692✔
3516
                if nodes == nil {
2,692✔
3517
                        return ErrGraphNotFound
×
3518
                }
×
3519

3520
                // Next, grab the edge bucket which stores the edges, and also
3521
                // the index itself so we can group the directed edges together
3522
                // logically.
3523
                edges := tx.ReadBucket(edgeBucket)
2,692✔
3524
                if edges == nil {
2,692✔
3525
                        return ErrGraphNoEdgesFound
×
3526
                }
×
3527
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
2,692✔
3528
                if edgeIndex == nil {
2,692✔
3529
                        return ErrGraphNoEdgesFound
×
3530
                }
×
3531

3532
                byteOrder.PutUint64(channelID[:], chanID)
2,692✔
3533

2,692✔
3534
                // Now, attempt to fetch edge.
2,692✔
3535
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
2,692✔
3536

2,692✔
3537
                // If it doesn't exist, we'll quickly check our zombie index to
2,692✔
3538
                // see if we've previously marked it as so.
2,692✔
3539
                if errors.Is(err, ErrEdgeNotFound) {
2,696✔
3540
                        // If the zombie index doesn't exist, or the edge is not
4✔
3541
                        // marked as a zombie within it, then we'll return the
4✔
3542
                        // original ErrEdgeNotFound error.
4✔
3543
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3544
                        if zombieIndex == nil {
4✔
3545
                                return ErrEdgeNotFound
×
3546
                        }
×
3547

3548
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
4✔
3549
                                zombieIndex, chanID,
4✔
3550
                        )
4✔
3551
                        if !isZombie {
7✔
3552
                                return ErrEdgeNotFound
3✔
3553
                        }
3✔
3554

3555
                        // Otherwise, the edge is marked as a zombie, so we'll
3556
                        // populate the edge info with the public keys of each
3557
                        // party as this is the only information we have about
3558
                        // it and return an error signaling so.
3559
                        edgeInfo = &models.ChannelEdgeInfo{
4✔
3560
                                NodeKey1Bytes: pubKey1,
4✔
3561
                                NodeKey2Bytes: pubKey2,
4✔
3562
                        }
4✔
3563

4✔
3564
                        return ErrZombieEdge
4✔
3565
                }
3566

3567
                // Otherwise, we'll just return the error if any.
3568
                if err != nil {
2,691✔
3569
                        return err
×
3570
                }
×
3571

3572
                edgeInfo = &edge
2,691✔
3573

2,691✔
3574
                // Then we'll attempt to fetch the accompanying policies of this
2,691✔
3575
                // edge.
2,691✔
3576
                e1, e2, err := fetchChanEdgePolicies(
2,691✔
3577
                        edgeIndex, edges, channelID[:],
2,691✔
3578
                )
2,691✔
3579
                if err != nil {
2,691✔
3580
                        return err
×
3581
                }
×
3582

3583
                policy1 = e1
2,691✔
3584
                policy2 = e2
2,691✔
3585

2,691✔
3586
                return nil
2,691✔
3587
        }, func() {
2,692✔
3588
                edgeInfo = nil
2,692✔
3589
                policy1 = nil
2,692✔
3590
                policy2 = nil
2,692✔
3591
        })
2,692✔
3592
        if errors.Is(err, ErrZombieEdge) {
2,696✔
3593
                return edgeInfo, nil, nil, err
4✔
3594
        }
4✔
3595
        if err != nil {
2,694✔
3596
                return nil, nil, nil, err
3✔
3597
        }
3✔
3598

3599
        return edgeInfo, policy1, policy2, nil
2,691✔
3600
}
3601

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

3621
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
16✔
3622

16✔
3623
                return err
16✔
3624
        }, func() {
16✔
3625
                nodeIsPublic = false
16✔
3626
        })
16✔
3627
        if err != nil {
16✔
3628
                return false, err
×
3629
        }
×
3630

3631
        return nodeIsPublic, nil
16✔
3632
}
3633

3634
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3635
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
49✔
3636
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
49✔
3637
        if err != nil {
49✔
3638
                return nil, err
×
3639
        }
×
3640

3641
        // With the witness script generated, we'll now turn it into a p2wsh
3642
        // script:
3643
        //  * OP_0 <sha256(script)>
3644
        bldr := txscript.NewScriptBuilder(
49✔
3645
                txscript.WithScriptAllocSize(input.P2WSHSize),
49✔
3646
        )
49✔
3647
        bldr.AddOp(txscript.OP_0)
49✔
3648
        scriptHash := sha256.Sum256(witnessScript)
49✔
3649
        bldr.AddData(scriptHash[:])
49✔
3650

49✔
3651
        return bldr.Script()
49✔
3652
}
3653

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

3662
        // OutPoint is the outpoint of the target channel.
3663
        OutPoint wire.OutPoint
3664
}
3665

3666
// String returns a human readable version of the target EdgePoint. We return
3667
// the outpoint directly as it is enough to uniquely identify the edge point.
3668
func (e *EdgePoint) String() string {
×
3669
        return e.OutPoint.String()
×
3670
}
×
3671

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

3695
                // Once we have the proper bucket, we'll range over each key
3696
                // (which is the channel point for the channel) and decode it,
3697
                // accumulating each entry.
3698
                return chanIndex.ForEach(
25✔
3699
                        func(chanPointBytes, chanID []byte) error {
70✔
3700
                                chanPointReader := bytes.NewReader(
45✔
3701
                                        chanPointBytes,
45✔
3702
                                )
45✔
3703

45✔
3704
                                var chanPoint wire.OutPoint
45✔
3705
                                err := ReadOutpoint(chanPointReader, &chanPoint)
45✔
3706
                                if err != nil {
45✔
3707
                                        return err
×
3708
                                }
×
3709

3710
                                edgeInfo, err := fetchChanEdgeInfo(
45✔
3711
                                        edgeIndex, chanID,
45✔
3712
                                )
45✔
3713
                                if err != nil {
45✔
3714
                                        return err
×
3715
                                }
×
3716

3717
                                pkScript, err := genMultiSigP2WSH(
45✔
3718
                                        edgeInfo.BitcoinKey1Bytes[:],
45✔
3719
                                        edgeInfo.BitcoinKey2Bytes[:],
45✔
3720
                                )
45✔
3721
                                if err != nil {
45✔
3722
                                        return err
×
3723
                                }
×
3724

3725
                                edgePoints = append(edgePoints, EdgePoint{
45✔
3726
                                        FundingPkScript: pkScript,
45✔
3727
                                        OutPoint:        chanPoint,
45✔
3728
                                })
45✔
3729

45✔
3730
                                return nil
45✔
3731
                        },
3732
                )
3733
        }, func() {
25✔
3734
                edgePoints = nil
25✔
3735
        }); err != nil {
25✔
3736
                return nil, err
×
3737
        }
×
3738

3739
        return edgePoints, nil
25✔
3740
}
3741

3742
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3743
// zombie. This method is used on an ad-hoc basis, when channels need to be
3744
// marked as zombies outside the normal pruning cycle.
3745
func (c *KVStore) MarkEdgeZombie(chanID uint64,
3746
        pubKey1, pubKey2 [33]byte) error {
129✔
3747

129✔
3748
        c.cacheMu.Lock()
129✔
3749
        defer c.cacheMu.Unlock()
129✔
3750

129✔
3751
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
258✔
3752
                edges := tx.ReadWriteBucket(edgeBucket)
129✔
3753
                if edges == nil {
129✔
3754
                        return ErrGraphNoEdgesFound
×
3755
                }
×
3756
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
129✔
3757
                if err != nil {
129✔
3758
                        return fmt.Errorf("unable to create zombie "+
×
3759
                                "bucket: %w", err)
×
3760
                }
×
3761

3762
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
129✔
3763
        })
3764
        if err != nil {
129✔
3765
                return err
×
3766
        }
×
3767

3768
        c.rejectCache.remove(chanID)
129✔
3769
        c.chanCache.remove(chanID)
129✔
3770

129✔
3771
        return nil
129✔
3772
}
3773

3774
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3775
// keys should represent the node public keys of the two parties involved in the
3776
// edge.
3777
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3778
        pubKey2 [33]byte) error {
156✔
3779

156✔
3780
        var k [8]byte
156✔
3781
        byteOrder.PutUint64(k[:], chanID)
156✔
3782

156✔
3783
        var v [66]byte
156✔
3784
        copy(v[:33], pubKey1[:])
156✔
3785
        copy(v[33:], pubKey2[:])
156✔
3786

156✔
3787
        return zombieIndex.Put(k[:], v[:])
156✔
3788
}
156✔
3789

3790
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3791
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
19✔
3792
        c.cacheMu.Lock()
19✔
3793
        defer c.cacheMu.Unlock()
19✔
3794

19✔
3795
        return c.markEdgeLiveUnsafe(nil, chanID)
19✔
3796
}
19✔
3797

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

3815
                var k [8]byte
19✔
3816
                byteOrder.PutUint64(k[:], chanID)
19✔
3817

19✔
3818
                if len(zombieIndex.Get(k[:])) == 0 {
21✔
3819
                        return ErrZombieEdgeNotFound
2✔
3820
                }
2✔
3821

3822
                return zombieIndex.Delete(k[:])
17✔
3823
        }
3824

3825
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3826
        // the existing transaction
3827
        var err error
19✔
3828
        if tx == nil {
38✔
3829
                err = kvdb.Update(c.db, dbFn, func() {})
38✔
3830
        } else {
×
3831
                err = dbFn(tx)
×
3832
        }
×
3833
        if err != nil {
21✔
3834
                return err
2✔
3835
        }
2✔
3836

3837
        c.rejectCache.remove(chanID)
17✔
3838
        c.chanCache.remove(chanID)
17✔
3839

17✔
3840
        return nil
17✔
3841
}
3842

3843
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3844
// zombie, then the two node public keys corresponding to this edge are also
3845
// returned.
3846
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte,
3847
        error) {
14✔
3848

14✔
3849
        var (
14✔
3850
                isZombie         bool
14✔
3851
                pubKey1, pubKey2 [33]byte
14✔
3852
        )
14✔
3853

14✔
3854
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
3855
                edges := tx.ReadBucket(edgeBucket)
14✔
3856
                if edges == nil {
14✔
3857
                        return ErrGraphNoEdgesFound
×
3858
                }
×
3859
                zombieIndex := edges.NestedReadBucket(zombieBucket)
14✔
3860
                if zombieIndex == nil {
14✔
3861
                        return nil
×
3862
                }
×
3863

3864
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
14✔
3865

14✔
3866
                return nil
14✔
3867
        }, func() {
14✔
3868
                isZombie = false
14✔
3869
                pubKey1 = [33]byte{}
14✔
3870
                pubKey2 = [33]byte{}
14✔
3871
        })
14✔
3872
        if err != nil {
14✔
3873
                return false, [33]byte{}, [33]byte{}, fmt.Errorf("%w: %w "+
×
3874
                        "(chanID=%d)", ErrCantCheckIfZombieEdgeStr, err, chanID)
×
3875
        }
×
3876

3877
        return isZombie, pubKey1, pubKey2, nil
14✔
3878
}
3879

3880
// isZombieEdge returns whether an entry exists for the given channel in the
3881
// zombie index. If an entry exists, then the two node public keys corresponding
3882
// to this edge are also returned.
3883
func isZombieEdge(zombieIndex kvdb.RBucket,
3884
        chanID uint64) (bool, [33]byte, [33]byte) {
189✔
3885

189✔
3886
        var k [8]byte
189✔
3887
        byteOrder.PutUint64(k[:], chanID)
189✔
3888

189✔
3889
        v := zombieIndex.Get(k[:])
189✔
3890
        if v == nil {
291✔
3891
                return false, [33]byte{}, [33]byte{}
102✔
3892
        }
102✔
3893

3894
        var pubKey1, pubKey2 [33]byte
90✔
3895
        copy(pubKey1[:], v[:33])
90✔
3896
        copy(pubKey2[:], v[33:])
90✔
3897

90✔
3898
        return true, pubKey1, pubKey2
90✔
3899
}
3900

3901
// NumZombies returns the current number of zombie channels in the graph.
3902
func (c *KVStore) NumZombies() (uint64, error) {
4✔
3903
        var numZombies uint64
4✔
3904
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3905
                edges := tx.ReadBucket(edgeBucket)
4✔
3906
                if edges == nil {
4✔
3907
                        return nil
×
3908
                }
×
3909
                zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3910
                if zombieIndex == nil {
4✔
3911
                        return nil
×
3912
                }
×
3913

3914
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3915
                        numZombies++
2✔
3916
                        return nil
2✔
3917
                })
2✔
3918
        }, func() {
4✔
3919
                numZombies = 0
4✔
3920
        })
4✔
3921
        if err != nil {
4✔
3922
                return 0, err
×
3923
        }
×
3924

3925
        return numZombies, nil
4✔
3926
}
3927

3928
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3929
// that we can ignore channel announcements that we know to be closed without
3930
// having to validate them and fetch a block.
3931
func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error {
1✔
3932
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
2✔
3933
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
1✔
3934
                if err != nil {
1✔
3935
                        return err
×
3936
                }
×
3937

3938
                var k [8]byte
1✔
3939
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3940

1✔
3941
                return closedScids.Put(k[:], []byte{})
1✔
3942
        }, func() {})
1✔
3943
}
3944

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

3956
                var k [8]byte
5✔
3957
                byteOrder.PutUint64(k[:], scid.ToUint64())
5✔
3958

5✔
3959
                if closedScids.Get(k[:]) != nil {
6✔
3960
                        isClosed = true
1✔
3961
                        return nil
1✔
3962
                }
1✔
3963

3964
                return nil
4✔
3965
        }, func() {
5✔
3966
                isClosed = false
5✔
3967
        })
5✔
3968
        if err != nil {
5✔
3969
                return false, err
×
3970
        }
×
3971

3972
        return isClosed, nil
5✔
3973
}
3974

3975
// GraphSession will provide the call-back with access to a NodeTraverser
3976
// instance which can be used to perform queries against the channel graph.
3977
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error,
3978
        reset func()) error {
54✔
3979

54✔
3980
        return c.db.View(func(tx walletdb.ReadTx) error {
108✔
3981
                return cb(&nodeTraverserSession{
54✔
3982
                        db: c,
54✔
3983
                        tx: tx,
54✔
3984
                })
54✔
3985
        }, reset)
54✔
3986
}
3987

3988
// nodeTraverserSession implements the NodeTraverser interface but with a
3989
// backing read only transaction for a consistent view of the graph.
3990
type nodeTraverserSession struct {
3991
        tx kvdb.RTx
3992
        db *KVStore
3993
}
3994

3995
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3996
// node.
3997
//
3998
// NOTE: Part of the NodeTraverser interface.
3999
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
4000
        cb func(channel *DirectedChannel) error, _ func()) error {
239✔
4001

239✔
4002
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb, func() {})
239✔
4003
}
4004

4005
// FetchNodeFeatures returns the features of the given node. If the node is
4006
// unknown, assume no additional features are supported.
4007
//
4008
// NOTE: Part of the NodeTraverser interface.
4009
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
4010
        *lnwire.FeatureVector, error) {
254✔
4011

254✔
4012
        return c.db.fetchNodeFeatures(c.tx, nodePub)
254✔
4013
}
254✔
4014

4015
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
4016
        node *models.LightningNode) error {
914✔
4017

914✔
4018
        var (
914✔
4019
                scratch [16]byte
914✔
4020
                b       bytes.Buffer
914✔
4021
        )
914✔
4022

914✔
4023
        pub, err := node.PubKey()
914✔
4024
        if err != nil {
914✔
4025
                return err
×
4026
        }
×
4027
        nodePub := pub.SerializeCompressed()
914✔
4028

914✔
4029
        // If the node has the update time set, write it, else write 0.
914✔
4030
        updateUnix := uint64(0)
914✔
4031
        if node.LastUpdate.Unix() > 0 {
1,689✔
4032
                updateUnix = uint64(node.LastUpdate.Unix())
775✔
4033
        }
775✔
4034

4035
        byteOrder.PutUint64(scratch[:8], updateUnix)
914✔
4036
        if _, err := b.Write(scratch[:8]); err != nil {
914✔
4037
                return err
×
4038
        }
×
4039

4040
        if _, err := b.Write(nodePub); err != nil {
914✔
4041
                return err
×
4042
        }
×
4043

4044
        // If we got a node announcement for this node, we will have the rest
4045
        // of the data available. If not we don't have more data to write.
4046
        if !node.HaveNodeAnnouncement {
1,003✔
4047
                // Write HaveNodeAnnouncement=0.
89✔
4048
                byteOrder.PutUint16(scratch[:2], 0)
89✔
4049
                if _, err := b.Write(scratch[:2]); err != nil {
89✔
4050
                        return err
×
4051
                }
×
4052

4053
                return nodeBucket.Put(nodePub, b.Bytes())
89✔
4054
        }
4055

4056
        // Write HaveNodeAnnouncement=1.
4057
        byteOrder.PutUint16(scratch[:2], 1)
828✔
4058
        if _, err := b.Write(scratch[:2]); err != nil {
828✔
4059
                return err
×
4060
        }
×
4061

4062
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
828✔
4063
                return err
×
4064
        }
×
4065
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
828✔
4066
                return err
×
4067
        }
×
4068
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
828✔
4069
                return err
×
4070
        }
×
4071

4072
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
828✔
4073
                return err
×
4074
        }
×
4075

4076
        if err := node.Features.Encode(&b); err != nil {
828✔
4077
                return err
×
4078
        }
×
4079

4080
        numAddresses := uint16(len(node.Addresses))
828✔
4081
        byteOrder.PutUint16(scratch[:2], numAddresses)
828✔
4082
        if _, err := b.Write(scratch[:2]); err != nil {
828✔
4083
                return err
×
4084
        }
×
4085

4086
        for _, address := range node.Addresses {
1,893✔
4087
                if err := SerializeAddr(&b, address); err != nil {
1,065✔
4088
                        return err
×
4089
                }
×
4090
        }
4091

4092
        sigLen := len(node.AuthSigBytes)
828✔
4093
        if sigLen > 80 {
828✔
4094
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4095
                        sigLen)
×
4096
        }
×
4097

4098
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
828✔
4099
        if err != nil {
828✔
4100
                return err
×
4101
        }
×
4102

4103
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
828✔
4104
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4105
        }
×
4106
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
828✔
4107
        if err != nil {
828✔
4108
                return err
×
4109
        }
×
4110

4111
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
828✔
4112
                return err
×
4113
        }
×
4114

4115
        // With the alias bucket updated, we'll now update the index that
4116
        // tracks the time series of node updates.
4117
        var indexKey [8 + 33]byte
828✔
4118
        byteOrder.PutUint64(indexKey[:8], updateUnix)
828✔
4119
        copy(indexKey[8:], nodePub)
828✔
4120

828✔
4121
        // If there was already an old index entry for this node, then we'll
828✔
4122
        // delete the old one before we write the new entry.
828✔
4123
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
847✔
4124
                // Extract out the old update time to we can reconstruct the
19✔
4125
                // prior index key to delete it from the index.
19✔
4126
                oldUpdateTime := nodeBytes[:8]
19✔
4127

19✔
4128
                var oldIndexKey [8 + 33]byte
19✔
4129
                copy(oldIndexKey[:8], oldUpdateTime)
19✔
4130
                copy(oldIndexKey[8:], nodePub)
19✔
4131

19✔
4132
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
19✔
4133
                        return err
×
4134
                }
×
4135
        }
4136

4137
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
828✔
4138
                return err
×
4139
        }
×
4140

4141
        return nodeBucket.Put(nodePub, b.Bytes())
828✔
4142
}
4143

4144
func fetchLightningNode(nodeBucket kvdb.RBucket,
4145
        nodePub []byte) (models.LightningNode, error) {
3,637✔
4146

3,637✔
4147
        nodeBytes := nodeBucket.Get(nodePub)
3,637✔
4148
        if nodeBytes == nil {
3,726✔
4149
                return models.LightningNode{}, ErrGraphNodeNotFound
89✔
4150
        }
89✔
4151

4152
        nodeReader := bytes.NewReader(nodeBytes)
3,551✔
4153

3,551✔
4154
        return deserializeLightningNode(nodeReader)
3,551✔
4155
}
4156

4157
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4158
        *lnwire.FeatureVector, error) {
123✔
4159

123✔
4160
        var (
123✔
4161
                pubKey      route.Vertex
123✔
4162
                features    = lnwire.EmptyFeatureVector()
123✔
4163
                nodeScratch [8]byte
123✔
4164
        )
123✔
4165

123✔
4166
        // Skip ahead:
123✔
4167
        // - LastUpdate (8 bytes)
123✔
4168
        if _, err := r.Read(nodeScratch[:]); err != nil {
123✔
4169
                return pubKey, nil, err
×
4170
        }
×
4171

4172
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
123✔
4173
                return pubKey, nil, err
×
4174
        }
×
4175

4176
        // Read the node announcement flag.
4177
        if _, err := r.Read(nodeScratch[:2]); err != nil {
123✔
4178
                return pubKey, nil, err
×
4179
        }
×
4180
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
123✔
4181

123✔
4182
        // The rest of the data is optional, and will only be there if we got a
123✔
4183
        // node announcement for this node.
123✔
4184
        if hasNodeAnn == 0 {
126✔
4185
                return pubKey, features, nil
3✔
4186
        }
3✔
4187

4188
        // We did get a node announcement for this node, so we'll have the rest
4189
        // of the data available.
4190
        var rgb uint8
123✔
4191
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4192
                return pubKey, nil, err
×
4193
        }
×
4194
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4195
                return pubKey, nil, err
×
4196
        }
×
4197
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4198
                return pubKey, nil, err
×
4199
        }
×
4200

4201
        if _, err := wire.ReadVarString(r, 0); err != nil {
123✔
4202
                return pubKey, nil, err
×
4203
        }
×
4204

4205
        if err := features.Decode(r); err != nil {
123✔
4206
                return pubKey, nil, err
×
4207
        }
×
4208

4209
        return pubKey, features, nil
123✔
4210
}
4211

4212
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,538✔
4213
        var (
8,538✔
4214
                node    models.LightningNode
8,538✔
4215
                scratch [8]byte
8,538✔
4216
                err     error
8,538✔
4217
        )
8,538✔
4218

8,538✔
4219
        // Always populate a feature vector, even if we don't have a node
8,538✔
4220
        // announcement and short circuit below.
8,538✔
4221
        node.Features = lnwire.EmptyFeatureVector()
8,538✔
4222

8,538✔
4223
        if _, err := r.Read(scratch[:]); err != nil {
8,538✔
4224
                return models.LightningNode{}, err
×
4225
        }
×
4226

4227
        unix := int64(byteOrder.Uint64(scratch[:]))
8,538✔
4228
        node.LastUpdate = time.Unix(unix, 0)
8,538✔
4229

8,538✔
4230
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,538✔
4231
                return models.LightningNode{}, err
×
4232
        }
×
4233

4234
        if _, err := r.Read(scratch[:2]); err != nil {
8,538✔
4235
                return models.LightningNode{}, err
×
4236
        }
×
4237

4238
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,538✔
4239
        if hasNodeAnn == 1 {
16,933✔
4240
                node.HaveNodeAnnouncement = true
8,395✔
4241
        } else {
8,541✔
4242
                node.HaveNodeAnnouncement = false
146✔
4243
        }
146✔
4244

4245
        // The rest of the data is optional, and will only be there if we got a
4246
        // node announcement for this node.
4247
        if !node.HaveNodeAnnouncement {
8,684✔
4248
                return node, nil
146✔
4249
        }
146✔
4250

4251
        // We did get a node announcement for this node, so we'll have the rest
4252
        // of the data available.
4253
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,395✔
4254
                return models.LightningNode{}, err
×
4255
        }
×
4256
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,395✔
4257
                return models.LightningNode{}, err
×
4258
        }
×
4259
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,395✔
4260
                return models.LightningNode{}, err
×
4261
        }
×
4262

4263
        node.Alias, err = wire.ReadVarString(r, 0)
8,395✔
4264
        if err != nil {
8,395✔
4265
                return models.LightningNode{}, err
×
4266
        }
×
4267

4268
        err = node.Features.Decode(r)
8,395✔
4269
        if err != nil {
8,395✔
4270
                return models.LightningNode{}, err
×
4271
        }
×
4272

4273
        if _, err := r.Read(scratch[:2]); err != nil {
8,395✔
4274
                return models.LightningNode{}, err
×
4275
        }
×
4276
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,395✔
4277

8,395✔
4278
        var addresses []net.Addr
8,395✔
4279
        for i := 0; i < numAddresses; i++ {
19,053✔
4280
                address, err := DeserializeAddr(r)
10,658✔
4281
                if err != nil {
10,658✔
4282
                        return models.LightningNode{}, err
×
4283
                }
×
4284
                addresses = append(addresses, address)
10,658✔
4285
        }
4286
        node.Addresses = addresses
8,395✔
4287

8,395✔
4288
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,395✔
4289
        if err != nil {
8,395✔
4290
                return models.LightningNode{}, err
×
4291
        }
×
4292

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

4305
        if len(extraBytes) > 0 {
8,405✔
4306
                node.ExtraOpaqueData = extraBytes
10✔
4307
        }
10✔
4308

4309
        return node, nil
8,395✔
4310
}
4311

4312
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4313
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,489✔
4314

1,489✔
4315
        var b bytes.Buffer
1,489✔
4316

1,489✔
4317
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,489✔
4318
                return err
×
4319
        }
×
4320
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,489✔
4321
                return err
×
4322
        }
×
4323
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,489✔
4324
                return err
×
4325
        }
×
4326
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,489✔
4327
                return err
×
4328
        }
×
4329

4330
        var featureBuf bytes.Buffer
1,489✔
4331
        if err := edgeInfo.Features.Encode(&featureBuf); err != nil {
1,489✔
4332
                return fmt.Errorf("unable to encode features: %w", err)
×
4333
        }
×
4334

4335
        if err := wire.WriteVarBytes(&b, 0, featureBuf.Bytes()); err != nil {
1,489✔
4336
                return err
×
4337
        }
×
4338

4339
        authProof := edgeInfo.AuthProof
1,489✔
4340
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,489✔
4341
        if authProof != nil {
2,894✔
4342
                nodeSig1 = authProof.NodeSig1Bytes
1,405✔
4343
                nodeSig2 = authProof.NodeSig2Bytes
1,405✔
4344
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,405✔
4345
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,405✔
4346
        }
1,405✔
4347

4348
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,489✔
4349
                return err
×
4350
        }
×
4351
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,489✔
4352
                return err
×
4353
        }
×
4354
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,489✔
4355
                return err
×
4356
        }
×
4357
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,489✔
4358
                return err
×
4359
        }
×
4360

4361
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,489✔
4362
                return err
×
4363
        }
×
4364
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
1,489✔
4365
        if err != nil {
1,489✔
4366
                return err
×
4367
        }
×
4368
        if _, err := b.Write(chanID[:]); err != nil {
1,489✔
4369
                return err
×
4370
        }
×
4371
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,489✔
4372
                return err
×
4373
        }
×
4374

4375
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,489✔
4376
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4377
        }
×
4378
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,489✔
4379
        if err != nil {
1,489✔
4380
                return err
×
4381
        }
×
4382

4383
        return edgeIndex.Put(chanID[:], b.Bytes())
1,489✔
4384
}
4385

4386
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4387
        chanID []byte) (models.ChannelEdgeInfo, error) {
6,803✔
4388

6,803✔
4389
        edgeInfoBytes := edgeIndex.Get(chanID)
6,803✔
4390
        if edgeInfoBytes == nil {
6,871✔
4391
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
68✔
4392
        }
68✔
4393

4394
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
6,738✔
4395

6,738✔
4396
        return deserializeChanEdgeInfo(edgeInfoReader)
6,738✔
4397
}
4398

4399
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
7,280✔
4400
        var (
7,280✔
4401
                err      error
7,280✔
4402
                edgeInfo models.ChannelEdgeInfo
7,280✔
4403
        )
7,280✔
4404

7,280✔
4405
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
7,280✔
4406
                return models.ChannelEdgeInfo{}, err
×
4407
        }
×
4408
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
7,280✔
4409
                return models.ChannelEdgeInfo{}, err
×
4410
        }
×
4411
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
7,280✔
4412
                return models.ChannelEdgeInfo{}, err
×
4413
        }
×
4414
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
7,280✔
4415
                return models.ChannelEdgeInfo{}, err
×
4416
        }
×
4417

4418
        featureBytes, err := wire.ReadVarBytes(r, 0, 900, "features")
7,280✔
4419
        if err != nil {
7,280✔
4420
                return models.ChannelEdgeInfo{}, err
×
4421
        }
×
4422

4423
        features := lnwire.NewRawFeatureVector()
7,280✔
4424
        err = features.Decode(bytes.NewReader(featureBytes))
7,280✔
4425
        if err != nil {
7,280✔
4426
                return models.ChannelEdgeInfo{}, fmt.Errorf("unable to decode "+
×
4427
                        "features: %w", err)
×
4428
        }
×
4429
        edgeInfo.Features = lnwire.NewFeatureVector(features, lnwire.Features)
7,280✔
4430

7,280✔
4431
        proof := &models.ChannelAuthProof{}
7,280✔
4432

7,280✔
4433
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
7,280✔
4434
        if err != nil {
7,280✔
4435
                return models.ChannelEdgeInfo{}, err
×
4436
        }
×
4437
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
7,280✔
4438
        if err != nil {
7,280✔
4439
                return models.ChannelEdgeInfo{}, err
×
4440
        }
×
4441
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
7,280✔
4442
        if err != nil {
7,280✔
4443
                return models.ChannelEdgeInfo{}, err
×
4444
        }
×
4445
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
7,280✔
4446
        if err != nil {
7,280✔
4447
                return models.ChannelEdgeInfo{}, err
×
4448
        }
×
4449

4450
        if !proof.IsEmpty() {
11,457✔
4451
                edgeInfo.AuthProof = proof
4,177✔
4452
        }
4,177✔
4453

4454
        edgeInfo.ChannelPoint = wire.OutPoint{}
7,280✔
4455
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
7,280✔
4456
                return models.ChannelEdgeInfo{}, err
×
4457
        }
×
4458
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
7,280✔
4459
                return models.ChannelEdgeInfo{}, err
×
4460
        }
×
4461
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
7,280✔
4462
                return models.ChannelEdgeInfo{}, err
×
4463
        }
×
4464

4465
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
7,280✔
4466
                return models.ChannelEdgeInfo{}, err
×
4467
        }
×
4468

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

4481
        return edgeInfo, nil
7,280✔
4482
}
4483

4484
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4485
        from, to []byte) error {
2,670✔
4486

2,670✔
4487
        var edgeKey [33 + 8]byte
2,670✔
4488
        copy(edgeKey[:], from)
2,670✔
4489
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,670✔
4490

2,670✔
4491
        var b bytes.Buffer
2,670✔
4492
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,670✔
4493
                return err
×
4494
        }
×
4495

4496
        // Before we write out the new edge, we'll create a new entry in the
4497
        // update index in order to keep it fresh.
4498
        updateUnix := uint64(edge.LastUpdate.Unix())
2,670✔
4499
        var indexKey [8 + 8]byte
2,670✔
4500
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,670✔
4501
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,670✔
4502

2,670✔
4503
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,670✔
4504
        if err != nil {
2,670✔
4505
                return err
×
4506
        }
×
4507

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

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

×
4536
                        return err
×
4537
                }
×
4538

4539
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
30✔
4540

30✔
4541
                var oldIndexKey [8 + 8]byte
30✔
4542
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
30✔
4543
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
30✔
4544

30✔
4545
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
30✔
4546
                        return err
×
4547
                }
×
4548
        }
4549

4550
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,670✔
4551
                return err
×
4552
        }
×
4553

4554
        err = updateEdgePolicyDisabledIndex(
2,670✔
4555
                edges, edge.ChannelID,
2,670✔
4556
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,670✔
4557
                edge.IsDisabled(),
2,670✔
4558
        )
2,670✔
4559
        if err != nil {
2,670✔
4560
                return err
×
4561
        }
×
4562

4563
        return edges.Put(edgeKey[:], b.Bytes())
2,670✔
4564
}
4565

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

2,938✔
4578
        var disabledEdgeKey [8 + 1]byte
2,938✔
4579
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,938✔
4580
        if direction {
4,405✔
4581
                disabledEdgeKey[8] = 1
1,467✔
4582
        }
1,467✔
4583

4584
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,938✔
4585
                disabledEdgePolicyBucket,
2,938✔
4586
        )
2,938✔
4587
        if err != nil {
2,938✔
4588
                return err
×
4589
        }
×
4590

4591
        if disabled {
2,967✔
4592
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4593
        }
29✔
4594

4595
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,912✔
4596
}
4597

4598
// putChanEdgePolicyUnknown marks the edge policy as unknown
4599
// in the edges bucket.
4600
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4601
        from []byte) error {
2,971✔
4602

2,971✔
4603
        var edgeKey [33 + 8]byte
2,971✔
4604
        copy(edgeKey[:], from)
2,971✔
4605
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,971✔
4606

2,971✔
4607
        if edges.Get(edgeKey[:]) != nil {
2,971✔
4608
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4609
                        " when there is already a policy present", channelID)
×
4610
        }
×
4611

4612
        return edges.Put(edgeKey[:], unknownPolicy)
2,971✔
4613
}
4614

4615
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4616
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
13,483✔
4617

13,483✔
4618
        var edgeKey [33 + 8]byte
13,483✔
4619
        copy(edgeKey[:], nodePub)
13,483✔
4620
        copy(edgeKey[33:], chanID)
13,483✔
4621

13,483✔
4622
        edgeBytes := edges.Get(edgeKey[:])
13,483✔
4623
        if edgeBytes == nil {
13,483✔
4624
                return nil, ErrEdgeNotFound
×
4625
        }
×
4626

4627
        // No need to deserialize unknown policy.
4628
        if bytes.Equal(edgeBytes, unknownPolicy) {
15,020✔
4629
                return nil, nil
1,537✔
4630
        }
1,537✔
4631

4632
        edgeReader := bytes.NewReader(edgeBytes)
11,949✔
4633

11,949✔
4634
        ep, err := deserializeChanEdgePolicy(edgeReader)
11,949✔
4635
        switch {
11,949✔
4636
        // If the db policy was missing an expected optional field, we return
4637
        // nil as if the policy was unknown.
4638
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
2✔
4639
                return nil, nil
2✔
4640

4641
        // If the policy contains invalid TLV bytes, we return nil as if
4642
        // the policy was unknown.
4643
        case errors.Is(err, ErrParsingExtraTLVBytes):
×
4644
                return nil, nil
×
4645

4646
        case err != nil:
×
4647
                return nil, err
×
4648
        }
4649

4650
        return ep, nil
11,947✔
4651
}
4652

4653
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4654
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4655
        error) {
2,901✔
4656

2,901✔
4657
        edgeInfo := edgeIndex.Get(chanID)
2,901✔
4658
        if edgeInfo == nil {
2,901✔
4659
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4660
                        chanID)
×
4661
        }
×
4662

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

4673
        // Similarly, the second node is contained within the latter
4674
        // half of the edge information.
4675
        node2Pub := edgeInfo[33:66]
2,901✔
4676
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
2,901✔
4677
        if err != nil {
2,901✔
4678
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4679
                        node2Pub)
×
4680
        }
×
4681

4682
        return edge1, edge2, nil
2,901✔
4683
}
4684

4685
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4686
        to []byte) error {
2,672✔
4687

2,672✔
4688
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,672✔
4689
        if err != nil {
2,672✔
4690
                return err
×
4691
        }
×
4692

4693
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,672✔
4694
                return err
×
4695
        }
×
4696

4697
        var scratch [8]byte
2,672✔
4698
        updateUnix := uint64(edge.LastUpdate.Unix())
2,672✔
4699
        byteOrder.PutUint64(scratch[:], updateUnix)
2,672✔
4700
        if _, err := w.Write(scratch[:]); err != nil {
2,672✔
4701
                return err
×
4702
        }
×
4703

4704
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,672✔
4705
                return err
×
4706
        }
×
4707
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,672✔
4708
                return err
×
4709
        }
×
4710
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,672✔
4711
                return err
×
4712
        }
×
4713
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,672✔
4714
                return err
×
4715
        }
×
4716
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
2,672✔
4717
        if err != nil {
2,672✔
4718
                return err
×
4719
        }
×
4720
        err = binary.Write(
2,672✔
4721
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
2,672✔
4722
        )
2,672✔
4723
        if err != nil {
2,672✔
4724
                return err
×
4725
        }
×
4726

4727
        if _, err := w.Write(to); err != nil {
2,672✔
4728
                return err
×
4729
        }
×
4730

4731
        // If the max_htlc field is present, we write it. To be compatible with
4732
        // older versions that wasn't aware of this field, we write it as part
4733
        // of the opaque data.
4734
        // TODO(halseth): clean up when moving to TLV.
4735
        var opaqueBuf bytes.Buffer
2,672✔
4736
        if edge.MessageFlags.HasMaxHtlc() {
4,960✔
4737
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,288✔
4738
                if err != nil {
2,288✔
4739
                        return err
×
4740
                }
×
4741
        }
4742

4743
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,672✔
4744
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4745
        }
×
4746
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,672✔
4747
                return err
×
4748
        }
×
4749

4750
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,672✔
4751
                return err
×
4752
        }
×
4753

4754
        return nil
2,672✔
4755
}
4756

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

×
4767
                return nil, err
×
4768
        }
×
4769

4770
        return edge, err
11,977✔
4771
}
4772

4773
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4774
        error) {
12,990✔
4775

12,990✔
4776
        edge := &models.ChannelEdgePolicy{}
12,990✔
4777

12,990✔
4778
        var err error
12,990✔
4779
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
12,990✔
4780
        if err != nil {
12,990✔
4781
                return nil, err
×
4782
        }
×
4783

4784
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
12,990✔
4785
                return nil, err
×
4786
        }
×
4787

4788
        var scratch [8]byte
12,990✔
4789
        if _, err := r.Read(scratch[:]); err != nil {
12,990✔
4790
                return nil, err
×
4791
        }
×
4792
        unix := int64(byteOrder.Uint64(scratch[:]))
12,990✔
4793
        edge.LastUpdate = time.Unix(unix, 0)
12,990✔
4794

12,990✔
4795
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
12,990✔
4796
                return nil, err
×
4797
        }
×
4798
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
12,990✔
4799
                return nil, err
×
4800
        }
×
4801
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
12,990✔
4802
                return nil, err
×
4803
        }
×
4804

4805
        var n uint64
12,990✔
4806
        if err := binary.Read(r, byteOrder, &n); err != nil {
12,990✔
4807
                return nil, err
×
4808
        }
×
4809
        edge.MinHTLC = lnwire.MilliSatoshi(n)
12,990✔
4810

12,990✔
4811
        if err := binary.Read(r, byteOrder, &n); err != nil {
12,990✔
4812
                return nil, err
×
4813
        }
×
4814
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
12,990✔
4815

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

12,990✔
4821
        if _, err := r.Read(edge.ToNode[:]); err != nil {
12,990✔
4822
                return nil, err
×
4823
        }
×
4824

4825
        // We'll try and see if there are any opaque bytes left, if not, then
4826
        // we'll ignore the EOF error and return the edge as is.
4827
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
12,990✔
4828
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
12,990✔
4829
        )
12,990✔
4830
        switch {
12,990✔
4831
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4832
        case errors.Is(err, io.EOF):
4✔
4833
        case err != nil:
×
4834
                return nil, err
×
4835
        }
4836

4837
        // See if optional fields are present.
4838
        if edge.MessageFlags.HasMaxHtlc() {
25,012✔
4839
                // The max_htlc field should be at the beginning of the opaque
12,022✔
4840
                // bytes.
12,022✔
4841
                opq := edge.ExtraOpaqueData
12,022✔
4842

12,022✔
4843
                // If the max_htlc field is not present, it might be old data
12,022✔
4844
                // stored before this field was validated. We'll return the
12,022✔
4845
                // edge along with an error.
12,022✔
4846
                if len(opq) < 8 {
12,026✔
4847
                        return edge, ErrEdgePolicyOptionalFieldNotFound
4✔
4848
                }
4✔
4849

4850
                maxHtlc := byteOrder.Uint64(opq[:8])
12,018✔
4851
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
12,018✔
4852

12,018✔
4853
                // Exclude the parsed field from the rest of the opaque data.
12,018✔
4854
                edge.ExtraOpaqueData = opq[8:]
12,018✔
4855
        }
4856

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

4868
        val, ok := typeMap[lnwire.FeeRecordType]
12,986✔
4869
        if ok && val == nil {
14,705✔
4870
                edge.InboundFee = fn.Some(inboundFee)
1,719✔
4871
        }
1,719✔
4872

4873
        return edge, nil
12,986✔
4874
}
4875

4876
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4877
// KVStore and a kvdb.RTx.
4878
type chanGraphNodeTx struct {
4879
        tx   kvdb.RTx
4880
        db   *KVStore
4881
        node *models.LightningNode
4882
}
4883

4884
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4885
// interface.
4886
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4887

4888
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4889
        node *models.LightningNode) *chanGraphNodeTx {
4,105✔
4890

4,105✔
4891
        return &chanGraphNodeTx{
4,105✔
4892
                tx:   tx,
4,105✔
4893
                db:   db,
4,105✔
4894
                node: node,
4,105✔
4895
        }
4,105✔
4896
}
4,105✔
4897

4898
// Node returns the raw information of the node.
4899
//
4900
// NOTE: This is a part of the NodeRTx interface.
4901
func (c *chanGraphNodeTx) Node() *models.LightningNode {
5,022✔
4902
        return c.node
5,022✔
4903
}
5,022✔
4904

4905
// FetchNode fetches the node with the given pub key under the same transaction
4906
// used to fetch the current node. The returned node is also a NodeRTx and any
4907
// operations on that NodeRTx will also be done under the same transaction.
4908
//
4909
// NOTE: This is a part of the NodeRTx interface.
4910
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
2,944✔
4911
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
2,944✔
4912
        if err != nil {
2,944✔
4913
                return nil, err
×
4914
        }
×
4915

4916
        return newChanGraphNodeTx(c.tx, c.db, node), nil
2,944✔
4917
}
4918

4919
// ForEachChannel can be used to iterate over the node's channels under
4920
// the same transaction used to fetch the node.
4921
//
4922
// NOTE: This is a part of the NodeRTx interface.
4923
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4924
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
965✔
4925

965✔
4926
        return c.db.forEachNodeChannelTx(
965✔
4927
                c.tx, c.node.PubKeyBytes,
965✔
4928
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
965✔
4929
                        policy2 *models.ChannelEdgePolicy) error {
3,909✔
4930

2,944✔
4931
                        return f(info, policy1, policy2)
2,944✔
4932
                },
2,944✔
4933
                // NOTE: We don't need to reset anything here as the caller is
4934
                // expected to pass in the reset function to the ForEachNode
4935
                // method that constructed the chanGraphNodeTx.
4936
                func() {},
×
4937
        )
4938
}
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