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

lightningnetwork / lnd / 16200890897

10 Jul 2025 04:39PM UTC coverage: 67.437% (+0.02%) from 67.417%
16200890897

Pull #10015

github

web-flow
Merge 46d2623a2 into 04a2be29d
Pull Request #10015: graph/db: add zombie channels cleanup routine

58 of 63 new or added lines in 2 files covered. (92.06%)

86 existing lines in 18 files now uncovered.

135349 of 200705 relevant lines covered (67.44%)

21863.02 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

302
                channelMap[key] = edge
999✔
303

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

310
        return channelMap, nil
148✔
311
}
312

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

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

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

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

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

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

369
        return nil
173✔
370
}
371

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

689✔
602
                if p1 != nil {
1,377✔
603
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
1,024✔
604
                                directedChannel.InboundFee = fee
336✔
605
                        })
336✔
606
                }
607

608
                if node == e.NodeKey2Bytes {
1,035✔
609
                        directedChannel.OtherNode = e.NodeKey1Bytes
346✔
610
                }
346✔
611

612
                return cb(directedChannel)
689✔
613
        }
614

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

723
                                channels[e.ChannelID] = directedChannel
190✔
724

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

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

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

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

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

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

4✔
768
                                        return nil
4✔
769
                                }
4✔
770

771
                                chanEdgeFound[chanID] = struct{}{}
7✔
772

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

784
        return disabledChanIDs, nil
6✔
785
}
786

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

904
                node, err := sourceNodeWithTx(nodes)
241✔
905
                if err != nil {
245✔
906
                        return err
4✔
907
                }
4✔
908
                source = node
240✔
909

240✔
910
                return nil
240✔
911
        }, func() {
241✔
912
                source = nil
241✔
913
        })
241✔
914
        if err != nil {
245✔
915
                return nil, err
4✔
916
        }
4✔
917

918
        return source, nil
240✔
919
}
920

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

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

938
        return &node, nil
509✔
939
}
940

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

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

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

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

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

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

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

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

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

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

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

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

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

5✔
1016
        var alias string
5✔
1017

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

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

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

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

4✔
1039
                return nil
4✔
1040
        }, func() {
5✔
1041
                alias = ""
5✔
1042
        })
5✔
1043
        if err != nil {
6✔
1044
                return "", err
1✔
1045
        }
1✔
1046

1047
        return alias, nil
4✔
1048
}
1049

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1319
                        return nil
89✔
1320
                }
1321

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

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

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

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

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

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

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

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

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

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

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

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

1387
                edge.AuthProof = proof
5✔
1388

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1565
        return prunedNodes, err
26✔
1566
}
1567

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

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

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

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

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

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

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

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

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

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

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

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

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

1654
                        return nil, err
×
1655
                }
1656

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

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

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

1668
        return pruned, err
271✔
1669
}
1670

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1798
        return removedChans, nil
151✔
1799
}
1800

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

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

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

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

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

38✔
1835
                return nil
38✔
1836
        }, func() {})
56✔
1837
        if err != nil {
77✔
1838
                return nil, 0, err
21✔
1839
        }
21✔
1840

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

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

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

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

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

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

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

1899
                return nil
86✔
1900
        }, func() {
147✔
1901
                infos = nil
147✔
1902
        })
147✔
1903
        if err != nil {
208✔
1904
                return nil, err
61✔
1905
        }
61✔
1906

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

1912
        return infos, nil
86✔
1913
}
1914

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

1930
        return chanID, nil
4✔
1931
}
1932

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

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

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

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

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

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

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

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

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

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

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

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

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

2001
        return cid, nil
6✔
2002
}
2003

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

12✔
2099
                                continue
12✔
2100
                        }
2101

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

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

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

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

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

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

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

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

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

2180
        return edgesInHorizon, nil
146✔
2181
}
2182

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

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

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

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

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

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

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

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

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

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

2245
        return nodesInHorizon, nil
11✔
2246
}
2247

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

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

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

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

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

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

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

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

89✔
2298
                                if isZombie {
133✔
2299
                                        knownZombies = append(
44✔
2300
                                                knownZombies, info,
44✔
2301
                                        )
44✔
2302

44✔
2303
                                        continue
44✔
2304
                                }
2305
                        }
2306

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

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

2324
                return ogChanIDs, nil, nil
×
2325

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

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

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

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

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

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

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

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

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

2370
        return chanInfo
199✔
2371
}
2372

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

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

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

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

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

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

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

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

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

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

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

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

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

22✔
2458
                                continue
22✔
2459
                        }
2460

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

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

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

×
2472
                                        return err
×
2473
                                }
×
2474

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

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

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

×
2487
                                        return err
×
2488
                                }
×
2489

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

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

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

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

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

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

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

2530
        return channelRanges, nil
11✔
2531
}
2532

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

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

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

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

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

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

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

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

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

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

2621
                return nil
7✔
2622
        }
2623

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

2632
                return chanEdges, nil
7✔
2633
        }
2634

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

2640
        return chanEdges, nil
×
2641
}
2642

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

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

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

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

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

2682
        return nil
142✔
2683
}
2684

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2862
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
2,674✔
2863
                        if err != nil {
2,678✔
2864
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
4✔
2865
                        }
4✔
2866

2867
                        // Silence ErrEdgeNotFound so that the batch can
2868
                        // succeed, but propagate the error via local state.
2869
                        if errors.Is(err, ErrEdgeNotFound) {
2,678✔
2870
                                edgeNotFound = true
4✔
2871
                                return nil
4✔
2872
                        }
4✔
2873

2874
                        return err
2,670✔
2875
                },
2876
                OnCommit: func(err error) error {
2,675✔
2877
                        switch {
2,675✔
2878
                        case err != nil:
1✔
2879
                                return err
1✔
2880
                        case edgeNotFound:
4✔
2881
                                return ErrEdgeNotFound
4✔
2882
                        default:
2,670✔
2883
                                c.updateEdgeCache(edge, isUpdate1)
2,670✔
2884
                                return nil
2,670✔
2885
                        }
2886
                },
2887
        }
2888

2889
        err := c.chanScheduler.Execute(ctx, r)
2,675✔
2890

2,675✔
2891
        return from, to, err
2,675✔
2892
}
2893

2894
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
2895
        isUpdate1 bool) {
2,670✔
2896

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

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

2924
// updateEdgePolicy attempts to update an edge's policy within the relevant
2925
// buckets using an existing database transaction. The returned boolean will be
2926
// true if the updated policy belongs to node1, and false if the policy belonged
2927
// to node2.
2928
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
2929
        route.Vertex, route.Vertex, bool, error) {
2,674✔
2930

2,674✔
2931
        var noVertex route.Vertex
2,674✔
2932

2,674✔
2933
        edges := tx.ReadWriteBucket(edgeBucket)
2,674✔
2934
        if edges == nil {
2,674✔
2935
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2936
        }
×
2937
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,674✔
2938
        if edgeIndex == nil {
2,674✔
2939
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2940
        }
×
2941

2942
        // Create the channelID key be converting the channel ID
2943
        // integer into a byte slice.
2944
        var chanID [8]byte
2,674✔
2945
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,674✔
2946

2,674✔
2947
        // With the channel ID, we then fetch the value storing the two
2,674✔
2948
        // nodes which connect this channel edge.
2,674✔
2949
        nodeInfo := edgeIndex.Get(chanID[:])
2,674✔
2950
        if nodeInfo == nil {
2,678✔
2951
                return noVertex, noVertex, false, ErrEdgeNotFound
4✔
2952
        }
4✔
2953

2954
        // Depending on the flags value passed above, either the first
2955
        // or second edge policy is being updated.
2956
        var fromNode, toNode []byte
2,670✔
2957
        var isUpdate1 bool
2,670✔
2958
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
4,009✔
2959
                fromNode = nodeInfo[:33]
1,339✔
2960
                toNode = nodeInfo[33:66]
1,339✔
2961
                isUpdate1 = true
1,339✔
2962
        } else {
2,673✔
2963
                fromNode = nodeInfo[33:66]
1,334✔
2964
                toNode = nodeInfo[:33]
1,334✔
2965
                isUpdate1 = false
1,334✔
2966
        }
1,334✔
2967

2968
        // Finally, with the direction of the edge being updated
2969
        // identified, we update the on-disk edge representation.
2970
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,670✔
2971
        if err != nil {
2,670✔
2972
                return noVertex, noVertex, false, err
×
2973
        }
×
2974

2975
        var (
2,670✔
2976
                fromNodePubKey route.Vertex
2,670✔
2977
                toNodePubKey   route.Vertex
2,670✔
2978
        )
