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

lightningnetwork / lnd / 16072717768

04 Jul 2025 11:27AM UTC coverage: 67.353% (+9.5%) from 57.822%
16072717768

Pull #10025

github

web-flow
Merge 9f3eac7c6 into b3eb9a3cb
Pull Request #10025: [draft] graph/db: kvdb -> SQL migration

10 of 664 new or added lines in 5 files covered. (1.51%)

89 existing lines in 8 files now uncovered.

135148 of 200655 relevant lines covered (67.35%)

21869.75 hits per line

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

77.97
/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(cb func(*models.ChannelEdgeInfo,
408
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
10✔
409

10✔
410
        return forEachChannel(c.db, cb)
10✔
411
}
10✔
412

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

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

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

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

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

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

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

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

105✔
468
                                return cb(&info, policy1, policy2)
105✔
469
                        },
470
                )
471
        }, func() {})
10✔
472
}
473

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

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

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

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

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

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

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

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

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

399✔
542
                                if policy1 != nil {
798✔
543
                                        cachedPolicy1 = models.NewCachedPolicy(
399✔
544
                                                policy1,
399✔
545
                                        )
399✔
546
                                }
399✔
547

548
                                if policy2 != nil {
798✔
549
                                        cachedPolicy2 = models.NewCachedPolicy(
399✔
550
                                                policy2,
399✔
551
                                        )
399✔
552
                                }
399✔
553

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

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

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

582
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
266✔
583
                p2 *models.ChannelEdgePolicy) error {
956✔
584

690✔
585
                var cachedInPolicy *models.CachedEdgePolicy
690✔
586
                if p2 != nil {
1,377✔
587
                        cachedInPolicy = models.NewCachedPolicy(p2)
687✔
588
                        cachedInPolicy.ToNodePubKey = toNodeCallback
687✔
589
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
687✔
590
                }
687✔
591

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

690✔
601
                if p1 != nil {
1,379✔
602
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
1,026✔
603
                                directedChannel.InboundFee = fee
337✔
604
                        })
337✔
605
                }
606

607
                if node == e.NodeKey2Bytes {
1,040✔
608
                        directedChannel.OtherNode = e.NodeKey1Bytes
350✔
609
                }
350✔
610

611
                return cb(directedChannel)
690✔
612
        }
613

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

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

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

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

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

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

26✔
652
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
26✔
653
}
26✔
654

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

4✔
662
        return c.fetchNodeFeatures(nil, nodePub)
4✔
663
}
4✔
664

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

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

20✔
679
                channels := make(map[uint64]*DirectedChannel)
20✔
680

20✔
681
                err := c.forEachNodeChannelTx(tx, node.PubKeyBytes,
20✔
682
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
20✔
683
                                p1 *models.ChannelEdgePolicy,
20✔
684
                                p2 *models.ChannelEdgePolicy) error {
210✔
685

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

696
                                var cachedInPolicy *models.CachedEdgePolicy
190✔
697
                                if p2 != nil {
380✔
698
                                        cachedInPolicy =
190✔
699
                                                models.NewCachedPolicy(p2)
190✔
700
                                        cachedInPolicy.ToNodePubKey =
190✔
701
                                                toNodeCallback
190✔
702
                                        cachedInPolicy.ToNodeFeatures =
190✔
703
                                                toNodeFeatures
190✔
704
                                }
190✔
705

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

190✔
716
                                if node.PubKeyBytes == e.NodeKey2Bytes {
285✔
717
                                        directedChannel.OtherNode =
95✔
718
                                                e.NodeKey1Bytes
95✔
719
                                }
95✔
720

721
                                channels[e.ChannelID] = directedChannel
190✔
722

190✔
723
                                return nil
190✔
724
                        })
725
                if err != nil {
20✔
726
                        return err
×
727
                }
×
728

729
                return cb(node.PubKeyBytes, channels)
20✔
730
        })
731
}
732

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

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

746
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
747
                        disabledEdgePolicyBucket,
6✔
748
                )
6✔
749
                if disabledEdgePolicyIndex == nil {
7✔
750
                        return nil
1✔
751
                }
1✔
752

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

4✔
766
                                        return nil
4✔
767
                                }
4✔
768

769
                                chanEdgeFound[chanID] = struct{}{}
7✔
770

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

782
        return disabledChanIDs, nil
6✔
783
}
784

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

1,161✔
795
                return cb(newChanGraphNodeTx(tx, c, node))
1,161✔
796
        })
1,161✔
797
}
798

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

132✔
809
        traversal := func(tx kvdb.RTx) error {
264✔
810
                // First grab the nodes bucket which stores the mapping from
132✔
811
                // pubKey to node information.
132✔
812
                nodes := tx.ReadBucket(nodeBucket)
132✔
813
                if nodes == nil {
132✔
814
                        return ErrGraphNotFound
×
815
                }
×
816

817
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,574✔
818
                        // If this is the source key, then we skip this
1,442✔
819
                        // iteration as the value for this key is a pubKey
1,442✔
820
                        // rather than raw node information.
1,442✔
821
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
1,706✔
822
                                return nil
264✔
823
                        }
264✔
824

825
                        nodeReader := bytes.NewReader(nodeBytes)
1,181✔
826
                        node, err := deserializeLightningNode(nodeReader)
1,181✔
827
                        if err != nil {
1,181✔
828
                                return err
×
829
                        }
×
830

831
                        // Execute the callback, the transaction will abort if
832
                        // this returns an error.
833
                        return cb(tx, &node)
1,181✔
834
                })
835
        }
836

837
        return kvdb.View(db, traversal, func() {})
264✔
838
}
839

840
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
841
// graph, executing the passed callback with each node encountered. If the
842
// callback returns an error, then the transaction is aborted and the iteration
843
// stops early.
844
func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
845
        *lnwire.FeatureVector) error) error {
142✔
846

142✔
847
        traversal := func(tx kvdb.RTx) error {
284✔
848
                // First grab the nodes bucket which stores the mapping from
142✔
849
                // pubKey to node information.
142✔
850
                nodes := tx.ReadBucket(nodeBucket)
142✔
851
                if nodes == nil {
142✔
852
                        return ErrGraphNotFound
×
853
                }
×
854

855
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
543✔
856
                        // If this is the source key, then we skip this
401✔
857
                        // iteration as the value for this key is a pubKey
401✔
858
                        // rather than raw node information.
401✔
859
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
682✔
860
                                return nil
281✔
861
                        }
281✔
862

863
                        nodeReader := bytes.NewReader(nodeBytes)
123✔
864
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
123✔
865
                                nodeReader,
123✔
866
                        )
123✔
867
                        if err != nil {
123✔
868
                                return err
×
869
                        }
×
870

871
                        // Execute the callback, the transaction will abort if
872
                        // this returns an error.
873
                        return cb(node, features)
123✔
874
                })
875
        }
876

877
        return kvdb.View(c.db, traversal, func() {})
284✔
878
}
879

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

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

900
                node, err := sourceNodeWithTx(nodes)
241✔
901
                if err != nil {
245✔
902
                        return err
4✔
903
                }
4✔
904
                source = node
240✔
905

240✔
906
                return nil
240✔
907
        }, func() {
241✔
908
                source = nil
241✔
909
        })
241✔
910
        if err != nil {
245✔
911
                return nil, err
4✔
912
        }
4✔
913

914
        return source, nil
240✔
915
}
916

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

927
        // With the pubKey of the source node retrieved, we're able to
928
        // fetch the full node information.
929
        node, err := fetchLightningNode(nodes, selfPub)
505✔
930
        if err != nil {
505✔
931
                return nil, err
×
932
        }
×
933

934
        return &node, nil
505✔
935
}
936

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

117✔
943
        nodePubBytes := node.PubKeyBytes[:]
117✔
944

117✔
945
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
234✔
946
                // First grab the nodes bucket which stores the mapping from
117✔
947
                // pubKey to node information.
117✔
948
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
117✔
949
                if err != nil {
117✔
950
                        return err
×
951
                }
×
952

953
                // Next we create the mapping from source to the targeted
954
                // public key.
955
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
117✔
956
                        return err
×
957
                }
×
958

959
                // Finally, we commit the information of the lightning node
960
                // itself.
961
                return addLightningNode(tx, node)
117✔
962
        }, func() {})
117✔
963
}
964

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

715✔
976
        r := &batch.Request[kvdb.RwTx]{
715✔
977
                Opts: batch.NewSchedulerOptions(opts...),
715✔
978
                Do: func(tx kvdb.RwTx) error {
1,430✔
979
                        return addLightningNode(tx, node)
715✔
980
                },
715✔
981
        }
982

983
        return c.nodeScheduler.Execute(ctx, r)
715✔
984
}
985

986
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
914✔
987
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
914✔
988
        if err != nil {
914✔
989
                return err
×
990
        }
×
991

992
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
914✔
993
        if err != nil {
914✔
994
                return err
×
995
        }
×
996

997
        updateIndex, err := nodes.CreateBucketIfNotExists(
914✔
998
                nodeUpdateIndexBucket,
914✔
999
        )
914✔
1000
        if err != nil {
914✔
1001
                return err
×
1002
        }
×
1003

1004
        return putLightningNode(nodes, aliases, updateIndex, node)
914✔
1005
}
1006

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

5✔
1012
        var alias string
5✔
1013

5✔
1014
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
1015
                nodes := tx.ReadBucket(nodeBucket)
5✔
1016
                if nodes == nil {
5✔
1017
                        return ErrGraphNodesNotFound
×
1018
                }
×
1019

1020
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
5✔
1021
                if aliases == nil {
5✔
1022
                        return ErrGraphNodesNotFound
×
1023
                }
×
1024

1025
                nodePub := pub.SerializeCompressed()
5✔
1026
                a := aliases.Get(nodePub)
5✔
1027
                if a == nil {
6✔
1028
                        return ErrNodeAliasNotFound
1✔
1029
                }
1✔
1030

1031
                // TODO(roasbeef): should actually be using the utf-8
1032
                // package...
1033
                alias = string(a)
4✔
1034

4✔
1035
                return nil
4✔
1036
        }, func() {
5✔
1037
                alias = ""
5✔
1038
        })
5✔
1039
        if err != nil {
6✔
1040
                return "", err
1✔
1041
        }
1✔
1042

1043
        return alias, nil