2,670✔
2979
        copy(fromNodePubKey[:], fromNode)
2,670✔
2980
        copy(toNodePubKey[:], toNode)
2,670✔
2981

2,670✔
2982
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
2,670✔
2983
}
2984

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

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

13✔
3001
                // If this edge doesn't extend to the source node, we'll
13✔
3002
                // terminate our search as we can now conclude that the node is
13✔
3003
                // publicly advertised within the graph due to the local node
13✔
3004
                // knowing of the current edge.
13✔
3005
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
13✔
3006
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
19✔
3007

6✔
3008
                        nodeIsPublic = true
6✔
3009
                        return errDone
6✔
3010
                }
6✔
3011

3012
                // Since the edge _does_ extend to the source node, we'll also
3013
                // need to ensure that this is a public edge.
3014
                if info.AuthProof != nil {
19✔
3015
                        nodeIsPublic = true
9✔
3016
                        return errDone
9✔
3017
                }
9✔
3018

3019
                // Otherwise, we'll continue our search.
3020
                return nil
4✔
3021
        })
3022
        if err != nil && !errors.Is(err, errDone) {
16✔
3023
                return false, err
×
3024
        }
×
3025

3026
        return nodeIsPublic, nil
16✔
3027
}
3028

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

3,654✔
3036
        return c.fetchLightningNode(tx, nodePub)
3,654✔
3037
}
3,654✔
3038

3039
// FetchLightningNode attempts to look up a target node by its identity public
3040
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3041
// returned.
3042
func (c *KVStore) FetchLightningNode(_ context.Context,
3043
        nodePub route.Vertex) (*models.LightningNode, error) {
162✔
3044

162✔
3045
        return c.fetchLightningNode(nil, nodePub)
162✔
3046
}
162✔
3047

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

3,813✔
3055
        var node *models.LightningNode
3,813✔
3056
        fetch := func(tx kvdb.RTx) error {
7,626✔
3057
                // First grab the nodes bucket which stores the mapping from
3,813✔
3058
                // pubKey to node information.
3,813✔
3059
                nodes := tx.ReadBucket(nodeBucket)
3,813✔
3060
                if nodes == nil {
3,813✔
3061
                        return ErrGraphNotFound
×
3062
                }
×
3063

3064
                // If a key for this serialized public key isn't found, then
3065
                // the target node doesn't exist within the database.
3066
                nodeBytes := nodes.Get(nodePub[:])
3,813✔
3067
                if nodeBytes == nil {
3,831✔
3068
                        return ErrGraphNodeNotFound
18✔
3069
                }
18✔
3070

3071
                // If the node is found, then we can de deserialize the node
3072
                // information to return to the user.
3073
                nodeReader := bytes.NewReader(nodeBytes)
3,798✔
3074
                n, err := deserializeLightningNode(nodeReader)
3,798✔
3075
                if err != nil {
3,798✔
3076
                        return err
×
3077
                }
×
3078

3079
                node = &n
3,798✔
3080

3,798✔
3081
                return nil
3,798✔
3082
        }
3083

3084
        if tx == nil {
3,999✔
3085
                err := kvdb.View(
186✔
3086
                        c.db, fetch, func() {
372✔
3087
                                node = nil
186✔
3088
                        },
186✔
3089
                )
3090
                if err != nil {
193✔
3091
                        return nil, err
7✔
3092
                }
7✔
3093

3094
                return node, nil
182✔
3095
        }
3096

3097
        err := fetch(tx)
3,627✔
3098
        if err != nil {
3,638✔
3099
                return nil, err
11✔
3100
        }
11✔
3101

3102
        return node, nil
3,616✔
3103
}
3104

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

20✔
3113
        var (
20✔
3114
                updateTime time.Time
20✔
3115
                exists     bool
20✔
3116
        )
20✔
3117

20✔
3118
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
40✔
3119
                // First grab the nodes bucket which stores the mapping from
20✔
3120
                // pubKey to node information.
20✔
3121
                nodes := tx.ReadBucket(nodeBucket)
20✔
3122
                if nodes == nil {
20✔
3123
                        return ErrGraphNotFound
×
3124
                }
×
3125

3126
                // If a key for this serialized public key isn't found, we can
3127
                // exit early.
3128
                nodeBytes := nodes.Get(nodePub[:])
20✔
3129
                if nodeBytes == nil {
26✔
3130
                        exists = false
6✔
3131
                        return nil
6✔
3132
                }
6✔
3133

3134
                // Otherwise we continue on to obtain the time stamp
3135
                // representing the last time the data for this node was
3136
                // updated.
3137
                nodeReader := bytes.NewReader(nodeBytes)
17✔
3138
                node, err := deserializeLightningNode(nodeReader)
17✔
3139
                if err != nil {
17✔
3140
                        return err
×
3141
                }
×
3142

3143
                exists = true
17✔
3144
                updateTime = node.LastUpdate
17✔
3145

17✔
3146
                return nil
17✔
3147
        }, func() {
20✔
3148
                updateTime = time.Time{}
20✔
3149
                exists = false
20✔
3150
        })
20✔
3151
        if err != nil {
20✔
3152
                return time.Time{}, exists, err
×
3153
        }
×
3154

3155
        return updateTime, exists, nil
20✔
3156
}
3157

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

1,270✔
3164
        traversal := func(tx kvdb.RTx) error {
2,540✔
3165
                edges := tx.ReadBucket(edgeBucket)
1,270✔
3166
                if edges == nil {
1,270✔
3167
                        return ErrGraphNotFound
×
3168
                }
×
3169
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,270✔
3170
                if edgeIndex == nil {
1,270✔
3171
                        return ErrGraphNoEdgesFound
×
3172
                }
×
3173

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

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

3201
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,845✔
3202
                                edges, chanID, nodePub,
3,845✔
3203
                        )
3,845✔
3204
                        if err != nil {
3,845✔
3205
                                return err
×
3206
                        }
×
3207

3208
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,845✔
3209
                        if err != nil {
3,845✔
3210
                                return err
×
3211
                        }
×
3212

3213
                        incomingPolicy, err := fetchChanEdgePolicy(
3,845✔
3214
                                edges, chanID, otherNode[:],
3,845✔
3215
                        )
3,845✔
3216
                        if err != nil {
3,845✔
3217
                                return err
×
3218
                        }
×
3219

3220
                        // Finally, we execute the callback.
3221
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,845✔
3222
                        if err != nil {
3,857✔
3223
                                return err
12✔
3224
                        }
12✔
3225
                }
3226

3227
                return nil
1,261✔
3228
        }
3229

3230
        // If no transaction was provided, then we'll create a new transaction
3231
        // to execute the transaction within.
3232
        if tx == nil {
1,302✔
3233
                return kvdb.View(db, traversal, func() {})
64✔
3234
        }
3235

3236
        // Otherwise, we re-use the existing transaction to execute the graph
3237
        // traversal.
3238
        return traversal(tx)
1,241✔
3239
}
3240

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

9✔
3253
        return nodeTraversal(nil, nodePub[:], c.db, func(_ kvdb.RTx,
9✔
3254
                info *models.ChannelEdgeInfo, policy,
9✔
3255
                policy2 *models.ChannelEdgePolicy) error {
22✔
3256

13✔
3257
                return cb(info, policy, policy2)
13✔
3258
        })
13✔
3259
}
3260

3261
// ForEachSourceNodeChannel iterates through all channels of the source node,
3262
// executing the passed callback on each. The callback is provided with the
3263
// channel's outpoint, whether we have a policy for the channel and the channel
3264
// peer's node information.
3265
func (c *KVStore) ForEachSourceNodeChannel(_ context.Context,
3266
        cb func(chanPoint wire.OutPoint, havePolicy bool,
3267
                otherNode *models.LightningNode) error) error {
4✔
3268

4✔
3269
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3270
                nodes := tx.ReadBucket(nodeBucket)
4✔
3271
                if nodes == nil {
4✔
3272
                        return ErrGraphNotFound
×
3273
                }
×
3274

3275
                node, err := sourceNodeWithTx(nodes)
4✔
3276
                if err != nil {
4✔
3277
                        return err
×
3278
                }
×
3279

3280
                return nodeTraversal(
4✔
3281
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
4✔
3282
                                info *models.ChannelEdgeInfo,
4✔
3283
                                policy, _ *models.ChannelEdgePolicy) error {
9✔
3284

5✔
3285
                                peer, err := c.fetchOtherNode(
5✔
3286
                                        tx, info, node.PubKeyBytes[:],
5✔
3287
                                )
5✔
3288
                                if err != nil {
5✔
3289
                                        return err
×
3290
                                }
×
3291

3292
                                return cb(
5✔
3293
                                        info.ChannelPoint, policy != nil, peer,
5✔
3294
                                )
5✔
3295
                        },
3296
                )
3297
        }, func() {})
4✔
3298
}
3299

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

1,001✔
3318
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,001✔
3319
}
1,001✔
3320

3321
// fetchOtherNode attempts to fetch the full LightningNode that's opposite of
3322
// the target node in the channel. This is useful when one knows the pubkey of
3323
// one of the nodes, and wishes to obtain the full LightningNode for the other
3324
// end of the channel.
3325
func (c *KVStore) fetchOtherNode(tx kvdb.RTx,
3326
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3327
        *models.LightningNode, error) {
5✔
3328

5✔
3329
        // Ensure that the node passed in is actually a member of the channel.
5✔
3330
        var targetNodeBytes [33]byte
5✔
3331
        switch {
5✔
3332
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
4✔
3333
                targetNodeBytes = channel.NodeKey2Bytes
4✔
3334
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
4✔
3335
                targetNodeBytes = channel.NodeKey1Bytes
4✔
3336
        default:
×
3337
                return nil, fmt.Errorf("node not participating in this channel")
×
3338
        }
3339

3340
        var targetNode *models.LightningNode
5✔
3341
        fetchNodeFunc := func(tx kvdb.RTx) error {
10✔
3342
                // First grab the nodes bucket which stores the mapping from
5✔
3343
                // pubKey to node information.
5✔
3344
                nodes := tx.ReadBucket(nodeBucket)
5✔
3345
                if nodes == nil {
5✔
3346
                        return ErrGraphNotFound
×
3347
                }
×
3348

3349
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
5✔
3350
                if err != nil {
5✔
3351
                        return err
×
3352
                }
×
3353

3354
                targetNode = &node
5✔
3355

5✔
3356
                return nil
5✔
3357
        }
3358

3359
        // If the transaction is nil, then we'll need to create a new one,
3360
        // otherwise we can use the existing db transaction.
3361
        var err error
5✔
3362
        if tx == nil {
5✔
3363
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3364
                        targetNode = nil
×
3365
                })
×
3366
        } else {
5✔
3367
                err = fetchNodeFunc(tx)
5✔
3368
        }
5✔
3369

3370
        return targetNode, err
5✔
3371
}
3372

3373
// computeEdgePolicyKeys is a helper function that can be used to compute the
3374
// keys used to index the channel edge policy info for the two nodes of the
3375
// edge. The keys for node 1 and node 2 are returned respectively.
3376
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
25✔
3377
        var (
25✔
3378
                node1Key [33 + 8]byte
25✔
3379
                node2Key [33 + 8]byte
25✔
3380
        )
25✔
3381

25✔
3382
        copy(node1Key[:], info.NodeKey1Bytes[:])
25✔
3383
        copy(node2Key[:], info.NodeKey2Bytes[:])
25✔
3384

25✔
3385
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
25✔
3386
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
25✔
3387

25✔
3388
        return node1Key[:], node2Key[:]
25✔
3389
}
25✔
3390

3391
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3392
// the channel identified by the funding outpoint. If the channel can't be
3393
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3394
// information for the channel itself is returned as well as two structs that
3395
// contain the routing policies for the channel in either direction.
3396
func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3397
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3398
        *models.ChannelEdgePolicy, error) {
14✔
3399

14✔
3400
        var (
14✔
3401
                edgeInfo *models.ChannelEdgeInfo
14✔
3402
                policy1  *models.ChannelEdgePolicy
14✔
3403
                policy2  *models.ChannelEdgePolicy
14✔
3404
        )
14✔
3405

14✔
3406
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
3407
                // First, grab the node bucket. This will be used to populate
14✔
3408
                // the Node pointers in each edge read from disk.
14✔
3409
                nodes := tx.ReadBucket(nodeBucket)
14✔
3410
                if nodes == nil {
14✔
3411
                        return ErrGraphNotFound
×
3412
                }
×
3413

3414
                // Next, grab the edge bucket which stores the edges, and also
3415
                // the index itself so we can group the directed edges together
3416
                // logically.
3417
                edges := tx.ReadBucket(edgeBucket)
14✔
3418
                if edges == nil {
14✔
3419
                        return ErrGraphNoEdgesFound
×
3420
                }
×
3421
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
3422
                if edgeIndex == nil {
14✔
3423
                        return ErrGraphNoEdgesFound
×
3424
                }
×
3425

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

3441
                // If the channel is found to exists, then we'll first retrieve
3442
                // the general information for the channel.
3443
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
4✔
3444
                if err != nil {
4✔
3445
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3446
                }
×
3447
                edgeInfo = &edge
4✔
3448

4✔
3449
                // Once we have the information about the channels' parameters,
4✔
3450
                // we'll fetch the routing policies for each for the directed
4✔
3451
                // edges.
4✔
3452
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
4✔
3453
                if err != nil {
4✔
3454
                        return fmt.Errorf("failed to find policy: %w", err)
×
3455
                }
×
3456

3457
                policy1 = e1
4✔
3458
                policy2 = e2
4✔
3459

4✔
3460
                return nil
4✔
3461
        }, func() {
14✔
3462
                edgeInfo = nil
14✔
3463
                policy1 = nil
14✔
3464
                policy2 = nil
14✔
3465
        })
14✔
3466
        if err != nil {
27✔
3467
                return nil, nil, nil, err
13✔
3468
        }
13✔
3469

3470
        return edgeInfo, policy1, policy2, nil
4✔
3471
}
3472

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

2,692✔
3486
        var (
2,692✔
3487
                edgeInfo  *models.ChannelEdgeInfo
2,692✔
3488
                policy1   *models.ChannelEdgePolicy
2,692✔
3489
                policy2   *models.ChannelEdgePolicy
2,692✔
3490
                channelID [8]byte
2,692✔
3491
        )
2,692✔
3492

2,692✔
3493
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
5,384✔
3494
                // First, grab the node bucket. This will be used to populate
2,692✔
3495
                // the Node pointers in each edge read from disk.
2,692✔
3496
                nodes := tx.ReadBucket(nodeBucket)
2,692✔
3497
                if nodes == nil {
2,692✔
3498
                        return ErrGraphNotFound
×
3499
                }
×
3500

3501
                // Next, grab the edge bucket which stores the edges, and also
3502
                // the index itself so we can group the directed edges together
3503
                // logically.
3504
                edges := tx.ReadBucket(edgeBucket)
2,692✔
3505
                if edges == nil {
2,692✔
3506
                        return ErrGraphNoEdgesFound
×
3507
                }
×
3508
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
2,692✔
3509
                if edgeIndex == nil {
2,692✔
3510
                        return ErrGraphNoEdgesFound
×
3511
                }
×
3512

3513
                byteOrder.PutUint64(channelID[:], chanID)
2,692✔
3514

2,692✔
3515
                // Now, attempt to fetch edge.
2,692✔
3516
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
2,692✔
3517

2,692✔
3518
                // If it doesn't exist, we'll quickly check our zombie index to
2,692✔
3519
                // see if we've previously marked it as so.
2,692✔
3520
                if errors.Is(err, ErrEdgeNotFound) {
2,696✔
3521
                        // If the zombie index doesn't exist, or the edge is not
4✔
3522
                        // marked as a zombie within it, then we'll return the
4✔
3523
                        // original ErrEdgeNotFound error.
4✔
3524
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3525
                        if zombieIndex == nil {
4✔
3526
                                return ErrEdgeNotFound
×
3527
                        }
×
3528

3529
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
4✔
3530
                                zombieIndex, chanID,
4✔
3531
                        )
4✔
3532
                        if !isZombie {
7✔
3533
                                return ErrEdgeNotFound
3✔
3534
                        }
3✔
3535

3536
                        // Otherwise, the edge is marked as a zombie, so we'll
3537
                        // populate the edge info with the public keys of each
3538
                        // party as this is the only information we have about
3539
                        // it and return an error signaling so.
3540
                        edgeInfo = &models.ChannelEdgeInfo{
4✔
3541
                                NodeKey1Bytes: pubKey1,
4✔
3542
                                NodeKey2Bytes: pubKey2,
4✔
3543
                        }
4✔
3544

4✔
3545
                        return ErrZombieEdge
4✔
3546
                }
3547

3548
                // Otherwise, we'll just return the error if any.
3549
                if err != nil {
2,691✔
3550
                        return err
×
3551
                }
×
3552

3553
                edgeInfo = &edge
2,691✔
3554

2,691✔
3555
                // Then we'll attempt to fetch the accompanying policies of this
2,691✔
3556
                // edge.