4✔
1044
}
1045

1046
// DeleteLightningNode starts a new database transaction to remove a vertex/node
1047
// from the database according to the node's public key.
1048
func (c *KVStore) DeleteLightningNode(_ context.Context,
1049
        nodePub route.Vertex) error {
4✔
1050

4✔
1051
        // TODO(roasbeef): ensure dangling edges are removed...
4✔
1052
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
8✔
1053
                nodes := tx.ReadWriteBucket(nodeBucket)
4✔
1054
                if nodes == nil {
4✔
1055
                        return ErrGraphNodeNotFound
×
1056
                }
×
1057

1058
                return c.deleteLightningNode(nodes, nodePub[:])
4✔
1059
        }, func() {})
4✔
1060
}
1061

1062
// deleteLightningNode uses an existing database transaction to remove a
1063
// vertex/node from the database according to the node's public key.
1064
func (c *KVStore) deleteLightningNode(nodes kvdb.RwBucket,
1065
        compressedPubKey []byte) error {
73✔
1066

73✔
1067
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
73✔
1068
        if aliases == nil {
73✔
1069
                return ErrGraphNodesNotFound
×
1070
        }
×
1071

1072
        if err := aliases.Delete(compressedPubKey); err != nil {
73✔
1073
                return err
×
1074
        }
×
1075

1076
        // Before we delete the node, we'll fetch its current state so we can
1077
        // determine when its last update was to clear out the node update
1078
        // index.
1079
        node, err := fetchLightningNode(nodes, compressedPubKey)
73✔
1080
        if err != nil {
74✔
1081
                return err
1✔
1082
        }
1✔
1083

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

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

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

72✔
1103
        return nodeUpdateIndex.Delete(indexKey[:])
72✔
1104
}
1105

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

1,720✔
1115
        var alreadyExists bool
1,720✔
1116
        r := &batch.Request[kvdb.RwTx]{
1,720✔
1117
                Opts: batch.NewSchedulerOptions(opts...),
1,720✔
1118
                Reset: func() {
3,440✔
1119
                        alreadyExists = false
1,720✔
1120
                },
1,720✔
1121
                Do: func(tx kvdb.RwTx) error {
1,720✔
1122
                        err := c.addChannelEdge(tx, edge)
1,720✔
1123

1,720✔
1124
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,720✔
1125
                        // succeed, but propagate the error via local state.
1,720✔
1126
                        if errors.Is(err, ErrEdgeAlreadyExist) {
1,957✔
1127
                                alreadyExists = true
237✔
1128
                                return nil
237✔
1129
                        }
237✔
1130

1131
                        return err
1,483✔
1132
                },
1133
                OnCommit: func(err error) error {
1,720✔
1134
                        switch {
1,720✔
1135
                        case err != nil:
×
1136
                                return err
×
1137
                        case alreadyExists:
237✔
1138
                                return ErrEdgeAlreadyExist
237✔
1139
                        default:
1,483✔
1140
                                c.rejectCache.remove(edge.ChannelID)
1,483✔
1141
                                c.chanCache.remove(edge.ChannelID)
1,483✔
1142
                                return nil
1,483✔
1143
                        }
1144
                },
1145
        }
1146

1147
        return c.chanScheduler.Execute(ctx, r)
1,720✔
1148
}
1149

1150
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1151
// utilize an existing db transaction.
1152
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
1153
        edge *models.ChannelEdgeInfo) error {
1,720✔
1154

1,720✔
1155
        // Construct the channel's primary key which is the 8-byte channel ID.
1,720✔
1156
        var chanKey [8]byte
1,720✔
1157
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,720✔
1158

1,720✔
1159
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,720✔
1160
        if err != nil {
1,720✔
1161
                return err
×
1162
        }
×
1163
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,720✔
1164
        if err != nil {
1,720✔
1165
                return err
×
1166
        }
×
1167
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,720✔
1168
        if err != nil {
1,720✔
1169
                return err
×
1170
        }
×
1171
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,720✔
1172
        if err != nil {
1,720✔
1173
                return err
×
1174
        }
×
1175

1176
        // First, attempt to check if this edge has already been created. If
1177
        // so, then we can exit early as this method is meant to be idempotent.
1178
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
1,957✔
1179
                return ErrEdgeAlreadyExist
237✔
1180
        }
237✔
1181

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

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

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

1225
        // Mark edge policies for both sides as unknown. This is to enable
1226
        // efficient incoming channel lookup for a node.
1227
        keys := []*[33]byte{
1,483✔
1228
                &edge.NodeKey1Bytes,
1,483✔
1229
                &edge.NodeKey2Bytes,
1,483✔
1230
        }
1,483✔
1231
        for _, key := range keys {
4,446✔
1232
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,963✔
1233
                if err != nil {
2,963✔
1234
                        return err
×
1235
                }
×
1236
        }
1237

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

1245
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,483✔
1246
}
1247

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

215✔
1257
        var (
215✔
1258
                upd1Time time.Time
215✔
1259
                upd2Time time.Time
215✔
1260
                exists   bool
215✔
1261
                isZombie bool
215✔
1262
        )
215✔
1263

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

77✔
1273
                return upd1Time, upd2Time, exists, isZombie, nil
77✔
1274
        }
77✔
1275
        c.cacheMu.RUnlock()
141✔
1276

141✔
1277
        c.cacheMu.Lock()
141✔
1278
        defer c.cacheMu.Unlock()
141✔
1279

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

8✔
1288
                return upd1Time, upd2Time, exists, isZombie, nil
8✔
1289
        }
8✔
1290

1291
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
272✔
1292
                edges := tx.ReadBucket(edgeBucket)
136✔
1293
                if edges == nil {
136✔
1294
                        return ErrGraphNoEdgesFound
×
1295
                }
×
1296
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
136✔
1297
                if edgeIndex == nil {
136✔
1298
                        return ErrGraphNoEdgesFound
×
1299
                }
×
1300

1301
                var channelID [8]byte
136✔
1302
                byteOrder.PutUint64(channelID[:], chanID)
136✔
1303

136✔
1304
                // If the edge doesn't exist, then we'll also check our zombie
136✔
1305
                // index.
136✔
1306
                if edgeIndex.Get(channelID[:]) == nil {
227✔
1307
                        exists = false
91✔
1308
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
91✔
1309
                        if zombieIndex != nil {
182✔
1310
                                isZombie, _, _ = isZombieEdge(
91✔
1311
                                        zombieIndex, chanID,
91✔
1312
                                )
91✔
1313
                        }
91✔
1314

1315
                        return nil
91✔
1316
                }
1317

1318
                exists = true
48✔
1319
                isZombie = false
48✔
1320

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

1329
                e1, e2, err := fetchChanEdgePolicies(
48✔
1330
                        edgeIndex, edges, channelID[:],
48✔
1331
                )
48✔
1332
                if err != nil {
48✔
1333
                        return err
×
1334
                }
×
1335

1336
                // As we may have only one of the edges populated, only set the
1337
                // update time if the edge was found in the database.
1338
                if e1 != nil {
69✔
1339
                        upd1Time = e1.LastUpdate
21✔
1340
                }
21✔
1341
                if e2 != nil {
67✔
1342
                        upd2Time = e2.LastUpdate
19✔
1343
                }
19✔
1344

1345
                return nil
48✔
1346
        }, func() {}); err != nil {
136✔
1347
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1348
        }
×
1349

1350
        c.rejectCache.insert(chanID, rejectCacheEntry{
136✔
1351
                upd1Time: upd1Time.Unix(),
136✔
1352
                upd2Time: upd2Time.Unix(),
136✔
1353
                flags:    packRejectFlags(exists, isZombie),
136✔
1354
        })
136✔
1355

136✔
1356
        return upd1Time, upd2Time, exists, isZombie, nil
136✔
1357
}
1358

1359
// AddEdgeProof sets the proof of an existing edge in the graph database.
1360
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
1361
        proof *models.ChannelAuthProof) error {
5✔
1362

5✔
1363
        // Construct the channel's primary key which is the 8-byte channel ID.
5✔
1364
        var chanKey [8]byte
5✔
1365
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
5✔
1366

5✔
1367
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
10✔
1368
                edges := tx.ReadWriteBucket(edgeBucket)
5✔
1369
                if edges == nil {
5✔
1370
                        return ErrEdgeNotFound
×
1371
                }
×
1372

1373
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
5✔
1374
                if edgeIndex == nil {
5✔
1375
                        return ErrEdgeNotFound
×
1376
                }
×
1377

1378
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
5✔
1379
                if err != nil {
5✔
1380
                        return err
×
1381
                }
×
1382

1383
                edge.AuthProof = proof
5✔
1384

5✔
1385
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
5✔
1386
        }, func() {})
5✔
1387
}
1388

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

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

244✔
1410
        c.cacheMu.Lock()
244✔
1411
        defer c.cacheMu.Unlock()
244✔
1412

244✔
1413
        var (
244✔
1414
                chansClosed []*models.ChannelEdgeInfo
244✔
1415
                prunedNodes []route.Vertex
244✔
1416
        )
244✔
1417

244✔
1418
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
488✔
1419
                // First grab the edges bucket which houses the information
244✔
1420
                // we'd like to delete
244✔
1421
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
244✔
1422
                if err != nil {
244✔
1423
                        return err
×
1424
                }
×
1425

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

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

160✔
1454
                        var opBytes bytes.Buffer
160✔
1455
                        err := WriteOutpoint(&opBytes, chanPoint)
160✔
1456
                        if err != nil {
160✔
1457
                                return err
×
1458
                        }
×
1459

1460
                        // First attempt to see if the channel exists within
1461
                        // the database, if not, then we can exit early.
1462
                        chanID := chanIndex.Get(opBytes.Bytes())
160✔
1463
                        if chanID == nil {
295✔
1464
                                continue
135✔
1465
                        }
1466

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

1479
                        chansClosed = append(chansClosed, edgeInfo)
25✔
1480
                }
1481

1482
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
244✔
1483
                if err != nil {
244✔
1484
                        return err
×
1485
                }
×
1486

1487
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
244✔
1488
                        pruneLogBucket,
244✔
1489
                )
244✔
1490
                if err != nil {
244✔
1491
                        return err
×
1492
                }
×
1493

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

244✔
1500
                var newTip [pruneTipBytes]byte