2,691✔
3557
                e1, e2, err := fetchChanEdgePolicies(
2,691✔
3558
                        edgeIndex, edges, channelID[:],
2,691✔
3559
                )
2,691✔
3560
                if err != nil {
2,691✔
3561
                        return err
×
3562
                }
×
3563

3564
                policy1 = e1
2,691✔
3565
                policy2 = e2
2,691✔
3566

2,691✔
3567
                return nil
2,691✔
3568
        }, func() {
2,692✔
3569
                edgeInfo = nil
2,692✔
3570
                policy1 = nil
2,692✔
3571
                policy2 = nil
2,692✔
3572
        })
2,692✔
3573
        if errors.Is(err, ErrZombieEdge) {
2,696✔
3574
                return edgeInfo, nil, nil, err
4✔
3575
        }
4✔
3576
        if err != nil {
2,694✔
3577
                return nil, nil, nil, err
3✔
3578
        }
3✔
3579

3580
        return edgeInfo, policy1, policy2, nil
2,691✔
3581
}
3582

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

3602
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
16✔
3603

16✔
3604
                return err
16✔
3605
        }, func() {
16✔
3606
                nodeIsPublic = false
16✔
3607
        })
16✔
3608
        if err != nil {
16✔
3609
                return false, err
×
3610
        }
×
3611

3612
        return nodeIsPublic, nil
16✔
3613
}
3614

3615
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3616
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
49✔
3617
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
49✔
3618
        if err != nil {
49✔
3619
                return nil, err
×
3620
        }
×
3621

3622
        // With the witness script generated, we'll now turn it into a p2wsh
3623
        // script:
3624
        //  * OP_0 <sha256(script)>
3625
        bldr := txscript.NewScriptBuilder(
49✔
3626
                txscript.WithScriptAllocSize(input.P2WSHSize),
49✔
3627
        )
49✔
3628
        bldr.AddOp(txscript.OP_0)
49✔
3629
        scriptHash := sha256.Sum256(witnessScript)
49✔
3630
        bldr.AddData(scriptHash[:])
49✔
3631

49✔
3632
        return bldr.Script()
49✔
3633
}
3634

3635
// EdgePoint couples the outpoint of a channel with the funding script that it
3636
// creates. The FilteredChainView will use this to watch for spends of this
3637
// edge point on chain. We require both of these values as depending on the
3638
// concrete implementation, either the pkScript, or the out point will be used.
3639
type EdgePoint struct {
3640
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3641
        FundingPkScript []byte
3642

3643
        // OutPoint is the outpoint of the target channel.
3644
        OutPoint wire.OutPoint
3645
}
3646

3647
// String returns a human readable version of the target EdgePoint. We return
3648
// the outpoint directly as it is enough to uniquely identify the edge point.
3649
func (e *EdgePoint) String() string {
×
3650
        return e.OutPoint.String()
×
3651
}
×
3652

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

3676
                // Once we have the proper bucket, we'll range over each key
3677
                // (which is the channel point for the channel) and decode it,
3678
                // accumulating each entry.
3679
                return chanIndex.ForEach(
25✔
3680
                        func(chanPointBytes, chanID []byte) error {
70✔
3681
                                chanPointReader := bytes.NewReader(
45✔
3682
                                        chanPointBytes,
45✔
3683
                                )
45✔
3684

45✔
3685
                                var chanPoint wire.OutPoint
45✔
3686
                                err := ReadOutpoint(chanPointReader, &chanPoint)
45✔
3687
                                if err != nil {
45✔
3688
                                        return err
×
3689
                                }
×
3690

3691
                                edgeInfo, err := fetchChanEdgeInfo(
45✔
3692
                                        edgeIndex, chanID,
45✔
3693
                                )
45✔
3694
                                if err != nil {
45✔
3695
                                        return err
×
3696
                                }
×
3697

3698
                                pkScript, err := genMultiSigP2WSH(
45✔
3699
                                        edgeInfo.BitcoinKey1Bytes[:],
45✔
3700
                                        edgeInfo.BitcoinKey2Bytes[:],
45✔
3701
                                )
45✔
3702
                                if err != nil {
45✔
3703
                                        return err
×
3704
                                }
×
3705

3706
                                edgePoints = append(edgePoints, EdgePoint{
45✔
3707
                                        FundingPkScript: pkScript,
45✔
3708
                                        OutPoint:        chanPoint,
45✔
3709
                                })
45✔
3710

45✔
3711
                                return nil
45✔
3712
                        },
3713
                )
3714
        }, func() {
25✔
3715
                edgePoints = nil
25✔
3716
        }); err != nil {
25✔
3717
                return nil, err
×
3718
        }
×
3719

3720
        return edgePoints, nil
25✔
3721
}
3722

3723
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3724
// zombie. This method is used on an ad-hoc basis, when channels need to be
3725
// marked as zombies outside the normal pruning cycle.
3726
func (c *KVStore) MarkEdgeZombie(chanID uint64,
3727
        pubKey1, pubKey2 [33]byte) error {
124✔
3728

124✔
3729
        c.cacheMu.Lock()
124✔
3730
        defer c.cacheMu.Unlock()
124✔
3731

124✔
3732
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
248✔
3733
                edges := tx.ReadWriteBucket(edgeBucket)
124✔
3734
                if edges == nil {
124✔
3735
                        return ErrGraphNoEdgesFound
×
3736
                }
×
3737
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
124✔
3738
                if err != nil {
124✔
3739
                        return fmt.Errorf("unable to create zombie "+
×
3740
                                "bucket: %w", err)
×
3741
                }
×
3742

3743
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
124✔
3744
        })
3745
        if err != nil {
124✔
3746
                return err
×
3747
        }
×
3748

3749
        c.rejectCache.remove(chanID)
124✔
3750
        c.chanCache.remove(chanID)
124✔
3751

124✔
3752
        return nil
124✔
3753
}
3754

3755
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3756
// keys should represent the node public keys of the two parties involved in the
3757
// edge.
3758
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3759
        pubKey2 [33]byte) error {
149✔
3760

149✔
3761
        var k [8]byte
149✔
3762
        byteOrder.PutUint64(k[:], chanID)
149✔
3763

149✔
3764
        var v [66]byte
149✔
3765
        copy(v[:33], pubKey1[:])
149✔
3766
        copy(v[33:], pubKey2[:])
149✔
3767

149✔
3768
        return zombieIndex.Put(k[:], v[:])
149✔
3769
}
149✔
3770

3771
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3772
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
23✔
3773
        c.cacheMu.Lock()
23✔
3774
        defer c.cacheMu.Unlock()
23✔
3775

23✔
3776
        return c.markEdgeLiveUnsafe(nil, chanID)
23✔
3777
}
23✔
3778

3779
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3780
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3781
// case a new transaction will be created.
3782
//
3783
// NOTE: this method MUST only be called if the cacheMu has already been
3784
// acquired.
3785
func (c *KVStore) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
23✔
3786
        dbFn := func(tx kvdb.RwTx) error {
46✔
3787
                edges := tx.ReadWriteBucket(edgeBucket)
23✔
3788
                if edges == nil {
23✔
3789
                        return ErrGraphNoEdgesFound
×
3790
                }
×
3791
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
23✔
3792
                if zombieIndex == nil {
23✔
3793
                        return nil
×
3794
                }
×
3795

3796
                var k [8]byte
23✔
3797
                byteOrder.PutUint64(k[:], chanID)
23✔
3798

23✔
3799
                if len(zombieIndex.Get(k[:])) == 0 {
25✔
3800
                        return ErrZombieEdgeNotFound
2✔
3801
                }
2✔
3802

3803
                return zombieIndex.Delete(k[:])
21✔
3804
        }
3805

3806
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3807
        // the existing transaction
3808
        var err error
23✔
3809
        if tx == nil {
46✔
3810
                err = kvdb.Update(c.db, dbFn, func() {})
46✔
3811
        } else {
×
3812
                err = dbFn(tx)
×
3813
        }
×
3814
        if err != nil {
25✔
3815
                return err
2✔
3816
        }
2✔
3817

3818
        c.rejectCache.remove(chanID)
21✔
3819
        c.chanCache.remove(chanID)
21✔
3820

21✔
3821
        return nil
21✔
3822
}
3823

3824
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3825
// zombie, then the two node public keys corresponding to this edge are also
3826
// returned.
3827
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte,
3828
        error) {
14✔
3829

14✔
3830
        var (
14✔
3831
                isZombie         bool
14✔
3832
                pubKey1, pubKey2 [33]byte
14✔
3833
        )
14✔
3834

14✔
3835
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
3836
                edges := tx.ReadBucket(edgeBucket)
14✔
3837
                if edges == nil {
14✔
3838
                        return ErrGraphNoEdgesFound
×
3839
                }
×
3840
                zombieIndex := edges.NestedReadBucket(zombieBucket)
14✔
3841
                if zombieIndex == nil {
14✔
3842
                        return nil
×
3843
                }
×
3844

3845
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
14✔
3846

14✔
3847
                return nil
14✔
3848
        }, func() {
14✔
3849
                isZombie = false
14✔
3850
                pubKey1 = [33]byte{}
14✔
3851
                pubKey2 = [33]byte{}
14✔
3852
        })
14✔
3853
        if err != nil {
14✔
3854
                return false, [33]byte{}, [33]byte{}, fmt.Errorf("%w: %w "+
×
3855
                        "(chanID=%d)", ErrCantCheckIfZombieEdgeStr, err, chanID)
×
3856
        }
×
3857

3858
        return isZombie, pubKey1, pubKey2, nil
14✔
3859
}
3860

3861
// isZombieEdge returns whether an entry exists for the given channel in the
3862
// zombie index. If an entry exists, then the two node public keys corresponding
3863
// to this edge are also returned.
3864
func isZombieEdge(zombieIndex kvdb.RBucket,
3865
        chanID uint64) (bool, [33]byte, [33]byte) {
190✔
3866

190✔
3867
        var k [8]byte
190✔
3868
        byteOrder.PutUint64(k[:], chanID)
190✔
3869

190✔
3870
        v := zombieIndex.Get(k[:])
190✔
3871
        if v == nil {
290✔
3872
                return false, [33]byte{}, [33]byte{}
100✔
3873
        }
100✔
3874

3875
        var pubKey1, pubKey2 [33]byte
93✔
3876
        copy(pubKey1[:], v[:33])
93✔
3877
        copy(pubKey2[:], v[33:])
93✔
3878

93✔
3879
        return true, pubKey1, pubKey2
93✔
3880
}
3881

3882
// NumZombies returns the current number of zombie channels in the graph.
3883
func (c *KVStore) NumZombies() (uint64, error) {
4✔
3884
        var numZombies uint64
4✔
3885
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3886
                edges := tx.ReadBucket(edgeBucket)
4✔
3887
                if edges == nil {
4✔
3888
                        return nil
×
3889
                }
×
3890
                zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3891
                if zombieIndex == nil {
4✔
3892
                        return nil
×
3893
                }
×
3894

3895
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3896
                        numZombies++
2✔
3897
                        return nil
2✔
3898
                })
2✔
3899
        }, func() {
4✔
3900
                numZombies = 0
4✔
3901
        })
4✔
3902
        if err != nil {
4✔
3903
                return 0, err
×
3904
        }
×
3905

3906
        return numZombies, nil
4✔
3907
}
3908

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

3919
                var k [8]byte
1✔
3920
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3921

1✔
3922
                return closedScids.Put(k[:], []byte{})
1✔
3923
        }, func() {})
1✔
3924
}
3925

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

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

5✔
3940
                if closedScids.Get(k[:]) != nil {
6✔
3941
                        isClosed = true
1✔
3942
                        return nil
1✔
3943
                }
1✔
3944

3945
                return nil
4✔
3946
        }, func() {
5✔
3947
                isClosed = false
5✔
3948
        })
5✔
3949
        if err != nil {
5✔
3950
                return false, err
×
3951
        }
×
3952

3953
        return isClosed, nil
5✔
3954
}
3955

3956
// GraphSession will provide the call-back with access to a NodeTraverser
3957
// instance which can be used to perform queries against the channel graph.
3958
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error {
54✔
3959
        return c.db.View(func(tx walletdb.ReadTx) error {
108✔
3960
                return cb(&nodeTraverserSession{
54✔
3961
                        db: c,
54✔
3962
                        tx: tx,
54✔
3963
                })
54✔
3964
        }, func() {})
108✔
3965
}
3966

3967
// nodeTraverserSession implements the NodeTraverser interface but with a
3968
// backing read only transaction for a consistent view of the graph.
3969
type nodeTraverserSession struct {
3970
        tx kvdb.RTx
3971
        db *KVStore
3972
}
3973

3974
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3975
// node.
3976
//
3977
// NOTE: Part of the NodeTraverser interface.
3978
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
3979
        cb func(channel *DirectedChannel) error) error {
239✔
3980

239✔
3981
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
239✔
3982
}
239✔
3983

3984
// FetchNodeFeatures returns the features of the given node. If the node is
3985
// unknown, assume no additional features are supported.
3986
//
3987
// NOTE: Part of the NodeTraverser interface.
3988
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
3989
        *lnwire.FeatureVector, error) {
254✔
3990

254✔
3991
        return c.db.fetchNodeFeatures(c.tx, nodePub)
254✔
3992
}
254✔
3993

3994
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3995
        node *models.LightningNode) error {
912✔
3996

912✔
3997
        var (
912✔
3998
                scratch [16]byte
912✔
3999
                b       bytes.Buffer
912✔
4000
        )
912✔
4001

912✔
4002
        pub, err := node.PubKey()
912✔
4003
        if err != nil {
912✔
4004
                return err
×
4005
        }
×
4006
        nodePub := pub.SerializeCompressed()
912✔
4007

912✔
4008
        // If the node has the update time set, write it, else write 0.
912✔
4009
        updateUnix := uint64(0)
912✔
4010
        if node.LastUpdate.Unix() > 0 {
1,687✔
4011
                updateUnix = uint64(node.LastUpdate.Unix())
775✔
4012
        }
775✔
4013

4014
        byteOrder.PutUint64(scratch[:8], updateUnix)
912✔
4015
        if _, err := b.Write(scratch[:8]); err != nil {
912✔
4016
                return err
×
4017
        }
×
4018

4019
        if _, err := b.Write(nodePub); err != nil {
912✔
4020
                return err
×
4021
        }
×
4022

4023
        // If we got a node announcement for this node, we will have the rest
4024
        // of the data available. If not we don't have more data to write.
4025
        if !node.HaveNodeAnnouncement {
999✔
4026
                // Write HaveNodeAnnouncement=0.
87✔
4027
                byteOrder.PutUint16(scratch[:2], 0)
87✔
4028
                if _, err := b.Write(scratch[:2]); err != nil {
87✔
4029
                        return err
×
4030
                }
×
4031

4032
                return nodeBucket.Put(nodePub, b.Bytes())
87✔
4033
        }
4034

4035
        // Write HaveNodeAnnouncement=1.
4036
        byteOrder.PutUint16(scratch[:2], 1)
828✔
4037
        if _, err := b.Write(scratch[:2]); err != nil {
828✔
4038
                return err
×
4039
        }
×
4040

4041
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
828✔
4042
                return err
×
4043
        }
×
4044
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
828✔
4045
                return err
×
4046
        }
×
4047
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
828✔
4048
                return err
×
4049
        }
×
4050

4051
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
828✔
4052
                return err
×
4053
        }
×
4054

4055
        if err := node.Features.Encode(&b); err != nil {
828✔
4056
                return err
×
4057
        }
×
4058

4059
        numAddresses := uint16(len(node.Addresses))
828✔
4060
        byteOrder.PutUint16(scratch[:2], numAddresses)
828✔
4061
        if _, err := b.Write(scratch[:2]); err != nil {
828✔
4062
                return err
×
4063
        }
×
4064

4065
        for _, address := range node.Addresses {
1,893✔
4066
                if err := SerializeAddr(&b, address); err != nil {
1,065✔
4067
                        return err
×
4068
                }
×
4069
        }
4070

4071
        sigLen := len(node.AuthSigBytes)
828✔
4072
        if sigLen > 80 {
828✔
4073
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4074
                        sigLen)
×
4075
        }
×
4076

4077
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
828✔
4078
        if err != nil {
828✔
4079
                return err
×
4080
        }
×
4081

4082
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
828✔
4083
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4084
        }
×
4085
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
828✔
4086
        if err != nil {
828✔
4087
                return err
×
4088
        }
×
4089

4090
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
828✔
4091
                return err
×
4092
        }
×
4093

4094
        // With the alias bucket updated, we'll now update the index that
4095
        // tracks the time series of node updates.
4096
        var indexKey [8 + 33]byte
828✔
4097
        byteOrder.PutUint64(indexKey[:8], updateUnix)
828✔
4098
        copy(indexKey[8:], nodePub)
828✔
4099

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

19✔
4107
                var oldIndexKey [8 + 33]byte
19✔
4108
                copy(oldIndexKey[:8], oldUpdateTime)
19✔
4109
                copy(oldIndexKey[8:], nodePub)
19✔
4110

19✔
4111
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
19✔
4112
                        return err