244✔
1501
                copy(newTip[:], blockHash[:])
244✔
1502

244✔
1503
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
244✔
1504
                if err != nil {
244✔
1505
                        return err
×
1506
                }
×
1507

1508
                // Now that the graph has been pruned, we'll also attempt to
1509
                // prune any nodes that have had a channel closed within the
1510
                // latest block.
1511
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
244✔
1512

244✔
1513
                return err
244✔
1514
        }, func() {
244✔
1515
                chansClosed = nil
244✔
1516
                prunedNodes = nil
244✔
1517
        })
244✔
1518
        if err != nil {
244✔
1519
                return nil, nil, err
×
1520
        }
×
1521

1522
        for _, channel := range chansClosed {
269✔
1523
                c.rejectCache.remove(channel.ChannelID)
25✔
1524
                c.chanCache.remove(channel.ChannelID)
25✔
1525
        }
25✔
1526

1527
        return chansClosed, prunedNodes, nil
244✔
1528
}
1529

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

1550
                var err error
26✔
1551
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
26✔
1552
                if err != nil {
26✔
1553
                        return err
×
1554
                }
×
1555

1556
                return nil
26✔
1557
        }, func() {
26✔
1558
                prunedNodes = nil
26✔
1559
        })
26✔
1560

1561
        return prunedNodes, err
26✔
1562
}
1563

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

267✔
1570
        log.Trace("Pruning nodes from graph with no open channels")
267✔
1571

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

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

1591
                var nodePub [33]byte
514✔
1592
                copy(nodePub[:], pubKey)
514✔
1593
                nodeRefCounts[nodePub] = 0
514✔
1594

514✔
1595
                return nil
514✔
1596
        })
1597
        if err != nil {
267✔
1598
                return nil, err
×
1599
        }
×
1600

1601
        // To ensure we never delete the source node, we'll start off by
1602
        // bumping its ref count to 1.
1603
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
267✔
1604

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

191✔
1616
                // With the nodes extracted, we'll increase the ref count of
191✔
1617
                // each of the nodes.
191✔
1618
                nodeRefCounts[node1]++
191✔
1619
                nodeRefCounts[node2]++
191✔
1620

191✔
1621
                return nil
191✔
1622
        })
191✔
1623
        if err != nil {
267✔
1624
                return nil, err
×
1625
        }
×
1626

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

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

×
1645
                                log.Warnf("Unable to prune node %x from the "+
×
1646
                                        "graph: %v", nodePubKey, err)
×
1647
                                continue
×
1648
                        }
1649

1650
                        return nil, err
×
1651
                }
1652

1653
                log.Infof("Pruned unconnected node %x from channel graph",
69✔
1654
                        nodePubKey[:])
69✔
1655

69✔
1656
                pruned = append(pruned, nodePubKey)
69✔
1657
        }
1658

1659
        if len(pruned) > 0 {
320✔
1660
                log.Infof("Pruned %v unconnected nodes from the channel graph",
53✔
1661
                        len(pruned))
53✔
1662
        }
53✔
1663

1664
        return pruned, err
267✔
1665
}
1666

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

162✔
1677
        // Every channel having a ShortChannelID starting at 'height'
162✔
1678
        // will no longer be confirmed.
162✔
1679
        startShortChanID := lnwire.ShortChannelID{
162✔
1680
                BlockHeight: height,
162✔
1681
        }
162✔
1682

162✔
1683
        // Delete everything after this height from the db up until the
162✔
1684
        // SCID alias range.
162✔
1685
        endShortChanID := aliasmgr.StartingAlias
162✔
1686

162✔
1687
        // The block height will be the 3 first bytes of the channel IDs.
162✔
1688
        var chanIDStart [8]byte
162✔
1689
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
162✔
1690
        var chanIDEnd [8]byte
162✔
1691
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
162✔
1692

162✔
1693
        c.cacheMu.Lock()
162✔
1694
        defer c.cacheMu.Unlock()
162✔
1695

162✔
1696
        // Keep track of the channels that are removed from the graph.
162✔
1697
        var removedChans []*models.ChannelEdgeInfo
162✔
1698

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

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

162✔
1728
                //nolint:ll
162✔
1729
                for k, _ := cursor.Seek(chanIDStart[:]); k != nil &&
162✔
1730
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, _ = cursor.Next() {
248✔
1731
                        keys = append(keys, k)
86✔
1732
                }
86✔
1733

1734
                for _, k := range keys {
248✔
1735
                        edgeInfo, err := c.delChannelEdgeUnsafe(
86✔
1736
                                edges, edgeIndex, chanIndex, zombieIndex,
86✔
1737
                                k, false, false,
86✔
1738
                        )
86✔
1739
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
86✔
1740
                                return err
×
1741
                        }
×
1742

1743
                        removedChans = append(removedChans, edgeInfo)
86✔
1744
                }
1745

1746
                // Delete all the entries in the prune log having a height
1747
                // greater or equal to the block disconnected.
1748
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
162✔
1749
                if err != nil {
162✔
1750
                        return err
×
1751
                }
×
1752

1753
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
162✔
1754
                        pruneLogBucket,
162✔
1755
                )
162✔
1756
                if err != nil {
162✔
1757
                        return err
×
1758
                }
×
1759

1760
                var pruneKeyStart [4]byte
162✔
1761
                byteOrder.PutUint32(pruneKeyStart[:], height)
162✔
1762

162✔
1763
                var pruneKeyEnd [4]byte
162✔
1764
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
162✔
1765

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

1776
                for _, k := range pruneKeys {
256✔
1777
                        if err := pruneBucket.Delete(k); err != nil {
94✔
1778
                                return err
×
1779
                        }
×
1780
                }
1781

1782
                return nil
162✔
1783
        }, func() {
162✔
1784
                removedChans = nil
162✔
1785
        }); err != nil {
162✔
1786
                return nil, err
×
1787
        }
×
1788

1789
        for _, channel := range removedChans {
248✔
1790
                c.rejectCache.remove(channel.ChannelID)
86✔
1791
                c.chanCache.remove(channel.ChannelID)
86✔
1792
        }
86✔
1793

1794
        return removedChans, nil
162✔
1795
}
1796

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

56✔
1807
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
112✔
1808
                graphMeta := tx.ReadBucket(graphMetaBucket)
56✔
1809
                if graphMeta == nil {
56✔
1810
                        return ErrGraphNotFound
×
1811
                }
×
1812
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
56✔
1813
                if pruneBucket == nil {
56✔
1814
                        return ErrGraphNeverPruned
×
1815
                }
×
1816

1817
                pruneCursor := pruneBucket.ReadCursor()
56✔
1818

56✔
1819
                // The prune key with the largest block height will be our
56✔
1820
                // prune tip.
56✔
1821
                k, v := pruneCursor.Last()
56✔
1822
                if k == nil {
77✔
1823
                        return ErrGraphNeverPruned
21✔
1824
                }
21✔
1825

1826
                // Once we have the prune tip, the value will be the block hash,
1827
                // and the key the block height.
1828
                copy(tipHash[:], v)
38✔
1829
                tipHeight = byteOrder.Uint32(k)
38✔
1830

38✔
1831
                return nil
38✔
1832
        }, func() {})
56✔
1833
        if err != nil {
77✔
1834
                return nil, 0, err
21✔
1835
        }
21✔
1836

1837
        return &tipHash, tipHeight, nil
38✔
1838
}
1839

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

146✔
1851
        // TODO(roasbeef): possibly delete from node bucket if node has no more
146✔
1852
        // channels
146✔
1853
        // TODO(roasbeef): don't delete both edges?
146✔
1854

146✔
1855
        c.cacheMu.Lock()
146✔
1856
        defer c.cacheMu.Unlock()
146✔
1857

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

1881
                var rawChanID [8]byte
146✔
1882
                for _, chanID := range chanIDs {
231✔
1883
                        byteOrder.PutUint64(rawChanID[:], chanID)
85✔
1884
                        edgeInfo, err := c.delChannelEdgeUnsafe(
85✔
1885
                                edges, edgeIndex, chanIndex, zombieIndex,
85✔
1886
                                rawChanID[:], markZombie, strictZombiePruning,
85✔
1887
                        )
85✔
1888
                        if err != nil {
141✔
1889
                                return err
56✔
1890
                        }
56✔
1891

1892
                        infos = append(infos, edgeInfo)
29✔
1893
                }
1894

1895
                return nil
90✔
1896
        }, func() {
146✔
1897
                infos = nil
146✔
1898
        })
146✔
1899
        if err != nil {
202✔
1900
                return nil, err
56✔
1901
        }
56✔
1902

1903
        for _, chanID := range chanIDs {
119✔
1904
                c.rejectCache.remove(chanID)
29✔
1905
                c.chanCache.remove(chanID)
29✔
1906
        }
29✔
1907

1908
        return infos, nil
90✔
1909
}
1910

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

1926
        return chanID, nil
4✔
1927
}
1928

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

1936
        edges := tx.ReadBucket(edgeBucket)
4✔
1937
        if edges == nil {
4✔
1938
                return 0, ErrGraphNoEdgesFound
×
1939
        }
×
1940
        chanIndex := edges.NestedReadBucket(channelPointBucket)
4✔
1941
        if chanIndex == nil {
4✔
1942
                return 0, ErrGraphNoEdgesFound
×
1943
        }
×
1944

1945
        chanIDBytes := chanIndex.Get(b.Bytes())
4✔
1946
        if chanIDBytes == nil {
7✔
1947
                return 0, ErrEdgeNotFound
3✔
1948
        }
3✔
1949

1950
        chanID := byteOrder.Uint64(chanIDBytes)
4✔
1951

4✔
1952
        return chanID, nil
4✔
1953
}
1954

1955
// TODO(roasbeef): allow updates to use Batch?
1956

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

6✔
1963
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
1964
                edges := tx.ReadBucket(edgeBucket)
6✔
1965
                if edges == nil {
6✔
1966
                        return ErrGraphNoEdgesFound
×
1967
                }
×
1968
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
6✔
1969
                if edgeIndex == nil {
6✔
1970
                        return ErrGraphNoEdgesFound
×
1971
                }
×
1972

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

6✔
1977
                lastChanID, _ := cidCursor.Last()
6✔
1978

6✔
1979
                // If there's no key, then this means that we don't actually
6✔
1980
                // know of any channels, so we'll return a predicable error.