×
4113
                }
×
4114
        }
4115

4116
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
828✔
4117
                return err
×
4118
        }
×
4119

4120
        return nodeBucket.Put(nodePub, b.Bytes())
828✔
4121
}
4122

4123
func fetchLightningNode(nodeBucket kvdb.RBucket,
4124
        nodePub []byte) (models.LightningNode, error) {
3,650✔
4125

3,650✔
4126
        nodeBytes := nodeBucket.Get(nodePub)
3,650✔
4127
        if nodeBytes == nil {
3,737✔
4128
                return models.LightningNode{}, ErrGraphNodeNotFound
87✔
4129
        }
87✔
4130

4131
        nodeReader := bytes.NewReader(nodeBytes)
3,566✔
4132

3,566✔
4133
        return deserializeLightningNode(nodeReader)
3,566✔
4134
}
4135

4136
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4137
        *lnwire.FeatureVector, error) {
123✔
4138

123✔
4139
        var (
123✔
4140
                pubKey      route.Vertex
123✔
4141
                features    = lnwire.EmptyFeatureVector()
123✔
4142
                nodeScratch [8]byte
123✔
4143
        )
123✔
4144

123✔
4145
        // Skip ahead:
123✔
4146
        // - LastUpdate (8 bytes)
123✔
4147
        if _, err := r.Read(nodeScratch[:]); err != nil {
123✔
4148
                return pubKey, nil, err
×
4149
        }
×
4150

4151
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
123✔
4152
                return pubKey, nil, err
×
4153
        }
×
4154

4155
        // Read the node announcement flag.
4156
        if _, err := r.Read(nodeScratch[:2]); err != nil {
123✔
4157
                return pubKey, nil, err
×
4158
        }
×
4159
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
123✔
4160

123✔
4161
        // The rest of the data is optional, and will only be there if we got a
123✔
4162
        // node announcement for this node.
123✔
4163
        if hasNodeAnn == 0 {
126✔
4164
                return pubKey, features, nil
3✔
4165
        }
3✔
4166

4167
        // We did get a node announcement for this node, so we'll have the rest
4168
        // of the data available.
4169
        var rgb uint8
123✔
4170
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4171
                return pubKey, nil, err
×
4172
        }
×
4173
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4174
                return pubKey, nil, err
×
4175
        }
×
4176
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4177
                return pubKey, nil, err
×
4178
        }
×
4179

4180
        if _, err := wire.ReadVarString(r, 0); err != nil {
123✔
4181
                return pubKey, nil, err
×
4182
        }
×
4183

4184
        if err := features.Decode(r); err != nil {
123✔
4185
                return pubKey, nil, err
×
4186
        }
×
4187

4188
        return pubKey, features, nil
123✔
4189
}
4190

4191
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,553✔
4192
        var (
8,553✔
4193
                node    models.LightningNode
8,553✔
4194
                scratch [8]byte
8,553✔
4195
                err     error
8,553✔
4196
        )
8,553✔
4197

8,553✔
4198
        // Always populate a feature vector, even if we don't have a node
8,553✔
4199
        // announcement and short circuit below.
8,553✔
4200
        node.Features = lnwire.EmptyFeatureVector()
8,553✔
4201

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

4206
        unix := int64(byteOrder.Uint64(scratch[:]))
8,553✔
4207
        node.LastUpdate = time.Unix(unix, 0)
8,553✔
4208

8,553✔
4209
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,553✔
4210
                return models.LightningNode{}, err
×
4211
        }
×
4212

4213
        if _, err := r.Read(scratch[:2]); err != nil {
8,553✔
4214
                return models.LightningNode{}, err
×
4215
        }
×
4216

4217
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,553✔
4218
        if hasNodeAnn == 1 {
16,958✔
4219
                node.HaveNodeAnnouncement = true
8,405✔
4220
        } else {
8,556✔
4221
                node.HaveNodeAnnouncement = false
151✔
4222
        }
151✔
4223

4224
        // The rest of the data is optional, and will only be there if we got a
4225
        // node announcement for this node.
4226
        if !node.HaveNodeAnnouncement {
8,704✔
4227
                return node, nil
151✔
4228
        }
151✔
4229

4230
        // We did get a node announcement for this node, so we'll have the rest
4231
        // of the data available.
4232
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,405✔
4233
                return models.LightningNode{}, err
×
4234
        }
×
4235
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,405✔
4236
                return models.LightningNode{}, err
×
4237
        }
×
4238
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,405✔
4239
                return models.LightningNode{}, err
×
4240
        }
×
4241

4242
        node.Alias, err = wire.ReadVarString(r, 0)
8,405✔
4243
        if err != nil {
8,405✔
4244
                return models.LightningNode{}, err
×
4245
        }
×
4246

4247
        err = node.Features.Decode(r)
8,405✔
4248
        if err != nil {
8,405✔
4249
                return models.LightningNode{}, err
×
4250
        }
×
4251

4252
        if _, err := r.Read(scratch[:2]); err != nil {
8,405✔
4253
                return models.LightningNode{}, err
×
4254
        }
×
4255
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,405✔
4256

8,405✔
4257
        var addresses []net.Addr
8,405✔
4258
        for i := 0; i < numAddresses; i++ {
19,082✔
4259
                address, err := DeserializeAddr(r)
10,677✔
4260
                if err != nil {
10,677✔
4261
                        return models.LightningNode{}, err
×
4262
                }
×
4263
                addresses = append(addresses, address)
10,677✔
4264
        }
4265
        node.Addresses = addresses
8,405✔
4266

8,405✔
4267
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,405✔
4268
        if err != nil {
8,405✔
4269
                return models.LightningNode{}, err
×
4270
        }
×
4271

4272
        // We'll try and see if there are any opaque bytes left, if not, then
4273
        // we'll ignore the EOF error and return the node as is.
4274
        extraBytes, err := wire.ReadVarBytes(
8,405✔
4275
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,405✔
4276
        )
8,405✔
4277
        switch {
8,405✔
4278
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4279
        case errors.Is(err, io.EOF):
×
4280
        case err != nil:
×
4281
                return models.LightningNode{}, err
×
4282
        }
4283

4284
        if len(extraBytes) > 0 {
8,415✔
4285
                node.ExtraOpaqueData = extraBytes
10✔
4286
        }
10✔
4287

4288
        return node, nil
8,405✔
4289
}
4290

4291
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4292
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,494✔
4293

1,494✔
4294
        var b bytes.Buffer
1,494✔
4295

1,494✔
4296
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,494✔
4297
                return err
×
4298
        }
×
4299
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,494✔
4300
                return err
×
4301
        }
×
4302
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,494✔
4303
                return err
×
4304
        }
×
4305
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,494✔
4306
                return err
×
4307
        }
×
4308

4309
        var featureBuf bytes.Buffer
1,494✔
4310
        if err := edgeInfo.Features.Encode(&featureBuf); err != nil {
1,494✔
4311
                return fmt.Errorf("unable to encode features: %w", err)
×
4312
        }
×
4313

4314
        if err := wire.WriteVarBytes(&b, 0, featureBuf.Bytes()); err != nil {
1,494✔
4315
                return err
×
4316
        }
×
4317

4318
        authProof := edgeInfo.AuthProof
1,494✔
4319
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,494✔
4320
        if authProof != nil {
2,904✔
4321
                nodeSig1 = authProof.NodeSig1Bytes
1,410✔
4322
                nodeSig2 = authProof.NodeSig2Bytes
1,410✔
4323
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,410✔
4324
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,410✔
4325
        }
1,410✔
4326

4327
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,494✔
4328
                return err
×
4329
        }
×
4330
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,494✔
4331
                return err
×
4332
        }
×
4333
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,494✔
4334
                return err
×
4335
        }
×
4336
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,494✔
4337
                return err
×
4338
        }
×
4339

4340
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,494✔
4341
                return err
×
4342
        }
×
4343
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
1,494✔
4344
        if err != nil {
1,494✔
4345
                return err
×
4346
        }
×
4347
        if _, err := b.Write(chanID[:]); err != nil {
1,494✔
4348
                return err
×
4349
        }
×
4350
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,494✔
4351
                return err
×
4352
        }
×
4353

4354
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,494✔
4355
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4356
        }
×
4357
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,494✔
4358
        if err != nil {
1,494✔
4359
                return err
×
4360
        }
×
4361

4362
        return edgeIndex.Put(chanID[:], b.Bytes())
1,494✔
4363
}
4364