6✔
1981
                if lastChanID == nil {
10✔
1982
                        return ErrGraphNoEdgesFound
4✔
1983
                }
4✔
1984

1985
                // Otherwise, we'll de serialize the channel ID and return it
1986
                // to the caller.
1987
                cid = byteOrder.Uint64(lastChanID)
5✔
1988

5✔
1989
                return nil
5✔
1990
        }, func() {
6✔
1991
                cid = 0
6✔
1992
        })
6✔
1993
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
6✔
1994
                return 0, err
×
1995
        }
×
1996

1997
        return cid, nil
6✔
1998
}
1999

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

2007
        // Policy1 points to the "first" edge policy of the channel containing
2008
        // the dynamic information required to properly route through the edge.
2009
        Policy1 *models.ChannelEdgePolicy
2010

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

2015
        // Node1 is "node 1" in the channel. This is the node that would have
2016
        // produced Policy1 if it exists.
2017
        Node1 *models.LightningNode
2018

2019
        // Node2 is "node 2" in the channel. This is the node that would have
2020
        // produced Policy2 if it exists.
2021
        Node2 *models.LightningNode
2022
}
2023

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

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

144✔
2036
        c.cacheMu.Lock()
144✔
2037
        defer c.cacheMu.Unlock()
144✔
2038

144✔
2039
        var hits int
144✔
2040
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
288✔
2041
                edges := tx.ReadBucket(edgeBucket)
144✔
2042
                if edges == nil {
144✔
2043
                        return ErrGraphNoEdgesFound
×
2044
                }
×
2045
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
144✔
2046
                if edgeIndex == nil {
144✔
2047
                        return ErrGraphNoEdgesFound
×
2048
                }
×
2049
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
144✔
2050
                if edgeUpdateIndex == nil {
144✔
2051
                        return ErrGraphNoEdgesFound
×
2052
                }
×
2053

2054
                nodes := tx.ReadBucket(nodeBucket)
144✔
2055
                if nodes == nil {
144✔
2056
                        return ErrGraphNodesNotFound
×
2057
                }
×
2058

2059
                // We'll now obtain a cursor to perform a range query within
2060
                // the index to find all channels within the horizon.
2061
                updateCursor := edgeUpdateIndex.ReadCursor()
144✔
2062

144✔
2063
                var startTimeBytes, endTimeBytes [8 + 8]byte
144✔
2064
                byteOrder.PutUint64(
144✔
2065
                        startTimeBytes[:8], uint64(startTime.Unix()),
144✔
2066
                )
144✔
2067
                byteOrder.PutUint64(
144✔
2068
                        endTimeBytes[:8], uint64(endTime.Unix()),
144✔
2069
                )
144✔
2070

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

49✔
2082
                        // If we've already retrieved the info and policies for
49✔
2083
                        // this edge, then we can skip it as we don't need to do
49✔
2084
                        // so again.
49✔
2085
                        chanIDInt := byteOrder.Uint64(chanID)
49✔
2086
                        if _, ok := edgesSeen[chanIDInt]; ok {
68✔
2087
                                continue
19✔
2088
                        }
2089

2090
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
41✔
2091
                                hits++
11✔
2092
                                edgesSeen[chanIDInt] = struct{}{}
11✔
2093
                                edgesInHorizon = append(edgesInHorizon, channel)
11✔
2094

11✔
2095
                                continue
11✔
2096
                        }
2097

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

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

2118
                        node1, err := fetchLightningNode(
21✔
2119
                                nodes, edgeInfo.NodeKey1Bytes[:],
21✔
2120
                        )
21✔
2121
                        if err != nil {
21✔
2122
                                return err
×
2123
                        }
×
2124

2125
                        node2, err := fetchLightningNode(
21✔
2126
                                nodes, edgeInfo.NodeKey2Bytes[:],
21✔
2127
                        )
21✔
2128
                        if err != nil {
21✔
2129
                                return err
×
2130
                        }
×
2131

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

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

2158
        case err != nil:
×
2159
                return nil, err
×
2160
        }
2161

2162
        // Insert any edges loaded from disk into the cache.
2163
        for chanid, channel := range edgesToCache {
165✔
2164
                c.chanCache.insert(chanid, channel)
21✔
2165
        }
21✔
2166

2167
        if len(edgesInHorizon) > 0 {
152✔
2168
                log.Debugf("ChanUpdatesInHorizon hit percentage: %.2f (%d/%d)",
8✔
2169
                        float64(hits)*100/float64(len(edgesInHorizon)), hits,
8✔
2170
                        len(edgesInHorizon))
8✔
2171
        } else {
147✔
2172
                log.Debugf("ChanUpdatesInHorizon returned no edges in "+
139✔
2173
                        "horizon (%s, %s)", startTime, endTime)
139✔
2174
        }
139✔
2175

2176
        return edgesInHorizon, nil
144✔
2177
}
2178

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

11✔
2186
        var nodesInHorizon []models.LightningNode
11✔
2187

11✔
2188
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
22✔
2189
                nodes := tx.ReadBucket(nodeBucket)
11✔
2190
                if nodes == nil {
11✔
2191
                        return ErrGraphNodesNotFound
×
2192
                }
×
2193

2194
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
11✔
2195
                if nodeUpdateIndex == nil {
11✔
2196
                        return ErrGraphNodesNotFound
×
2197
                }
×
2198

2199
                // We'll now obtain a cursor to perform a range query within
2200
                // the index to find all node announcements within the horizon.
2201
                updateCursor := nodeUpdateIndex.ReadCursor()
11✔
2202

11✔
2203
                var startTimeBytes, endTimeBytes [8 + 33]byte
11✔
2204
                byteOrder.PutUint64(
11✔
2205
                        startTimeBytes[:8], uint64(startTime.Unix()),
11✔
2206
                )
11✔
2207
                byteOrder.PutUint64(
11✔
2208
                        endTimeBytes[:8], uint64(endTime.Unix()),
11✔
2209
                )
11✔
2210

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

2224
                        nodesInHorizon = append(nodesInHorizon, node)
32✔
2225
                }
2226

2227
                return nil
11✔
2228
        }, func() {
11✔
2229
                nodesInHorizon = nil
11✔
2230
        })
11✔
2231
        switch {
11✔
2232
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2233
                fallthrough
×
2234
        case errors.Is(err, ErrGraphNodesNotFound):
×
2235
                break
×
2236

2237
        case err != nil:
×
2238
                return nil, err
×
2239
        }
2240

2241
        return nodesInHorizon, nil
11✔
2242
}
2243

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

129✔
2253
        var (
129✔
2254
                newChanIDs   []uint64
129✔
2255
                knownZombies []ChannelUpdateInfo
129✔
2256
        )
129✔
2257

129✔
2258
        c.cacheMu.Lock()
129✔
2259
        defer c.cacheMu.Unlock()
129✔
2260

129✔
2261
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
258✔
2262
                edges := tx.ReadBucket(edgeBucket)
129✔
2263
                if edges == nil {
129✔
2264
                        return ErrGraphNoEdgesFound
×
2265
                }
×
2266
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
129✔
2267
                if edgeIndex == nil {
129✔
2268
                        return ErrGraphNoEdgesFound
×
2269
                }
×
2270

2271
                // Fetch the zombie index, it may not exist if no edges have
2272
                // ever been marked as zombies. If the index has been
2273
                // initialized, we will use it later to skip known zombie edges.
2274
                zombieIndex := edges.NestedReadBucket(zombieBucket)
129✔
2275

129✔
2276
                // We'll run through the set of chanIDs and collate only the
129✔
2277
                // set of channel that are unable to be found within our db.
129✔
2278
                var cidBytes [8]byte
129✔
2279
                for _, info := range chansInfo {
253✔
2280
                        scid := info.ShortChannelID.ToUint64()
124✔
2281
                        byteOrder.PutUint64(cidBytes[:], scid)
124✔
2282

124✔
2283
                        // If the edge is already known, skip it.
124✔
2284
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
143✔
2285
                                continue
19✔
2286
                        }
2287

2288
                        // If the edge is a known zombie, skip it.
2289
                        if zombieIndex != nil {
216✔
2290
                                isZombie, _, _ := isZombieEdge(
108✔
2291
                                        zombieIndex, scid,
108✔
2292
                                )
108✔
2293

108✔
2294
                                if isZombie {
153✔
2295
                                        knownZombies = append(
45✔
2296
                                                knownZombies, info,
45✔
2297
                                        )
45✔
2298

45✔
2299
                                        continue
45✔
2300
                                }
2301
                        }
2302

2303
                        newChanIDs = append(newChanIDs, scid)
63✔
2304
                }
2305

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

2320
                return ogChanIDs, nil, nil
×
2321

2322
        case err != nil:
×
2323
                return nil, nil, err
×
2324
        }
2325

2326
        return newChanIDs, knownZombies, nil
129✔
2327
}
2328

2329
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2330
// latest received channel updates for the channel.
2331
type ChannelUpdateInfo struct {
2332
        // ShortChannelID is the SCID identifier of the channel.
2333
        ShortChannelID lnwire.ShortChannelID
2334

2335
        // Node1UpdateTimestamp is the timestamp of the latest received update
2336
        // from the node 1 channel peer. This will be set to zero time if no
2337
        // update has yet been received from this node.
2338
        Node1UpdateTimestamp time.Time
2339

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

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

199✔
2352
        chanInfo := ChannelUpdateInfo{
199✔
2353
                ShortChannelID:       scid,
199✔
2354
                Node1UpdateTimestamp: node1Timestamp,
199✔
2355
                Node2UpdateTimestamp: node2Timestamp,
199✔
2356
        }
199✔
2357

199✔
2358
        if node1Timestamp.IsZero() {
388✔
2359
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
189✔
2360
        }
189✔
2361

2362
        if node2Timestamp.IsZero() {
388✔
2363
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
189✔
2364
        }
189✔
2365

2366
        return chanInfo
199✔
2367
}
2368

2369
// BlockChannelRange represents a range of channels for a given block height.
2370
type BlockChannelRange struct {
2371
        // Height is the height of the block all of the channels below were
2372
        // included in.
2373
        Height uint32
2374

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

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

14✔
2392
        startChanID := &lnwire.ShortChannelID{
14✔
2393
                BlockHeight: startHeight,
14✔
2394
        }
14✔
2395

14✔
2396
        endChanID := lnwire.ShortChannelID{
14✔
2397
                BlockHeight: endHeight,
14✔
2398
                TxIndex:     math.MaxUint32 & 0x00ffffff,
14✔
2399
                TxPosition:  math.MaxUint16,
14✔
2400
        }
14✔
2401

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

14✔
2409
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
14✔
2410
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
2411
                edges := tx.ReadBucket(edgeBucket)
14✔
2412
                if edges == nil {
14✔
2413
                        return ErrGraphNoEdgesFound
×
2414
                }
×
2415
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
2416
                if edgeIndex == nil {
14✔
2417
                        return ErrGraphNoEdgesFound
×
2418
                }
×
2419

2420
                cursor := edgeIndex.ReadCursor()
14✔
2421

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

2435
                        if edgeInfo.AuthProof == nil {
50✔
2436
                                continue
3✔
2437
                        }
2438

2439
                        // This channel ID rests within the target range, so
2440
                        // we'll add it to our returned set.
2441
                        rawCid := byteOrder.Uint64(k)
47✔
2442
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
47✔
2443

47✔
2444
                        chanInfo := NewChannelUpdateInfo(
47✔
2445
                                cid, time.Time{}, time.Time{},
47✔
2446
                        )
47✔
2447

47✔
2448
                        if !withTimestamps {
69✔
2449
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2450
                                        channelsPerBlock[cid.BlockHeight],
22✔
2451
                                        chanInfo,
22✔
2452
                                )
22✔
2453

22✔
2454
                                continue
22✔
2455
                        }
2456

2457
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
25✔
2458

25✔
2459
                        rawPolicy := edges.Get(node1Key)
25✔
2460
                        if len(rawPolicy) != 0 {
34✔
2461
                                r := bytes.NewReader(rawPolicy)
9✔
2462

9✔
2463
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2464
                                if err != nil && !errors.Is(
9✔
2465
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2466
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
9✔
2467

×
2468
                                        return err
×
2469
                                }
×
2470

2471
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2472
                        }
2473

2474
                        rawPolicy = edges.Get(node2Key)
25✔
2475
                        if len(rawPolicy) != 0 {
39✔
2476
                                r := bytes.NewReader(rawPolicy)
14✔
2477

14✔
2478
                                edge, err := deserializeChanEdgePolicyRaw(r)
14✔
2479
                                if err != nil && !errors.Is(
14✔
2480
                                        err, ErrEdgePolicyOptionalFieldNotFound,
14✔
2481
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
14✔
2482

×
2483
                                        return err
×
2484
                                }
×
2485

2486
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
14✔
2487
                        }
2488

2489
                        channelsPerBlock[cid.BlockHeight] = append(
25✔
2490
                                channelsPerBlock[cid.BlockHeight], chanInfo,
25✔
2491
                        )
25✔
2492
                }
2493

2494
                return nil
14✔
2495
        }, func() {
14✔
2496
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
14✔
2497
        })
14✔
2498

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

2505
        case err != nil:
×
2506
                return nil, err
×
2507
        }
2508

2509
        // Return the channel ranges in ascending block height order.
2510
        blocks := make([]uint32, 0, len(channelsPerBlock))
11✔
2511
        for block := range channelsPerBlock {
36✔
2512
                blocks = append(blocks, block)
25✔
2513
        }
25✔
2514
        sort.Slice(blocks, func(i, j int) bool {
38✔
2515
                return blocks[i] < blocks[j]
27✔
2516
        })
27✔
2517

2518
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
11✔
2519
        for _, block := range blocks {
36✔
2520
                channelRanges = append(channelRanges, BlockChannelRange{
25✔
2521
                        Height:   block,
25✔
2522
                        Channels: channelsPerBlock[block],
25✔
2523
                })
25✔
2524
        }
25✔
2525

2526
        return channelRanges, nil
11✔
2527
}
2528

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

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

7✔
2550
        var (
7✔
2551
                chanEdges []ChannelEdge
7✔
2552
                cidBytes  [8]byte
7✔
2553
        )
7✔
2554

7✔
2555
        fetchChanInfos := func(tx kvdb.RTx) error {
14✔
2556
                edges := tx.ReadBucket(edgeBucket)
7✔
2557
                if edges == nil {
7✔
2558
                        return ErrGraphNoEdgesFound
×
2559
                }
×
2560
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
7✔
2561
                if edgeIndex == nil {
7✔
2562
                        return ErrGraphNoEdgesFound
×
2563
                }
×
2564
                nodes := tx.ReadBucket(nodeBucket)
7✔
2565
                if nodes == nil {
7✔
2566
                        return ErrGraphNotFound
×
2567
                }
×
2568

2569
                for _, cid := range chanIDs {
21✔
2570
                        byteOrder.PutUint64(cidBytes[:], cid)
14✔
2571

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

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

2594
                        node1, err := fetchLightningNode(
11✔
2595
                                nodes, edgeInfo.NodeKey1Bytes[:],
11✔
2596
                        )
11✔
2597
                        if err != nil {
11✔
2598
                                return err
×
2599
                        }
×
2600

2601
                        node2, err := fetchLightningNode(
11✔
2602
                                nodes, edgeInfo.NodeKey2Bytes[:],
11✔
2603
                        )
11✔
2604
                        if err != nil {
11✔
2605
                                return err
×
2606
                        }
×
2607

2608
                        chanEdges = append(chanEdges, ChannelEdge{
11✔
2609
                                Info:    &edgeInfo,
11✔
2610
                                Policy1: edge1,
11✔
2611
                                Policy2: edge2,
11✔
2612
                                Node1:   &node1,
11✔
2613
                                Node2:   &node2,
11✔
2614
                        })
11✔
2615
                }
2616

2617
                return nil
7✔
2618
        }
2619

2620
        if tx == nil {
14✔
2621
                err := kvdb.View(c.db, fetchChanInfos, func() {
14✔
2622
                        chanEdges = nil
7✔
2623
                })
7✔
2624
                if err != nil {
7✔
2625
                        return nil, err
×
2626
                }
×
2627

2628
                return chanEdges, nil
7✔
2629
        }
2630

2631
        err := fetchChanInfos(tx)
×
2632
        if err != nil {
×
2633
                return nil, err
×
2634
        }
×
2635

2636
        return chanEdges, nil
×
2637
}
2638

2639
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2640
        edge1, edge2 *models.ChannelEdgePolicy) error {
135✔
2641

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

2650
        // Now that we have the bucket, we'll attempt to construct a template
2651
        // for the index key: updateTime || chanid.
2652
        var indexKey [8 + 8]byte
135✔
2653
        byteOrder.PutUint64(indexKey[8:], chanID)
135✔
2654

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

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

2678
        return nil
135✔
2679
}
2680

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

191✔
2692
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
191✔
2693
        if err != nil {
247✔
2694
                return nil, err
56✔
2695
        }
56✔
2696

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

2710
        // The edge key is of the format pubKey || chanID. First we construct
2711
        // the latter half, populating the channel ID.
2712
        var edgeKey [33 + 8]byte
135✔
2713
        copy(edgeKey[33:], chanID)
135✔
2714

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

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

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

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

2763
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
27✔
2764
        if strictZombie {
30✔
2765
                var e1UpdateTime, e2UpdateTime *time.Time
3✔
2766
                if edge1 != nil {
5✔
2767
                        e1UpdateTime = &edge1.LastUpdate
2✔
2768
                }
2✔
2769
                if edge2 != nil {
6✔
2770
                        e2UpdateTime = &edge2.LastUpdate
3✔
2771
                }
3✔
2772

2773
                nodeKey1, nodeKey2 = makeZombiePubkeys(
3✔
2774
                        &edgeInfo, e1UpdateTime, e2UpdateTime,
3✔
2775
                )
3✔
2776
        }
2777

2778
        return &edgeInfo, markEdgeZombie(
27✔
2779
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
27✔
2780
        )
27✔
2781
}
2782

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

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

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

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

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

2,675✔
2834
        var (
2,675✔
2835
                isUpdate1    bool
2,675✔
2836
                edgeNotFound bool
2,675✔
2837
                from, to     route.Vertex
2,675✔
2838
        )
2,675✔
2839

2,675✔
2840
        r := &batch.Request[kvdb.RwTx]{
2,675✔
2841
                Opts: batch.NewSchedulerOptions(opts...),
2,675✔
2842
                Reset: func() {
5,351✔
2843
                        isUpdate1 = false
2,676✔
2844
                        edgeNotFound = false
2,676✔
2845
                },
2,676✔
2846
                Do: func(tx kvdb.RwTx) error {
2,676✔
2847
                        // Validate that the ExtraOpaqueData is in fact a valid
2,676✔
2848
                        // TLV stream.
2,676✔
2849
                        err := edge.ExtraOpaqueData.ValidateTLV()
2,676✔
2850
                        if err != nil {
2,678✔
2851
                                return fmt.Errorf("%w: %w",
2✔
2852
                                        ErrParsingExtraTLVBytes, err)
2✔
2853
                        }
2✔
2854

2855
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
2,674✔
2856
                        if err != nil {
2,678✔
2857
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
4✔
2858
                        }
4✔
2859

2860
                        // Silence ErrEdgeNotFound so that the batch can
2861
                        // succeed, but propagate the error via local state.
2862
                        if errors.Is(err, ErrEdgeNotFound) {
2,678✔
2863
                                edgeNotFound = true
4✔
2864
                                return nil
4✔
2865
                        }
4✔
2866

2867
                        return err
2,670✔
2868
                },
2869
                OnCommit: func(err error) error {
2,675✔
2870
                        switch {
2,675✔
2871
                        case err != nil:
1✔
2872
                                return err
1✔
2873
                        case edgeNotFound:
4✔
2874
                                return ErrEdgeNotFound
4✔
2875
                        default:
2,670✔
2876
                                c.updateEdgeCache(edge, isUpdate1)
2,670✔
2877
                                return nil
2,670✔
2878
                        }
2879
                },
2880
        }
2881

2882
        err := c.chanScheduler.Execute(ctx, r)
2,675✔
2883

2,675✔
2884
        return from, to, err
2,675✔
2885
}
2886