4365
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4366
        chanID []byte) (models.ChannelEdgeInfo, error) {
6,808✔
4367

6,808✔
4368
        edgeInfoBytes := edgeIndex.Get(chanID)
6,808✔
4369
        if edgeInfoBytes == nil {
6,876✔
4370
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
68✔
4371
        }
68✔
4372

4373
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
6,743✔
4374

6,743✔
4375
        return deserializeChanEdgeInfo(edgeInfoReader)
6,743✔
4376
}
4377

4378
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
7,285✔
4379
        var (
7,285✔
4380
                err      error
7,285✔
4381
                edgeInfo models.ChannelEdgeInfo
7,285✔
4382
        )
7,285✔
4383

7,285✔
4384
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
7,285✔
4385
                return models.ChannelEdgeInfo{}, err
×
4386
        }
×
4387
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
7,285✔
4388
                return models.ChannelEdgeInfo{}, err
×
4389
        }
×
4390
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
7,285✔
4391
                return models.ChannelEdgeInfo{}, err
×
4392
        }
×
4393
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
7,285✔
4394
                return models.ChannelEdgeInfo{}, err
×
4395
        }
×
4396

4397
        featureBytes, err := wire.ReadVarBytes(r, 0, 900, "features")
7,285✔
4398
        if err != nil {
7,285✔
4399
                return models.ChannelEdgeInfo{}, err
×
4400
        }
×
4401

4402
        features := lnwire.NewRawFeatureVector()
7,285✔
4403
        err = features.Decode(bytes.NewReader(featureBytes))
7,285✔
4404
        if err != nil {
7,285✔
4405
                return models.ChannelEdgeInfo{}, fmt.Errorf("unable to decode "+
×
4406
                        "features: %w", err)
×
4407
        }
×
4408
        edgeInfo.Features = lnwire.NewFeatureVector(features, lnwire.Features)
7,285✔
4409

7,285✔
4410
        proof := &models.ChannelAuthProof{}
7,285✔
4411

7,285✔
4412
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
7,285✔
4413
        if err != nil {
7,285✔
4414
                return models.ChannelEdgeInfo{}, err
×
4415
        }
×
4416
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
7,285✔
4417
        if err != nil {
7,285✔
4418
                return models.ChannelEdgeInfo{}, err
×
4419
        }
×
4420
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
7,285✔
4421
        if err != nil {
7,285✔
4422
                return models.ChannelEdgeInfo{}, err
×
4423
        }
×
4424
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
7,285✔
4425
        if err != nil {
7,285✔
4426
                return models.ChannelEdgeInfo{}, err
×
4427
        }
×
4428

4429
        if !proof.IsEmpty() {
11,467✔
4430
                edgeInfo.AuthProof = proof
4,182✔
4431
        }
4,182✔
4432

4433
        edgeInfo.ChannelPoint = wire.OutPoint{}
7,285✔
4434
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
7,285✔
4435
                return models.ChannelEdgeInfo{}, err
×
4436
        }
×
4437
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
7,285✔
4438
                return models.ChannelEdgeInfo{}, err
×
4439
        }
×
4440
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
7,285✔
4441
                return models.ChannelEdgeInfo{}, err
×
4442
        }
×
4443

4444
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
7,285✔
4445
                return models.ChannelEdgeInfo{}, err
×
4446
        }
×
4447

4448
        // We'll try and see if there are any opaque bytes left, if not, then
4449
        // we'll ignore the EOF error and return the edge as is.
4450
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
7,285✔
4451
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
7,285✔
4452
        )
7,285✔
4453
        switch {
7,285✔
4454
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4455
        case errors.Is(err, io.EOF):
×
4456
        case err != nil:
×
4457
                return models.ChannelEdgeInfo{}, err
×
4458
        }
4459

4460
        return edgeInfo, nil
7,285✔
4461
}
4462

4463
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4464
        from, to []byte) error {
2,670✔
4465

2,670✔
4466
        var edgeKey [33 + 8]byte
2,670✔
4467
        copy(edgeKey[:], from)
2,670✔
4468
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,670✔
4469

2,670✔
4470
        var b bytes.Buffer
2,670✔
4471
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,670✔
4472
                return err
×
4473
        }
×
4474

4475
        // Before we write out the new edge, we'll create a new entry in the
4476
        // update index in order to keep it fresh.
4477
        updateUnix := uint64(edge.LastUpdate.Unix())
2,670✔
4478
        var indexKey [8 + 8]byte
2,670✔
4479
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,670✔
4480
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,670✔
4481

2,670✔
4482
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,670✔
4483
        if err != nil {
2,670✔
4484
                return err
×
4485
        }
×
4486

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

30✔
4494
                // In order to delete the old entry, we'll need to obtain the
30✔
4495
                // *prior* update time in order to delete it. To do this, we'll
30✔
4496
                // need to deserialize the existing policy within the database
30✔
4497
                // (now outdated by the new one), and delete its corresponding
30✔
4498
                // entry within the update index. We'll ignore any
30✔
4499
                // ErrEdgePolicyOptionalFieldNotFound or ErrParsingExtraTLVBytes
30✔
4500
                // errors, as we only need the channel ID and update time to
30✔
4501
                // delete the entry.
30✔
4502
                //
30✔
4503
                // TODO(halseth): get rid of these invalid policies in a
30✔
4504
                // migration.
30✔
4505
                //
30✔
4506
                // NOTE: the above TODO was completed in the SQL migration and
30✔
4507
                // so such edge cases no longer need to be handled there.
30✔
4508
                oldEdgePolicy, err := deserializeChanEdgePolicy(
30✔
4509
                        bytes.NewReader(edgeBytes),
30✔
4510
                )
30✔
4511
                if err != nil &&
30✔
4512
                        !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
30✔
4513
                        !errors.Is(err, ErrParsingExtraTLVBytes) {
30✔
4514

×
4515
                        return err
×
4516
                }
×
4517

4518
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
30✔
4519

30✔
4520
                var oldIndexKey [8 + 8]byte
30✔
4521
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
30✔
4522
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
30✔
4523

30✔
4524
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
30✔
4525
                        return err
×
4526
                }
×
4527
        }
4528

4529
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,670✔
4530
                return err
×
4531
        }
×
4532

4533
        err = updateEdgePolicyDisabledIndex(
2,670✔
4534
                edges, edge.ChannelID,
2,670✔
4535
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,670✔
4536
                edge.IsDisabled(),
2,670✔
4537
        )
2,670✔
4538
        if err != nil {
2,670✔
4539
                return err
×
4540
        }
×
4541

4542
        return edges.Put(edgeKey[:], b.Bytes())
2,670✔
4543
}
4544

4545
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4546
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4547
// one.
4548
// The direction represents the direction of the edge and disabled is used for
4549
// deciding whether to remove or add an entry to the bucket.
4550
// In general a channel is disabled if two entries for the same chanID exist
4551
// in this bucket.
4552
// Maintaining the bucket this way allows a fast retrieval of disabled
4553
// channels, for example when prune is needed.
4554
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4555
        direction bool, disabled bool) error {
2,948✔
4556

2,948✔
4557
        var disabledEdgeKey [8 + 1]byte
2,948✔
4558
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,948✔
4559
        if direction {
4,421✔
4560
                disabledEdgeKey[8] = 1
1,473✔
4561
        }
1,473✔
4562

4563
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,948✔
4564
                disabledEdgePolicyBucket,
2,948✔
4565
        )
2,948✔
4566
        if err != nil {
2,948✔
4567
                return err
×
4568
        }
×
4569

4570
        if disabled {
2,977✔
4571
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4572
        }
29✔
4573

4574
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,922✔
4575
}
4576

4577
// putChanEdgePolicyUnknown marks the edge policy as unknown
4578
// in the edges bucket.
4579
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4580
        from []byte) error {
2,981✔
4581

2,981✔
4582
        var edgeKey [33 + 8]byte
2,981✔
4583
        copy(edgeKey[:], from)
2,981✔
4584
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,981✔
4585

2,981✔
4586
        if edges.Get(edgeKey[:]) != nil {
2,981✔
4587
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4588
                        " when there is already a policy present", channelID)
×
4589
        }
×
4590

4591
        return edges.Put(edgeKey[:], unknownPolicy)
2,981✔
4592
}
4593

4594
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4595
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
13,501✔
4596

13,501✔
4597
        var edgeKey [33 + 8]byte
13,501✔
4598
        copy(edgeKey[:], nodePub)
13,501✔
4599
        copy(edgeKey[33:], chanID)
13,501✔
4600

13,501✔
4601
        edgeBytes := edges.Get(edgeKey[:])
13,501✔
4602
        if edgeBytes == nil {
13,501✔
4603
                return nil, ErrEdgeNotFound
×
4604
        }
×
4605

4606
        // No need to deserialize unknown policy.