2887
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2888
        isUpdate1 bool) {
2,670✔
2889

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

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

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

2,674✔
2924
        var noVertex route.Vertex
2,674✔
2925

2,674✔
2926
        edges := tx.ReadWriteBucket(edgeBucket)
2,674✔
2927
        if edges == nil {
2,674✔
2928
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2929
        }
×
2930
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,674✔
2931
        if edgeIndex == nil {
2,674✔
2932
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2933
        }
×
2934

2935
        // Create the channelID key be converting the channel ID
2936
        // integer into a byte slice.
2937
        var chanID [8]byte
2,674✔
2938
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,674✔
2939

2,674✔
2940
        // With the channel ID, we then fetch the value storing the two
2,674✔
2941
        // nodes which connect this channel edge.
2,674✔
2942
        nodeInfo := edgeIndex.Get(chanID[:])
2,674✔
2943
        if nodeInfo == nil {
2,678✔
2944
                return noVertex, noVertex, false, ErrEdgeNotFound
4✔
2945
        }
4✔
2946

2947
        // Depending on the flags value passed above, either the first
2948
        // or second edge policy is being updated.
2949
        var fromNode, toNode []byte
2,670✔
2950
        var isUpdate1 bool
2,670✔
2951
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
4,010✔
2952
                fromNode = nodeInfo[:33]
1,340✔
2953
                toNode = nodeInfo[33:66]
1,340✔
2954
                isUpdate1 = true
1,340✔
2955
        } else {
2,673✔
2956
                fromNode = nodeInfo[33:66]
1,333✔
2957
                toNode = nodeInfo[:33]
1,333✔
2958
                isUpdate1 = false
1,333✔
2959
        }
1,333✔
2960

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

2968
        var (
2,670✔
2969
                fromNodePubKey route.Vertex
2,670✔
2970
                toNodePubKey   route.Vertex
2,670✔
2971
        )
2,670✔
2972
        copy(fromNodePubKey[:], fromNode)
2,670✔
2973
        copy(toNodePubKey[:], toNode)
2,670✔
2974

2,670✔
2975
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
2,670✔
2976
}
2977

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

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

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

6✔
3001
                        nodeIsPublic = true
6✔
3002
                        return errDone
6✔
3003
                }
6✔
3004

3005
                // Since the edge _does_ extend to the source node, we'll also
3006
                // need to ensure that this is a public edge.
3007
                if info.AuthProof != nil {
19✔
3008
                        nodeIsPublic = true
9✔
3009
                        return errDone
9✔
3010
                }
9✔
3011

3012
                // Otherwise, we'll continue our search.
3013
                return nil
4✔
3014
        })
3015
        if err != nil && !errors.Is(err, errDone) {
16✔
3016
                return false, err
×
3017
        }
×
3018

3019
        return nodeIsPublic, nil
16✔
3020
}
3021

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

3,655✔
3029
        return c.fetchLightningNode(tx, nodePub)
3,655✔
3030
}
3,655✔
3031

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

162✔
3038
        return c.fetchLightningNode(nil, nodePub)
162✔
3039
}
162✔
3040

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

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

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

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

3072
                node = &n
3,799✔
3073

3,799✔
3074
                return nil
3,799✔
3075
        }
3076

3077
        if tx == nil {
4,000✔
3078
                err := kvdb.View(
186✔
3079
                        c.db, fetch, func() {
372✔
3080
                                node = nil
186✔
3081
                        },
186✔
3082
                )
3083
                if err != nil {
193✔
3084
                        return nil, err
7✔
3085
                }
7✔
3086

3087
                return node, nil
182✔
3088
        }
3089

3090
        err := fetch(tx)
3,628✔
3091
        if err != nil {
3,639✔
3092
                return nil, err
11✔
3093
        }
11✔
3094

3095
        return node, nil
3,617✔
3096
}
3097

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

20✔
3106
        var (
20✔
3107
                updateTime time.Time
20✔
3108
                exists     bool
20✔
3109
        )
20✔
3110

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

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

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

3136
                exists = true
17✔
3137
                updateTime = node.LastUpdate
17✔
3138

17✔
3139
                return nil
17✔
3140
        }, func() {
20✔
3141
                updateTime = time.Time{}
20✔
3142
                exists = false
20✔
3143
        })
20✔
3144
        if err != nil {
20✔
3145
                return time.Time{}, exists, err
×
3146
        }
×
3147

3148
        return updateTime, exists, nil
20✔
3149
}
3150

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

1,271✔
3157
        traversal := func(tx kvdb.RTx) error {
2,542✔
3158
                edges := tx.ReadBucket(edgeBucket)
1,271✔
3159
                if edges == nil {
1,271✔
3160
                        return ErrGraphNotFound
×
3161
                }
×
3162
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,271✔
3163
                if edgeIndex == nil {
1,271✔
3164
                        return ErrGraphNoEdgesFound
×
3165
                }
×
3166

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

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

3194
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,846✔
3195
                                edges, chanID, nodePub,
3,846✔
3196
                        )
3,846✔
3197
                        if err != nil {
3,846✔
3198
                                return err
×
3199
                        }
×
3200

3201
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,846✔
3202
                        if err != nil {
3,846✔
3203
                                return err
×
3204
                        }
×
3205

3206
                        incomingPolicy, err := fetchChanEdgePolicy(
3,846✔
3207
                                edges, chanID, otherNode[:],
3,846✔
3208
                        )
3,846✔
3209
                        if err != nil {
3,846✔
3210
                                return err
×
3211
                        }
×
3212

3213
                        // Finally, we execute the callback.
3214
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,846✔
3215
                        if err != nil {
3,858✔
3216
                                return err
12✔
3217
                        }
12✔
3218
                }
3219

3220
                return nil
1,262✔
3221
        }
3222

3223
        // If no transaction was provided, then we'll create a new transaction
3224
        // to execute the transaction within.
3225
        if tx == nil {
1,303✔
3226
                return kvdb.View(db, traversal, func() {})
64✔
3227
        }
3228

3229
        // Otherwise, we re-use the existing transaction to execute the graph
3230
        // traversal.
3231
        return traversal(tx)
1,242✔
3232
}
3233

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

9✔
3246
        return nodeTraversal(nil, nodePub[:], c.db, func(_ kvdb.RTx,
9✔
3247
                info *models.ChannelEdgeInfo, policy,
9✔
3248
                policy2 *models.ChannelEdgePolicy) error {
22✔
3249

13✔
3250
                return cb(info, policy, policy2)
13✔
3251
        })
13✔
3252
}
3253

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

4✔
3261
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3262
                nodes := tx.ReadBucket(nodeBucket)
4✔
3263
                if nodes == nil {
4✔
3264
                        return ErrGraphNotFound
×
3265
                }
×
3266

3267
                node, err := sourceNodeWithTx(nodes)
4✔
3268
                if err != nil {
4✔
3269
                        return err
×
3270
                }
×
3271

3272
                return nodeTraversal(
4✔
3273
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
4✔
3274
                                info *models.ChannelEdgeInfo,
4✔
3275
                                policy, _ *models.ChannelEdgePolicy) error {
9✔
3276

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

3284
                                return cb(
5✔
3285
                                        info.ChannelPoint, policy != nil, peer,
5✔
3286
                                )
5✔
3287
                        },
3288
                )
3289
        }, func() {})
4✔
3290
}
3291

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

1,001✔
3310
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,001✔
3311
}
1,001✔
3312

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

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

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

3341
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
5✔
3342
                if err != nil {
5✔
3343
                        return err
×
3344
                }
×
3345

3346
                targetNode = &node
5✔
3347

5✔
3348
                return nil
5✔
3349
        }
3350

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

3362
        return targetNode, err
5✔
3363
}
3364

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

25✔
3374
        copy(node1Key[:], info.NodeKey1Bytes[:])
25✔
3375
        copy(node2Key[:], info.NodeKey2Bytes[:])
25✔
3376

25✔
3377
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
25✔
3378
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
25✔
3379

25✔
3380
        return node1Key[:], node2Key[:]
25✔
3381
}
25✔
3382

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

14✔
3392
        var (
14✔
3393
                edgeInfo *models.ChannelEdgeInfo
14✔
3394
                policy1  *models.ChannelEdgePolicy
14✔
3395
                policy2  *models.ChannelEdgePolicy
14✔
3396
        )
14✔
3397

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

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

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

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

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

3449
                policy1 = e1
4✔
3450
                policy2 = e2
4✔
3451

4✔
3452
                return nil
4✔
3453
        }, func() {
14✔
3454
                edgeInfo = nil
14✔
3455
                policy1 = nil
14✔
3456
                policy2 = nil
14✔
3457
        })
14✔
3458
        if err != nil {
27✔
3459
                return nil, nil, nil, err
13✔
3460
        }
13✔
3461

3462
        return edgeInfo, policy1, policy2, nil
4✔
3463
}
3464

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

2,692✔
3478
        var (
2,692✔
3479
                edgeInfo  *models.ChannelEdgeInfo
2,692✔
3480
                policy1   *models.ChannelEdgePolicy
2,692✔
3481
                policy2   *models.ChannelEdgePolicy
2,692✔
3482
                channelID [8]byte
2,692✔
3483
        )
2,692✔
3484

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

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

3505
                byteOrder.PutUint64(channelID[:], chanID)
2,692✔
3506

2,692✔
3507
                // Now, attempt to fetch edge.
2,692✔
3508
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
2,692✔
3509

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

3521
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
5✔
3522
                                zombieIndex, chanID,
5✔
3523
                        )
5✔
3524
                        if !isZombie {
8✔
3525
                                return ErrEdgeNotFound
3✔
3526
                        }
3✔
3527

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

5✔
3537
                        return ErrZombieEdge
5✔
3538
                }
3539

3540
                // Otherwise, we'll just return the error if any.
3541
                if err != nil {
2,690✔
3542
                        return err
×
3543
                }
×
3544

3545
                edgeInfo = &edge
2,690✔
3546

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

3556
                policy1 = e1
2,690✔
3557
                policy2 = e2
2,690✔
3558

2,690✔
3559
                return nil
2,690✔
3560
        }, func() {
2,692✔
3561
                edgeInfo = nil
2,692✔
3562
                policy1 = nil
2,692✔
3563
                policy2 = nil
2,692✔
3564
        })
2,692✔
3565
        if errors.Is(err, ErrZombieEdge) {
2,697✔
3566
                return edgeInfo, nil, nil, err
5✔
3567
        }
5✔
3568
        if err != nil {
2,693✔
3569
                return nil, nil, nil, err
3✔
3570
        }
3✔
3571

3572
        return edgeInfo, policy1, policy2, nil
2,690✔
3573
}
3574

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

3594
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
16✔
3595

16✔
3596
                return err
16✔
3597
        }, func() {
16✔
3598
                nodeIsPublic = false
16✔
3599
        })
16✔
3600
        if err != nil {
16✔
3601
                return false, err
×
3602
        }
×
3603

3604
        return nodeIsPublic, nil
16✔
3605
}
3606

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

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

49✔
3624
        return bldr.Script()
49✔
3625
}
3626

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

3635
        // OutPoint is the outpoint of the target channel.
3636
        OutPoint wire.OutPoint
3637
}
3638

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

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

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

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

3683
                                edgeInfo, err := fetchChanEdgeInfo(
45✔
3684
                                        edgeIndex, chanID,
45✔
3685
                                )
45✔
3686
                                if err != nil {
45✔
3687
                                        return err
×
3688
                                }
×
3689

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

3698
                                edgePoints = append(edgePoints, EdgePoint{
45✔
3699
                                        FundingPkScript: pkScript,
45✔
3700
                                        OutPoint:        chanPoint,
45✔
3701
                                })
45✔
3702

45✔
3703
                                return nil
45✔
3704
                        },
3705
                )
3706
        }, func() {
25✔
3707
                edgePoints = nil
25✔
3708
        }); err != nil {
25✔
3709
                return nil, err
×
3710
        }
×
3711

3712
        return edgePoints, nil
25✔
3713
}
3714

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

130✔
3721
        c.cacheMu.Lock()
130✔
3722
        defer c.cacheMu.Unlock()
130✔
3723

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

3735
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
130✔
3736
        })
3737
        if err != nil {
130✔
3738
                return err
×
3739
        }
×
3740

3741
        c.rejectCache.remove(chanID)
130✔
3742
        c.chanCache.remove(chanID)
130✔
3743

130✔
3744
        return nil
130✔
3745
}
3746

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

157✔
3753
        var k [8]byte
157✔
3754
        byteOrder.PutUint64(k[:], chanID)
157✔
3755

157✔
3756
        var v [66]byte
157✔
3757
        copy(v[:33], pubKey1[:])
157✔
3758
        copy(v[33:], pubKey2[:])
157✔
3759

157✔
3760
        return zombieIndex.Put(k[:], v[:])
157✔
3761
}
157✔
3762

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

28✔
3768
        return c.markEdgeLiveUnsafe(nil, chanID)
28✔
3769
}
28✔
3770

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

3788
                var k [8]byte
28✔
3789
                byteOrder.PutUint64(k[:], chanID)
28✔
3790

28✔
3791
                if len(zombieIndex.Get(k[:])) == 0 {
30✔
3792
                        return ErrZombieEdgeNotFound
2✔
3793
                }
2✔
3794

3795
                return zombieIndex.Delete(k[:])
26✔
3796
        }
3797

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

3810
        c.rejectCache.remove(chanID)
26✔
3811
        c.chanCache.remove(chanID)
26✔
3812

26✔
3813
        return nil
26✔
3814
}
3815

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

14✔
3822
        var (
14✔
3823
                isZombie         bool
14✔
3824
                pubKey1, pubKey2 [33]byte
14✔
3825
        )
14✔
3826

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

3837
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
14✔
3838

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

3850
        return isZombie, pubKey1, pubKey2, nil
14✔
3851
}
3852

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

212✔
3859
        var k [8]byte
212✔
3860
        byteOrder.PutUint64(k[:], chanID)
212✔
3861

212✔
3862
        v := zombieIndex.Get(k[:])
212✔
3863
        if v == nil {
338✔
3864
                return false, [33]byte{}, [33]byte{}
126✔
3865
        }
126✔
3866

3867
        var pubKey1, pubKey2 [33]byte
89✔
3868
        copy(pubKey1[:], v[:33])
89✔
3869
        copy(pubKey2[:], v[33:])
89✔
3870

89✔
3871
        return true, pubKey1, pubKey2
89✔
3872
}
3873

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

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

3898
        return numZombies, nil
4✔
3899
}
3900

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

3911
                var k [8]byte
1✔
3912
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3913

1✔
3914
                return closedScids.Put(k[:], []byte{})
1✔
3915
        }, func() {})
1✔
3916
}
3917

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

3929
                var k [8]byte
5✔
3930
                byteOrder.PutUint64(k[:], scid.ToUint64())
5✔
3931

5✔
3932
                if closedScids.Get(k[:]) != nil {
6✔
3933
                        isClosed = true
1✔
3934
                        return nil
1✔
3935
                }
1✔
3936

3937
                return nil
4✔
3938
        }, func() {
5✔
3939
                isClosed = false
5✔
3940
        })
5✔
3941
        if err != nil {
5✔
3942
                return false, err
×
3943
        }
×
3944

3945
        return isClosed, nil
5✔
3946
}
3947

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

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

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

240✔
3973
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
240✔
3974
}
240✔
3975

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

254✔
3983
        return c.db.fetchNodeFeatures(c.tx, nodePub)
254✔
3984
}
254✔
3985

3986
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3987
        node *models.LightningNode) error {
914✔
3988

914✔
3989
        var (
914✔
3990
                scratch [16]byte
914✔
3991
                b       bytes.Buffer
914✔
3992
        )
914✔
3993

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

914✔
4000
        // If the node has the update time set, write it, else write 0.
914✔
4001
        updateUnix := uint64(0)
914✔
4002
        if node.LastUpdate.Unix() > 0 {
1,689✔
4003
                updateUnix = uint64(node.LastUpdate.Unix())
775✔
4004
        }
775✔
4005

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

4011
        if _, err := b.Write(nodePub); err != nil {
914✔
4012
                return err
×
4013
        }
×
4014

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

4024
                return nodeBucket.Put(nodePub, b.Bytes())
89✔
4025
        }
4026

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

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

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

4047
        if err := node.Features.Encode(&b); err != nil {
828✔
4048
                return err
×
4049
        }
×
4050

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

4057
        for _, address := range node.Addresses {
1,893✔
4058
                if err := SerializeAddr(&b, address); err != nil {
1,065✔
4059
                        return err
×
4060
                }
×
4061
        }
4062

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

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

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

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

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

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

19✔
4099
                var oldIndexKey [8 + 33]byte
19✔
4100
                copy(oldIndexKey[:8], oldUpdateTime)
19✔
4101
                copy(oldIndexKey[8:], nodePub)
19✔
4102

19✔
4103
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
19✔
4104
                        return err
×
4105
                }
×
4106
        }
4107

4108
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
828✔
4109
                return err
×
4110
        }
×
4111

4112
        return nodeBucket.Put(nodePub, b.Bytes())
828✔
4113
}
4114

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

3,631✔
4118
        nodeBytes := nodeBucket.Get(nodePub)
3,631✔
4119
        if nodeBytes == nil {
3,720✔
4120
                return models.LightningNode{}, ErrGraphNodeNotFound
89✔
4121
        }
89✔
4122

4123
        nodeReader := bytes.NewReader(nodeBytes)
3,545✔
4124

3,545✔
4125
        return deserializeLightningNode(nodeReader)
3,545✔
4126
}
4127

4128
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4129
        *lnwire.FeatureVector, error) {
123✔
4130

123✔
4131
        var (
123✔
4132
                pubKey      route.Vertex
123✔
4133
                features    = lnwire.EmptyFeatureVector()
123✔
4134
                nodeScratch [8]byte
123✔
4135
        )
123✔
4136

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

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

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

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

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

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

4176
        if err := features.Decode(r); err != nil {
123✔
4177
                return pubKey, nil, err
×
4178
        }
×
4179

4180
        return pubKey, features, nil
123✔
4181
}
4182

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

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

8,533✔
4194
        if _, err := r.Read(scratch[:]); err != nil {
8,533✔
4195
                return models.LightningNode{}, err
×
4196
        }
×
4197

4198
        unix := int64(byteOrder.Uint64(scratch[:]))
8,533✔
4199
        node.LastUpdate = time.Unix(unix, 0)
8,533✔
4200

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

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

4209
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,533✔
4210
        if hasNodeAnn == 1 {
16,926✔
4211
                node.HaveNodeAnnouncement = true
8,393✔
4212
        } else {
8,536✔
4213
                node.HaveNodeAnnouncement = false
143✔
4214
        }
143✔
4215

4216
        // The rest of the data is optional, and will only be there if we got a
4217
        // node announcement for this node.
4218
        if !node.HaveNodeAnnouncement {
8,676✔
4219
                return node, nil
143✔
4220
        }
143✔
4221

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

4234
        node.Alias, err = wire.ReadVarString(r, 0)
8,393✔
4235
        if err != nil {
8,393✔
4236
                return models.LightningNode{}, err
×
4237
        }
×
4238

4239
        err = node.Features.Decode(r)
8,393✔
4240
        if err != nil {
8,393✔
4241
                return models.LightningNode{}, err
×
4242
        }
×
4243

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

8,393✔
4249
        var addresses []net.Addr
8,393✔
4250
        for i := 0; i < numAddresses; i++ {
19,043✔
4251
                address, err := DeserializeAddr(r)
10,650✔
4252
                if err != nil {
10,650✔
4253
                        return models.LightningNode{}, err
×
4254
                }
×
4255
                addresses = append(addresses, address)
10,650✔
4256
        }
4257
        node.Addresses = addresses
8,393✔
4258

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

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

4276
        if len(extraBytes) > 0 {
8,403✔
4277
                node.ExtraOpaqueData = extraBytes
10✔
4278
        }
10✔
4279

4280
        return node, nil
8,393✔
4281
}
4282

4283
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4284
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,485✔
4285

1,485✔
4286
        var b bytes.Buffer
1,485✔
4287

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

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

4306
        if err := wire.WriteVarBytes(&b, 0, featureBuf.Bytes()); err != nil {
1,485✔
4307
                return err
×
4308
        }
×
4309

4310
        authProof := edgeInfo.AuthProof
1,485✔
4311
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,485✔
4312
        if authProof != nil {
2,886✔
4313
                nodeSig1 = authProof.NodeSig1Bytes
1,401✔
4314
                nodeSig2 = authProof.NodeSig2Bytes
1,401✔
4315
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,401✔
4316
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,401✔
4317
        }