4607
        if bytes.Equal(edgeBytes, unknownPolicy) {
14,887✔
4608
                return nil, nil
1,386✔
4609
        }
1,386✔
4610

4611
        edgeReader := bytes.NewReader(edgeBytes)
12,118✔
4612

12,118✔
4613
        ep, err := deserializeChanEdgePolicy(edgeReader)
12,118✔
4614
        switch {
12,118✔
4615
        // If the db policy was missing an expected optional field, we return
4616
        // nil as if the policy was unknown.
4617
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
2✔
4618
                return nil, nil
2✔
4619

4620
        // If the policy contains invalid TLV bytes, we return nil as if
4621
        // the policy was unknown.
4622
        case errors.Is(err, ErrParsingExtraTLVBytes):
×
4623
                return nil, nil
×
4624

4625
        case err != nil:
×
4626
                return nil, err
×
4627
        }
4628

4629
        return ep, nil
12,116✔
4630
}
4631

4632
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4633
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4634
        error) {
2,910✔
4635

2,910✔
4636
        edgeInfo := edgeIndex.Get(chanID)
2,910✔
4637
        if edgeInfo == nil {
2,910✔
4638
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4639
                        chanID)
×
4640
        }
×
4641

4642
        // The first node is contained within the first half of the edge
4643
        // information. We only propagate the error here and below if it's
4644
        // something other than edge non-existence.
4645
        node1Pub := edgeInfo[:33]
2,910✔
4646
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
2,910✔
4647
        if err != nil {
2,910✔
4648
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4649
                        node1Pub)
×
4650
        }
×
4651

4652
        // Similarly, the second node is contained within the latter
4653
        // half of the edge information.
4654
        node2Pub := edgeInfo[33:66]
2,910✔
4655
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
2,910✔
4656
        if err != nil {
2,910✔
4657
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4658
                        node2Pub)
×
4659
        }
×
4660

4661
        return edge1, edge2, nil
2,910✔
4662
}
4663

4664
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4665
        to []byte) error {
2,672✔
4666

2,672✔
4667
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,672✔
4668
        if err != nil {
2,672✔
4669
                return err
×
4670
        }
×
4671

4672
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,672✔
4673
                return err
×
4674
        }
×
4675

4676
        var scratch [8]byte
2,672✔
4677
        updateUnix := uint64(edge.LastUpdate.Unix())
2,672✔
4678
        byteOrder.PutUint64(scratch[:], updateUnix)
2,672✔
4679
        if _, err := w.Write(scratch[:]); err != nil {
2,672✔
4680
                return err
×
4681
        }
×
4682

4683
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,672✔
4684
                return err
×
4685
        }
×
4686
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,672✔
4687
                return err
×
4688
        }
×
4689
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,672✔
4690
                return err
×
4691
        }
×
4692
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,672✔
4693
                return err
×
4694
        }
×
4695
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
2,672✔
4696
        if err != nil {
2,672✔
4697
                return err
×
4698
        }
×
4699
        err = binary.Write(
2,672✔
4700
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
2,672✔
4701
        )
2,672✔
4702
        if err != nil {
2,672✔
4703
                return err
×
4704
        }
×
4705

4706
        if _, err := w.Write(to); err != nil {
2,672✔
4707
                return err
×
4708
        }
×
4709

4710
        // If the max_htlc field is present, we write it. To be compatible with
4711
        // older versions that wasn't aware of this field, we write it as part
4712
        // of the opaque data.
4713
        // TODO(halseth): clean up when moving to TLV.
4714
        var opaqueBuf bytes.Buffer
2,672✔
4715
        if edge.MessageFlags.HasMaxHtlc() {
4,960✔
4716
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,288✔
4717
                if err != nil {
2,288✔
4718
                        return err
×
4719
                }
×
4720
        }
4721

4722
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,672✔
4723
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4724
        }
×
4725
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,672✔
4726
                return err
×
4727
        }
×
4728

4729
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,672✔
4730
                return err
×
4731
        }
×
4732

4733
        return nil
2,672✔
4734
}
4735

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

×
4746
                return nil, err
×
4747
        }
×
4748

4749
        return edge, err
12,146✔
4750
}
4751

4752
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4753
        error) {
13,159✔
4754

13,159✔
4755
        edge := &models.ChannelEdgePolicy{}
13,159✔
4756

13,159✔
4757
        var err error
13,159✔
4758
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
13,159✔
4759
        if err != nil {
13,159✔
4760
                return nil, err
×
4761
        }
×
4762

4763
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
13,159✔
4764
                return nil, err
×
4765
        }
×
4766

4767
        var scratch [8]byte
13,159✔
4768
        if _, err := r.Read(scratch[:]); err != nil {
13,159✔
4769
                return nil, err
×
4770
        }
×
4771
        unix := int64(byteOrder.Uint64(scratch[:]))
13,159✔
4772
        edge.LastUpdate = time.Unix(unix, 0)
13,159✔
4773

13,159✔
4774
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
13,159✔
4775
                return nil, err
×
4776
        }
×
4777
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
13,159✔
4778
                return nil, err
×
4779
        }
×
4780
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
13,159✔
4781
                return nil, err
×
4782
        }
×
4783

4784
        var n uint64
13,159✔
4785
        if err := binary.Read(r, byteOrder, &n); err != nil {
13,159✔
4786
                return nil, err
×
4787
        }
×
4788
        edge.MinHTLC = lnwire.MilliSatoshi(n)
13,159✔
4789

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

13,159✔
4795
        if err := binary.Read(r, byteOrder, &n); err != nil {
13,159✔
4796
                return nil, err
×
4797
        }
×
4798
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
13,159✔
4799

13,159✔
4800
        if _, err := r.Read(edge.ToNode[:]); err != nil {
13,159✔
4801
                return nil, err
×
4802
        }
×
4803

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

4816
        // See if optional fields are present.
4817
        if edge.MessageFlags.HasMaxHtlc() {
25,350✔
4818
                // The max_htlc field should be at the beginning of the opaque
12,191✔
4819
                // bytes.
12,191✔
4820
                opq := edge.ExtraOpaqueData
12,191✔
4821

12,191✔
4822
                // If the max_htlc field is not present, it might be old data
12,191✔
4823
                // stored before this field was validated. We'll return the
12,191✔
4824
                // edge along with an error.
12,191✔
4825
                if len(opq) < 8 {
12,195✔
4826
                        return edge, ErrEdgePolicyOptionalFieldNotFound
4✔
4827
                }
4✔
4828

4829
                maxHtlc := byteOrder.Uint64(opq[:8])
12,187✔
4830
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
12,187✔
4831

12,187✔
4832
                // Exclude the parsed field from the rest of the opaque data.
12,187✔
4833
                edge.ExtraOpaqueData = opq[8:]
12,187✔
4834
        }
4835

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

4847
        val, ok := typeMap[lnwire.FeeRecordType]
13,155✔
4848
        if ok && val == nil {
14,882✔
4849
                edge.InboundFee = fn.Some(inboundFee)
1,727✔
4850
        }
1,727✔
4851

4852
        return edge, nil
13,155✔
4853
}
4854

4855
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4856
// KVStore and a kvdb.RTx.
4857
type chanGraphNodeTx struct {
4858
        tx   kvdb.RTx
4859
        db   *KVStore
4860
        node *models.LightningNode
4861
}
4862

4863
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4864
// interface.
4865
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4866

4867
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
4868
        node *models.LightningNode) *chanGraphNodeTx {
4,105✔
4869

4,105✔
4870
        return &chanGraphNodeTx{
4,105✔
4871
                tx:   tx,
4,105✔
4872
                db:   db,
4,105✔
4873
                node: node,
4,105✔
4874
        }
4,105✔
4875
}
4,105✔
4876

4877
// Node returns the raw information of the node.
4878
//
4879
// NOTE: This is a part of the NodeRTx interface.
4880
func (c *chanGraphNodeTx) Node() *models.LightningNode {
5,022✔
4881
        return c.node
5,022✔
4882
}
5,022✔
4883

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

4895
        return newChanGraphNodeTx(c.tx, c.db, node), nil
2,944✔
4896
}
4897

4898
// ForEachChannel can be used to iterate over the node's channels under
4899
// the same transaction used to fetch the node.
4900
//
4901
// NOTE: This is a part of the NodeRTx interface.
4902
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4903
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
965✔
4904

965✔
4905
        return c.db.forEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
965✔
4906
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
965✔
4907
                        policy2 *models.ChannelEdgePolicy) error {
3,909✔
4908

2,944✔
4909
                        return f(info, policy1, policy2)
2,944✔
4910
                },
2,944✔
4911
        )
4912
}
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