1,401✔
4318

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

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

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

4354
        return edgeIndex.Put(chanID[:], b.Bytes())
1,485✔
4355
}
4356

4357
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4358
        chanID []byte) (models.ChannelEdgeInfo, error) {
6,797✔
4359

6,797✔
4360
        edgeInfoBytes := edgeIndex.Get(chanID)
6,797✔
4361
        if edgeInfoBytes == nil {
6,861✔
4362
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
64✔
4363
        }
64✔
4364

4365
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
6,736✔
4366

6,736✔
4367
        return deserializeChanEdgeInfo(edgeInfoReader)
6,736✔
4368
}
4369

4370
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
7,278✔
4371
        var (
7,278✔
4372
                err      error
7,278✔
4373
                edgeInfo models.ChannelEdgeInfo
7,278✔
4374
        )
7,278✔
4375

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

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

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

7,278✔
4402
        proof := &models.ChannelAuthProof{}
7,278✔
4403

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

4421
        if !proof.IsEmpty() {
11,453✔
4422
                edgeInfo.AuthProof = proof
4,175✔
4423
        }
4,175✔
4424

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

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

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

4452
        return edgeInfo, nil
7,278✔
4453
}
4454

4455
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4456
        from, to []byte) error {
2,670✔
4457

2,670✔
4458
        var edgeKey [33 + 8]byte
2,670✔
4459
        copy(edgeKey[:], from)
2,670✔
4460
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,670✔
4461

2,670✔
4462
        var b bytes.Buffer
2,670✔
4463
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,670✔
4464
                return err
×
4465
        }
×
4466

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

2,670✔
4474
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,670✔
4475
        if err != nil {
2,670✔
4476
                return err
×
4477
        }
×
4478

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

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

×
4506
                        return err
×
4507
                }
×
4508

4509
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
30✔
4510

30✔
4511
                var oldIndexKey [8 + 8]byte
30✔
4512
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
30✔
4513
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
30✔
4514

30✔
4515
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
30✔
UNCOV
4516
                        return err
×
4517
                }
×
4518
        }
4519

4520
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,670✔
UNCOV
4521
                return err
×
4522
        }
×
4523

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

4533
        return edges.Put(edgeKey[:], b.Bytes())
2,670✔
4534
}
4535

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

2,934✔
4548
        var disabledEdgeKey [8 + 1]byte
2,934✔
4549
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,934✔
4550
        if direction {
4,399✔
4551
                disabledEdgeKey[8] = 1
1,465✔
4552
        }
1,465✔
4553

4554
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,934✔
4555
                disabledEdgePolicyBucket,
2,934✔
4556
        )
2,934✔
4557
        if err != nil {
2,934✔
UNCOV
4558
                return err
×
4559
        }
×
4560

4561
        if disabled {
2,963✔
4562
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4563
        }
29✔
4564

4565
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,908✔
4566
}
4567

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

2,963✔
4573
        var edgeKey [33 + 8]byte
2,963✔
4574
        copy(edgeKey[:], from)
2,963✔
4575
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,963✔
4576

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

4582
        return edges.Put(edgeKey[:], unknownPolicy)
2,963✔
4583
}
4584

4585
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4586
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
13,471✔
4587

13,471✔
4588
        var edgeKey [33 + 8]byte
13,471✔
4589
        copy(edgeKey[:], nodePub)
13,471✔
4590
        copy(edgeKey[33:], chanID)
13,471✔
4591

13,471✔
4592
        edgeBytes := edges.Get(edgeKey[:])
13,471✔
4593
        if edgeBytes == nil {
13,471✔
UNCOV
4594
                return nil, ErrEdgeNotFound
×
4595
        }
×
4596

4597
        // No need to deserialize unknown policy.
4598
        if bytes.Equal(edgeBytes, unknownPolicy) {
14,922✔
4599
                return nil, nil
1,451✔
4600
        }
1,451✔
4601

4602
        edgeReader := bytes.NewReader(edgeBytes)
12,023✔
4603

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

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

UNCOV
4616
        case err != nil:
×
4617
                return nil, err
×
4618
        }
4619

4620
        return ep, nil
12,021✔
4621
}
4622

4623
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4624
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4625
        error) {
2,894✔
4626

2,894✔
4627
        edgeInfo := edgeIndex.Get(chanID)
2,894✔
4628
        if edgeInfo == nil {
2,894✔
UNCOV
4629
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4630
                        chanID)
×
4631
        }
×
4632

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

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

4652
        return edge1, edge2, nil
2,894✔
4653
}
4654

4655
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4656
        to []byte) error {
2,672✔
4657

2,672✔
4658
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,672✔
4659
        if err != nil {
2,672✔
UNCOV
4660
                return err
×
4661
        }
×
4662

4663
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,672✔
UNCOV
4664
                return err
×
4665
        }
×
4666

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

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

4697
        if _, err := w.Write(to); err != nil {
2,672✔
UNCOV
4698
                return err
×
4699
        }
×
4700

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

4713
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,672✔
UNCOV
4714
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
UNCOV
4715
        }
×
4716
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,672✔
UNCOV
4717
                return err
×
4718
        }
×
4719

4720
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,672✔
UNCOV
4721
                return err
×
4722
        }
×
4723

4724
        return nil
2,672✔
4725
}
4726

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

×
4737
                return nil, err
×
4738
        }
×
4739

4740
        return edge, err
12,051✔
4741
}
4742

4743
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4744
        error) {
13,064✔
4745

13,064✔
4746
        edge := &models.ChannelEdgePolicy{}
13,064✔
4747

13,064✔
4748
        var err error
13,064✔
4749
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
13,064✔
4750
        if err != nil {
13,064✔
UNCOV
4751
                return nil, err
×
4752
        }
×
4753

4754
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
13,064✔
UNCOV
4755
                return nil, err
×
4756
        }
×
4757

4758
        var scratch [8]byte
13,064✔
4759
        if _, err := r.Read(scratch[:]); err != nil {
13,064✔
UNCOV
4760
                return nil, err
×
4761
        }
×
4762
        unix := int64(byteOrder.Uint64(scratch[:]))
13,064✔
4763
        edge.LastUpdate = time.Unix(unix, 0)
13,064✔
4764

13,064✔
4765
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
13,064✔
UNCOV
4766
                return nil, err
×
4767
        }
×
4768
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
13,064✔
UNCOV
4769
                return nil, err
×
4770
        }
×
4771
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
13,064✔
UNCOV
4772
                return nil, err
×
4773
        }
×
4774

4775
        var n uint64
13,064✔
4776
        if err := binary.Read(r, byteOrder, &n); err != nil {
13,064✔
UNCOV
4777
                return nil, err
×
4778
        }
×
4779
        edge.MinHTLC = lnwire.MilliSatoshi(n)
13,064✔
4780

13,064✔
4781
        if err := binary.Read(r, byteOrder, &n); err != nil {
13,064✔
UNCOV
4782
                return nil, err
×
4783
        }
×
4784
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
13,064✔
4785

13,064✔
4786
        if err := binary.Read(r, byteOrder, &n); err != nil {
13,064✔
UNCOV
4787
                return nil, err
×
4788
        }
×
4789
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
13,064✔
4790

13,064✔
4791
        if _, err := r.Read(edge.ToNode[:]); err != nil {
13,064✔
UNCOV
4792
                return nil, err
×
4793
        }
×
4794

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

4807
        // See if optional fields are present.
4808
        if edge.MessageFlags.HasMaxHtlc() {
25,159✔
4809
                // The max_htlc field should be at the beginning of the opaque
12,095✔
4810
                // bytes.
12,095✔
4811
                opq := edge.ExtraOpaqueData
12,095✔
4812

12,095✔
4813
                // If the max_htlc field is not present, it might be old data
12,095✔
4814
                // stored before this field was validated. We'll return the
12,095✔
4815
                // edge along with an error.
12,095✔
4816
                if len(opq) < 8 {
12,099✔
4817
                        return edge, ErrEdgePolicyOptionalFieldNotFound
4✔
4818
                }
4✔
4819

4820
                maxHtlc := byteOrder.Uint64(opq[:8])
12,091✔
4821
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
12,091✔
4822

12,091✔
4823
                // Exclude the parsed field from the rest of the opaque data.
12,091✔
4824
                edge.ExtraOpaqueData = opq[8:]
12,091✔
4825
        }
4826

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

4838
        val, ok := typeMap[lnwire.FeeRecordType]
13,060✔
4839
        if ok && val == nil {
14,796✔
4840
                edge.InboundFee = fn.Some(inboundFee)
1,736✔
4841
        }
1,736✔
4842

4843
        return edge, nil
13,060✔
4844
}
4845

4846
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4847
// KVStore and a kvdb.RTx.
4848
type chanGraphNodeTx struct {
4849
        tx   kvdb.RTx
4850
        db   *KVStore
4851
        node *models.LightningNode
4852
}
4853

4854
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4855
// interface.
4856
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4857

4858
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4859
        node *models.LightningNode) *chanGraphNodeTx {
4,105✔
4860

4,105✔
4861
        return &chanGraphNodeTx{
4,105✔
4862
                tx:   tx,
4,105✔
4863
                db:   db,
4,105✔
4864
                node: node,
4,105✔
4865
        }
4,105✔
4866
}
4,105✔
4867

4868
// Node returns the raw information of the node.
4869
//
4870
// NOTE: This is a part of the NodeRTx interface.
4871
func (c *chanGraphNodeTx) Node() *models.LightningNode {
5,022✔
4872
        return c.node
5,022✔
4873
}
5,022✔
4874

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

4886
        return newChanGraphNodeTx(c.tx, c.db, node), nil
2,944✔
4887
}
4888

4889
// ForEachChannel can be used to iterate over the node's channels under
4890
// the same transaction used to fetch the node.
4891
//
4892
// NOTE: This is a part of the NodeRTx interface.
4893
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4894
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
965✔
4895

965✔
4896
        return c.db.forEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
965✔
4897
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
965✔
4898
                        policy2 *models.ChannelEdgePolicy) error {
3,909✔
4899

2,944✔
4900
                        return f(info, policy1, policy2)
2,944✔
4901
                },
2,944✔
4902
        )
4903
}
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