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

lightningnetwork / lnd / 15569071323

10 Jun 2025 08:00PM UTC coverage: 58.363% (+0.03%) from 58.331%
15569071323

Pull #9752

github

web-flow
Merge 3e7a64ce6 into 32592dbd2
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

990 existing lines in 11 files now uncovered.

97788 of 167550 relevant lines covered (58.36%)

1.81 hits per line

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
260
                        return nil
3✔
261
                }
3✔
262

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

268
                var key channelMapKey
3✔
269
                copy(key.nodeKey[:], k[:33])
3✔
270
                copy(key.chanID[:], k[33:])
3✔
271

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

277
                edgeReader := bytes.NewReader(edgeBytes)
3✔
278
                edge, err := deserializeChanEdgePolicyRaw(
3✔
279
                        edgeReader,
3✔
280
                )
3✔
281

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

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

295
                case err != nil:
×
296
                        return err
×
297
                }
298

299
                channelMap[key] = edge
3✔
300

3✔
301
                return nil
3✔
302
        })
303
        if err != nil {
3✔
304
                return nil, err
×
305
        }
×
306

307
        return channelMap, nil
3✔
308
}
309

310
var graphTopLevelBuckets = [][]byte{
311
        nodeBucket,
312
        edgeBucket,
313
        graphMetaBucket,
314
        closedScidBucket,
315
}
316

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

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

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

357
                graphMeta := tx.ReadWriteBucket(graphMetaBucket)
3✔
358
                _, err = graphMeta.CreateBucketIfNotExists(pruneLogBucket)
3✔
359

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

366
        return nil
3✔
367
}
368

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

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

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

388
        case errors.Is(err, ErrGraphNodeNotFound):
3✔
389
                return false, nil, nil
3✔
390
        }
391

392
        return true, node.Addresses, nil
3✔
393
}
394

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

3✔
407
        return c.db.View(func(tx kvdb.RTx) error {
6✔
408
                edges := tx.ReadBucket(edgeBucket)
3✔
409
                if edges == nil {
3✔
410
                        return ErrGraphNoEdgesFound
×
411
                }
×
412

413
                // First, load all edges in memory indexed by node and channel
414
                // id.
415
                channelMap, err := c.getChannelMap(edges)
3✔
416
                if err != nil {
3✔
417
                        return err
×
418
                }
×
419

420
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
421
                if edgeIndex == nil {
3✔
422
                        return ErrGraphNoEdgesFound
×
423
                }
×
424

425
                // Load edge index, recombine each channel with the policies
426
                // loaded above and invoke the callback.
427
                return kvdb.ForAll(
3✔
428
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
6✔
429
                                var chanID [8]byte
3✔
430
                                copy(chanID[:], k)
3✔
431

3✔
432
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
433
                                info, err := deserializeChanEdgeInfo(
3✔
434
                                        edgeInfoReader,
3✔
435
                                )
3✔
436
                                if err != nil {
3✔
437
                                        return err
×
438
                                }
×
439

440
                                policy1 := channelMap[channelMapKey{
3✔
441
                                        nodeKey: info.NodeKey1Bytes,
3✔
442
                                        chanID:  chanID,
3✔
443
                                }]
3✔
444

3✔
445
                                policy2 := channelMap[channelMapKey{
3✔
446
                                        nodeKey: info.NodeKey2Bytes,
3✔
447
                                        chanID:  chanID,
3✔
448
                                }]
3✔
449

3✔
450
                                return cb(&info, policy1, policy2)
3✔
451
                        },
452
                )
453
        }, func() {})
3✔
454
}
455

456
// forEachNodeDirectedChannel iterates through all channels of a given node,
457
// executing the passed callback on the directed edge representing the channel
458
// and its incoming policy. If the callback returns an error, then the iteration
459
// is halted with the error propagated back up to the caller. An optional read
460
// transaction may be provided. If none is provided, a new one will be created.
461
//
462
// Unknown policies are passed into the callback as nil values.
463
func (c *KVStore) forEachNodeDirectedChannel(tx kvdb.RTx,
464
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
465

466
        // Fallback that uses the database.
467
        toNodeCallback := func() route.Vertex {
468
                return node
469
        }
3✔
470
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
3✔
471
        if err != nil {
6✔
472
                return err
3✔
473
        }
3✔
UNCOV
474

×
UNCOV
475
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
×
476
                p2 *models.ChannelEdgePolicy) error {
477

478
                var cachedInPolicy *models.CachedEdgePolicy
479
                if p2 != nil {
3✔
480
                        cachedInPolicy = models.NewCachedPolicy(p2)
3✔
UNCOV
481
                        cachedInPolicy.ToNodePubKey = toNodeCallback
×
UNCOV
482
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
×
483
                }
484

3✔
485
                directedChannel := &DirectedChannel{
3✔
UNCOV
486
                        ChannelID:    e.ChannelID,
×
UNCOV
487
                        IsNode1:      node == e.NodeKey1Bytes,
×
488
                        OtherNode:    e.NodeKey2Bytes,
489
                        Capacity:     e.Capacity,
490
                        OutPolicySet: p1 != nil,
491
                        InPolicy:     cachedInPolicy,
3✔
492
                }
6✔
493

3✔
494
                if p1 != nil {
3✔
495
                        p1.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
496
                                directedChannel.InboundFee = fee
3✔
497
                        })
3✔
498
                }
3✔
499

3✔
500
                if node == e.NodeKey2Bytes {
3✔
UNCOV
501
                        directedChannel.OtherNode = e.NodeKey1Bytes
×
UNCOV
502
                }
×
503

504
                return cb(directedChannel)
3✔
505
        }
3✔
506

3✔
507
        return nodeTraversal(tx, node[:], c.db, dbCallback)
3✔
508
}
3✔
509

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

3✔
516
        // Fallback that uses the database.
3✔
517
        targetNode, err := c.FetchLightningNodeTx(tx, node)
3✔
518
        switch {
3✔
519
        // If the node exists and has features, return them directly.
520
        case err == nil:
521
                return targetNode.Features, nil
3✔
522

523
        // If we couldn't find a node announcement, populate a blank feature
524
        // vector.
525
        case errors.Is(err, ErrGraphNodeNotFound):
526
                return lnwire.EmptyFeatureVector(), nil
527

528
        // Otherwise, bubble the error up.
529
        default:
530
                return nil, err
531
        }
532
}
3✔
533

3✔
534
// ForEachNodeDirectedChannel iterates through all channels of a given node,
3✔
535
// executing the passed callback on the directed edge representing the channel
6✔
536
// and its incoming policy. If the callback returns an error, then the iteration
3✔
537
// is halted with the error propagated back up to the caller.
3✔
538
//
3✔
539
// Unknown policies are passed into the callback as nil values.
3✔
UNCOV
540
//
×
UNCOV
541
// NOTE: this is part of the graphdb.NodeTraverser interface.
×
542
func (c *KVStore) ForEachNodeDirectedChannel(nodePub route.Vertex,
543
        cb func(channel *DirectedChannel) error) error {
3✔
544

6✔
545
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
3✔
546
}
3✔
547

6✔
548
// FetchNodeFeatures returns the features of the given node. If no features are
3✔
549
// known for the node, an empty feature vector is returned.
3✔
550
//
3✔
551
// NOTE: this is part of the graphdb.NodeTraverser interface.
3✔
552
func (c *KVStore) FetchNodeFeatures(nodePub route.Vertex) (
553
        *lnwire.FeatureVector, error) {
3✔
554

3✔
555
        return c.fetchNodeFeatures(nil, nodePub)
3✔
556
}
3✔
557

3✔
558
// ForEachNodeCached is similar to forEachNode, but it returns DirectedChannel
3✔
559
// data to the call-back.
3✔
560
//
3✔
561
// NOTE: The callback contents MUST not be modified.
3✔
562
func (c *KVStore) ForEachNodeCached(cb func(node route.Vertex,
6✔
563
        chans map[uint64]*DirectedChannel) error) error {
3✔
564

×
565
        // Otherwise call back to a version that uses the database directly.
×
566
        // We'll iterate over each node, then the set of channels for each
567
        // node, and construct a similar callback functiopn signature as the
568
        // main funcotin expects.
6✔
569
        return c.forEachNode(func(tx kvdb.RTx,
3✔
570
                node *models.LightningNode) error {
3✔
571

572
                channels := make(map[uint64]*DirectedChannel)
3✔
573

574
                err := c.forEachNodeChannelTx(tx, node.PubKeyBytes,
575
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
3✔
576
                                p1 *models.ChannelEdgePolicy,
577
                                p2 *models.ChannelEdgePolicy) error {
578

579
                                toNodeCallback := func() route.Vertex {
580
                                        return node.PubKeyBytes
581
                                }
582
                                toNodeFeatures, err := c.fetchNodeFeatures(
3✔
583
                                        tx, node.PubKeyBytes,
3✔
584
                                )
3✔
585
                                if err != nil {
3✔
586
                                        return err
3✔
587
                                }
588

3✔
589
                                var cachedInPolicy *models.CachedEdgePolicy
3✔
590
                                if p2 != nil {
591
                                        cachedInPolicy =
592
                                                models.NewCachedPolicy(p2)
593
                                        cachedInPolicy.ToNodePubKey =
×
594
                                                toNodeCallback
×
595
                                        cachedInPolicy.ToNodeFeatures =
596
                                                toNodeFeatures
597
                                }
×
UNCOV
598

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

609
                                if node.PubKeyBytes == e.NodeKey2Bytes {
610
                                        directedChannel.OtherNode =
611
                                                e.NodeKey1Bytes
3✔
612
                                }
3✔
613

3✔
614
                                channels[e.ChannelID] = directedChannel
3✔
615

616
                                return nil
617
                        })
618
                if err != nil {
619
                        return err
620
                }
621

3✔
622
                return cb(node.PubKeyBytes, channels)
3✔
623
        })
3✔
624
}
3✔
625

626
// DisabledChannelIDs returns the channel ids of disabled channels.
627
// A channel is disabled when two of the associated ChanelEdgePolicies
628
// have their disabled bit on.
629
func (c *KVStore) DisabledChannelIDs() ([]uint64, error) {
630
        var disabledChanIDs []uint64
631
        var chanEdgeFound map[uint64]struct{}
×
632

×
633
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
634
                edges := tx.ReadBucket(edgeBucket)
×
635
                if edges == nil {
×
636
                        return ErrGraphNoEdgesFound
×
637
                }
×
UNCOV
638

×
639
                disabledEdgePolicyIndex := edges.NestedReadBucket(
×
640
                        disabledEdgePolicyBucket,
×
641
                )
×
642
                if disabledEdgePolicyIndex == nil {
×
643
                        return nil
×
644
                }
×
UNCOV
645

×
UNCOV
646
                // We iterate over all disabled policies and we add each channel
×
UNCOV
647
                // that has more than one disabled policy to disabledChanIDs
×
UNCOV
648
                // array.
×
649
                return disabledEdgePolicyIndex.ForEach(
×
650
                        func(k, v []byte) error {
×
651
                                chanID := byteOrder.Uint64(k[:8])
×
652
                                _, edgeFound := chanEdgeFound[chanID]
×
653
                                if edgeFound {
×
654
                                        delete(chanEdgeFound, chanID)
×
655
                                        disabledChanIDs = append(
×
656
                                                disabledChanIDs, chanID,
657
                                        )
×
658

×
659
                                        return nil
×
660
                                }
×
UNCOV
661

×
662
                                chanEdgeFound[chanID] = struct{}{}
×
663

×
664
                                return nil
×
UNCOV
665
                        },
×
666
                )
667
        }, func() {
×
668
                disabledChanIDs = nil
×
669
                chanEdgeFound = make(map[uint64]struct{})
×
670
        })
×
671
        if err != nil {
×
672
                return nil, err
×
673
        }
×
UNCOV
674

×
675
        return disabledChanIDs, nil
×
UNCOV
676
}
×
UNCOV
677

×
UNCOV
678
// ForEachNode iterates through all the stored vertices/nodes in the graph,
×
UNCOV
679
// executing the passed callback with each node encountered. If the callback
×
UNCOV
680
// returns an error, then the transaction is aborted and the iteration stops
×
681
// early. Any operations performed on the NodeTx passed to the call-back are
UNCOV
682
// executed under the same read transaction and so, methods on the NodeTx object
×
UNCOV
683
// _MUST_ only be called from within the call-back.
×
UNCOV
684
func (c *KVStore) ForEachNode(cb func(tx NodeRTx) error) error {
×
685
        return c.forEachNode(func(tx kvdb.RTx,
UNCOV
686
                node *models.LightningNode) error {
×
UNCOV
687

×
UNCOV
688
                return cb(newChanGraphNodeTx(tx, c, node))
×
689
        })
UNCOV
690
}
×
691

692
// forEachNode iterates through all the stored vertices/nodes in the graph,
693
// executing the passed callback with each node encountered. If the callback
694
// returns an error, then the transaction is aborted and the iteration stops
695
// early.
696
//
UNCOV
697
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
×
UNCOV
698
// traversal when graph gets mega.
×
UNCOV
699
func (c *KVStore) forEachNode(
×
UNCOV
700
        cb func(kvdb.RTx, *models.LightningNode) error) error {
×
UNCOV
701

×
UNCOV
702
        traversal := func(tx kvdb.RTx) error {
×
UNCOV
703
                // First grab the nodes bucket which stores the mapping from
×
UNCOV
704
                // pubKey to node information.
×
UNCOV
705
                nodes := tx.ReadBucket(nodeBucket)
×
706
                if nodes == nil {
707
                        return ErrGraphNotFound
×
708
                }
×
UNCOV
709

×
UNCOV
710
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
×
UNCOV
711
                        // If this is the source key, then we skip this
×
UNCOV
712
                        // iteration as the value for this key is a pubKey
×
713
                        // rather than raw node information.
714
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
715
                                return nil
716
                        }
UNCOV
717

×
UNCOV
718
                        nodeReader := bytes.NewReader(nodeBytes)
×
UNCOV
719
                        node, err := deserializeLightningNode(nodeReader)
×
UNCOV
720
                        if err != nil {
×
721
                                return err
×
722
                        }
×
UNCOV
723

×
UNCOV
724
                        // Execute the callback, the transaction will abort if
×
UNCOV
725
                        // this returns an error.
×
UNCOV
726
                        return cb(tx, &node)
×
UNCOV
727
                })
×
UNCOV
728
        }
×
729

UNCOV
730
        return kvdb.View(c.db, traversal, func() {})
×
UNCOV
731
}
×
UNCOV
732

×
733
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
734
// graph, executing the passed callback with each node encountered. If the
UNCOV
735
// callback returns an error, then the transaction is aborted and the iteration
×
UNCOV
736
// stops early.
×
UNCOV
737
func (c *KVStore) ForEachNodeCacheable(cb func(route.Vertex,
×
UNCOV
738
        *lnwire.FeatureVector) error) error {
×
UNCOV
739

×
UNCOV
740
        traversal := func(tx kvdb.RTx) error {
×
UNCOV
741
                // First grab the nodes bucket which stores the mapping from
×
742
                // pubKey to node information.
UNCOV
743
                nodes := tx.ReadBucket(nodeBucket)
×
744
                if nodes == nil {
745
                        return ErrGraphNotFound
746
                }
747

748
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
749
                        // If this is the source key, then we skip this
750
                        // iteration as the value for this key is a pubKey
751
                        // rather than raw node information.
752
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
3✔
753
                                return nil
3✔
754
                        }
6✔
755

3✔
756
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
757
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
3✔
758
                                nodeReader,
759
                        )
760
                        if err != nil {
761
                                return err
762
                        }
763

764
                        // Execute the callback, the transaction will abort if
765
                        // this returns an error.
766
                        return cb(node, features)
767
                })
768
        }
3✔
769

3✔
770
        return kvdb.View(c.db, traversal, func() {})
6✔
771
}
3✔
772

3✔
773
// SourceNode returns the source node of the graph. The source node is treated
3✔
774
// as the center node within a star-graph. This method may be used to kick off
3✔
UNCOV
775
// a path finding algorithm in order to explore the reachability of another
×
UNCOV
776
// node based off the source node.
×
777
func (c *KVStore) SourceNode() (*models.LightningNode, error) {
778
        var source *models.LightningNode
6✔
779
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
3✔
780
                // First grab the nodes bucket which stores the mapping from
3✔
781
                // pubKey to node information.
3✔
782
                nodes := tx.ReadBucket(nodeBucket)
6✔
783
                if nodes == nil {
3✔
784
                        return ErrGraphNotFound
3✔
785
                }
786

3✔
787
                node, err := c.sourceNode(nodes)
3✔
788
                if err != nil {
3✔
789
                        return err
×
790
                }
×
791
                source = node
792

793
                return nil
794
        }, func() {
3✔
795
                source = nil
796
        })
797
        if err != nil {
798
                return nil, err
6✔
799
        }
800

801
        return source, nil
802
}
803

804
// sourceNode uses an existing database transaction and returns the source node
805
// of the graph. The source node is treated as the center node within a
806
// star-graph. This method may be used to kick off a path finding algorithm in
3✔
807
// order to explore the reachability of another node based off the source node.
3✔
808
func (c *KVStore) sourceNode(nodes kvdb.RBucket) (*models.LightningNode,
6✔
809
        error) {
3✔
810

3✔
811
        selfPub := nodes.Get(sourceKey)
3✔
812
        if selfPub == nil {
3✔
813
                return nil, ErrSourceNodeNotSet
×
814
        }
×
815

816
        // With the pubKey of the source node retrieved, we're able to
6✔
817
        // fetch the full node information.
3✔
818
        node, err := fetchLightningNode(nodes, selfPub)
3✔
819
        if err != nil {
3✔
820
                return nil, err
6✔
821
        }
3✔
822

3✔
823
        return &node, nil
824
}
3✔
825

3✔
826
// SetSourceNode sets the source node within the graph database. The source
3✔
827
// node is to be used as the center of a star-graph within path finding
3✔
828
// algorithms.
3✔
UNCOV
829
func (c *KVStore) SetSourceNode(node *models.LightningNode) error {
×
UNCOV
830
        nodePubBytes := node.PubKeyBytes[:]
×
831

832
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
833
                // First grab the nodes bucket which stores the mapping from
834
                // pubKey to node information.
3✔
835
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
836
                if err != nil {
837
                        return err
838
                }
6✔
839

840
                // Next we create the mapping from source to the targeted
841
                // public key.
842
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
843
                        return err
844
                }
845

3✔
846
                // Finally, we commit the information of the lightning node
3✔
847
                // itself.
6✔
848
                return addLightningNode(tx, node)
3✔
849
        }, func() {})
3✔
850
}
3✔
851

3✔
UNCOV
852
// AddLightningNode adds a vertex/node to the graph database. If the node is not
×
UNCOV
853
// in the database from before, this will add a new, unconnected one to the
×
854
// graph. If it is present from before, this will update that node's
855
// information. Note that this method is expected to only be called to update an
3✔
856
// already present node from a node announcement, or to insert a node found in a
3✔
UNCOV
857
// channel update.
×
UNCOV
858
//
×
859
// TODO(roasbeef): also need sig of announcement.
3✔
860
func (c *KVStore) AddLightningNode(node *models.LightningNode,
3✔
861
        opts ...batch.SchedulerOption) error {
3✔
862

3✔
863
        ctx := context.TODO()
3✔
864

3✔
865
        r := &batch.Request[kvdb.RwTx]{
3✔
UNCOV
866
                Opts: batch.NewSchedulerOptions(opts...),
×
UNCOV
867
                Do: func(tx kvdb.RwTx) error {
×
868
                        return addLightningNode(tx, node)
869
                },
3✔
870
        }
871

872
        return c.nodeScheduler.Execute(ctx, r)
873
}
874

875
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
876
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
877
        if err != nil {
3✔
878
                return err
3✔
879
        }
3✔
880

3✔
UNCOV
881
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
×
UNCOV
882
        if err != nil {
×
883
                return err
884
        }
885

886
        updateIndex, err := nodes.CreateBucketIfNotExists(
3✔
887
                nodeUpdateIndexBucket,
3✔
UNCOV
888
        )
×
UNCOV
889
        if err != nil {
×
890
                return err
891
        }
3✔
892

893
        return putLightningNode(nodes, aliases, updateIndex, node)
894
}
895

896
// LookupAlias attempts to return the alias as advertised by the target node.
897
// TODO(roasbeef): currently assumes that aliases are unique...
3✔
898
func (c *KVStore) LookupAlias(pub *btcec.PublicKey) (string, error) {
3✔
899
        var alias string
3✔
900

6✔
901
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
3✔
902
                nodes := tx.ReadBucket(nodeBucket)
3✔
903
                if nodes == nil {
3✔
904
                        return ErrGraphNodesNotFound
3✔
905
                }
×
UNCOV
906

×
907
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
908
                if aliases == nil {
909
                        return ErrGraphNodesNotFound
910
                }
3✔
UNCOV
911

×
UNCOV
912
                nodePub := pub.SerializeCompressed()
×
913
                a := aliases.Get(nodePub)
914
                if a == nil {
915
                        return ErrNodeAliasNotFound
916
                }
3✔
917

3✔
918
                // TODO(roasbeef): should actually be using the utf-8
919
                // package...
920
                alias = string(a)
921

922
                return nil
923
        }, func() {
924
                alias = ""
925
        })
926
        if err != nil {
927
                return "", err
928
        }
929

3✔
930
        return alias, nil
3✔
931
}
3✔
932

3✔
933
// DeleteLightningNode starts a new database transaction to remove a vertex/node
3✔
934
// from the database according to the node's public key.
3✔
935
func (c *KVStore) DeleteLightningNode(nodePub route.Vertex) error {
6✔
936
        // TODO(roasbeef): ensure dangling edges are removed...
3✔
937
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
3✔
938
                nodes := tx.ReadWriteBucket(nodeBucket)
939
                if nodes == nil {
940
                        return ErrGraphNodeNotFound
3✔
941
                }
942

943
                return c.deleteLightningNode(nodes, nodePub[:])
3✔
944
        }, func() {})
3✔
945
}
3✔
UNCOV
946

×
UNCOV
947
// deleteLightningNode uses an existing database transaction to remove a
×
948
// vertex/node from the database according to the node's public key.
949
func (c *KVStore) deleteLightningNode(nodes kvdb.RwBucket,
3✔
950
        compressedPubKey []byte) error {
3✔
UNCOV
951

×
UNCOV
952
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
×
953
        if aliases == nil {
954
                return ErrGraphNodesNotFound
3✔
955
        }
3✔
956

3✔
957
        if err := aliases.Delete(compressedPubKey); err != nil {
3✔
958
                return err
×
959
        }
×
960

961
        // Before we delete the node, we'll fetch its current state so we can
3✔
962
        // determine when its last update was to clear out the node update
963
        // index.
964
        node, err := fetchLightningNode(nodes, compressedPubKey)
965
        if err != nil {
966
                return err
3✔
967
        }
3✔
968

3✔
969
        if err := nodes.Delete(compressedPubKey); err != nil {
6✔
970
                return err
3✔
971
        }
3✔
UNCOV
972

×
UNCOV
973
        // Finally, we'll delete the index entry for the node within the
×
974
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
975
        // need to track its last update.
3✔
976
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
3✔
UNCOV
977
        if nodeUpdateIndex == nil {
×
978
                return ErrGraphNodesNotFound
×
979
        }
980

3✔
981
        // In order to delete the entry, we'll need to reconstruct the key for
3✔
982
        // its last update.
3✔
UNCOV
983
        updateUnix := uint64(node.LastUpdate.Unix())
×
UNCOV
984
        var indexKey [8 + 33]byte
×
985
        byteOrder.PutUint64(indexKey[:8], updateUnix)
986
        copy(indexKey[8:], compressedPubKey)
987

988
        return nodeUpdateIndex.Delete(indexKey[:])
3✔
989
}
3✔
990

3✔
991
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
3✔
992
// undirected edge from the two target nodes are created. The information stored
3✔
993
// denotes the static attributes of the channel, such as the channelID, the keys
3✔
994
// involved in creation of the channel, and the set of features that the channel
3✔
UNCOV
995
// supports. The chanPoint and chanID are used to uniquely identify the edge
×
UNCOV
996
// globally within the database.
×
997
func (c *KVStore) AddChannelEdge(edge *models.ChannelEdgeInfo,
998
        opts ...batch.SchedulerOption) error {
3✔
999

1000
        ctx := context.TODO()
1001

1002
        var alreadyExists bool
UNCOV
1003
        r := &batch.Request[kvdb.RwTx]{
×
UNCOV
1004
                Opts: batch.NewSchedulerOptions(opts...),
×
UNCOV
1005
                Reset: func() {
×
UNCOV
1006
                        alreadyExists = false
×
UNCOV
1007
                },
×
UNCOV
1008
                Do: func(tx kvdb.RwTx) error {
×
UNCOV
1009
                        err := c.addChannelEdge(tx, edge)
×
1010

UNCOV
1011
                        // Silence ErrEdgeAlreadyExist so that the batch can
×
UNCOV
1012
                        // succeed, but propagate the error via local state.
×
1013
                        if errors.Is(err, ErrEdgeAlreadyExist) {
1014
                                alreadyExists = true
1015
                                return nil
1016
                        }
1017

1018
                        return err
3✔
1019
                },
3✔
1020
                OnCommit: func(err error) error {
3✔
1021
                        switch {
3✔
1022
                        case err != nil:
×
1023
                                return err
×
1024
                        case alreadyExists:
1025
                                return ErrEdgeAlreadyExist
3✔
UNCOV
1026
                        default:
×
UNCOV
1027
                                c.rejectCache.remove(edge.ChannelID)
×
1028
                                c.chanCache.remove(edge.ChannelID)
1029
                                return nil
1030
                        }
1031
                },
1032
        }
3✔
1033

3✔
UNCOV
1034
        return c.chanScheduler.Execute(ctx, r)
×
UNCOV
1035
}
×
1036

1037
// addChannelEdge is the private form of AddChannelEdge that allows callers to
3✔
UNCOV
1038
// utilize an existing db transaction.
×
UNCOV
1039
func (c *KVStore) addChannelEdge(tx kvdb.RwTx,
×
1040
        edge *models.ChannelEdgeInfo) error {
1041

1042
        // Construct the channel's primary key which is the 8-byte channel ID.
1043
        var chanKey [8]byte
1044
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1045

3✔
UNCOV
1046
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
×
UNCOV
1047
        if err != nil {
×
1048
                return err
1049
        }
1050
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1051
        if err != nil {
3✔
1052
                return err
3✔
1053
        }
3✔
1054
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1055
        if err != nil {
3✔
1056
                return err
3✔
1057
        }
1058
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1059
        if err != nil {
1060
                return err
1061
        }
1062

1063
        // First, attempt to check if this edge has already been created. If
1064
        // so, then we can exit early as this method is meant to be idempotent.
1065
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
1066
                return ErrEdgeAlreadyExist
3✔
1067
        }
3✔
1068

3✔
1069
        // Before we insert the channel into the database, we'll ensure that
3✔
1070
        // both nodes already exist in the channel graph. If either node
3✔
1071
        // doesn't, then we'll insert a "shell" node that just includes its
3✔
1072
        // public key, so subsequent validation and queries can work properly.
3✔
1073
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
6✔
1074
        switch {
3✔
1075
        case errors.Is(node1Err, ErrGraphNodeNotFound):
3✔
1076
                node1Shell := models.LightningNode{
3✔
1077
                        PubKeyBytes:          edge.NodeKey1Bytes,
3✔
1078
                        HaveNodeAnnouncement: false,
3✔
1079
                }
3✔
1080
                err := addLightningNode(tx, &node1Shell)
3✔
1081
                if err != nil {
3✔
1082
                        return fmt.Errorf("unable to create shell node "+
×
1083
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1084
                }
×
1085
        case node1Err != nil:
1086
                return node1Err
3✔
1087
        }
1088

3✔
1089
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
3✔
UNCOV
1090
        switch {
×
UNCOV
1091
        case errors.Is(node2Err, ErrGraphNodeNotFound):
×
UNCOV
1092
                node2Shell := models.LightningNode{
×
UNCOV
1093
                        PubKeyBytes:          edge.NodeKey2Bytes,
×
1094
                        HaveNodeAnnouncement: false,
3✔
1095
                }
3✔
1096
                err := addLightningNode(tx, &node2Shell)
3✔
1097
                if err != nil {
3✔
1098
                        return fmt.Errorf("unable to create shell node "+
1099
                                "for: %x: %w", edge.NodeKey2Bytes, err)
1100
                }
1101
        case node2Err != nil:
1102
                return node2Err
3✔
1103
        }
1104

1105
        // If the edge hasn't been created yet, then we'll first add it to the
1106
        // edge index in order to associate the edge between two nodes and also
1107
        // store the static components of the channel.
1108
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
3✔
1109
                return err
3✔
1110
        }
3✔
1111

3✔
1112
        // Mark edge policies for both sides as unknown. This is to enable
3✔
1113
        // efficient incoming channel lookup for a node.
3✔
1114
        keys := []*[33]byte{
3✔
1115
                &edge.NodeKey1Bytes,
3✔
UNCOV
1116
                &edge.NodeKey2Bytes,
×
UNCOV
1117
        }
×
1118
        for _, key := range keys {
3✔
1119
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
3✔
UNCOV
1120
                if err != nil {
×
1121
                        return err
×
1122
                }
3✔
1123
        }
3✔
UNCOV
1124

×
UNCOV
1125
        // Finally we add it to the channel index which maps channel points
×
1126
        // (outpoints) to the shorter channel ID's.
3✔
1127
        var b bytes.Buffer
3✔
UNCOV
1128
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
×
1129
                return err
×
1130
        }
1131

1132
        return chanIndex.Put(b.Bytes(), chanKey[:])
1133
}
3✔
UNCOV
1134

×
UNCOV
1135
// HasChannelEdge returns true if the database knows of a channel edge with the
×
1136
// passed channel ID, and false otherwise. If an edge with that ID is found
1137
// within the graph, then two time stamps representing the last time the edge
1138
// was updated for both directed edges are returned along with the boolean. If
1139
// it is not found, then the zombie index is checked and its result is returned
1140
// as the second boolean.
1141
func (c *KVStore) HasChannelEdge(
3✔
1142
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
3✔
1143

3✔
1144
        var (
3✔
1145
                upd1Time time.Time
3✔
1146
                upd2Time time.Time
3✔
1147
                exists   bool
3✔
1148
                isZombie bool
3✔
1149
        )
3✔
UNCOV
1150

×
UNCOV
1151
        // We'll query the cache with the shared lock held to allow multiple
×
UNCOV
1152
        // readers to access values in the cache concurrently if they exist.
×
UNCOV
1153
        c.cacheMu.RLock()
×
UNCOV
1154
        if entry, ok := c.rejectCache.get(chanID); ok {
×
1155
                c.cacheMu.RUnlock()
1156
                upd1Time = time.Unix(entry.upd1Time, 0)
1157
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1158
                exists, isZombie = entry.flags.unpack()
3✔
1159

3✔
1160
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1161
        }
3✔
1162
        c.cacheMu.RUnlock()
3✔
1163

3✔
1164
        c.cacheMu.Lock()
3✔
1165
        defer c.cacheMu.Unlock()
3✔
UNCOV
1166

×
UNCOV
1167
        // The item was not found with the shared lock, so we'll acquire the
×
UNCOV
1168
        // exclusive lock and check the cache again in case another method added
×
UNCOV
1169
        // the entry to the cache while no lock was held.
×
UNCOV
1170
        if entry, ok := c.rejectCache.get(chanID); ok {
×
1171
                upd1Time = time.Unix(entry.upd1Time, 0)
1172
                upd2Time = time.Unix(entry.upd2Time, 0)
1173
                exists, isZombie = entry.flags.unpack()
1174

1175
                return upd1Time, upd2Time, exists, isZombie, nil
1176
        }
3✔
UNCOV
1177

×
UNCOV
1178
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
1179
                edges := tx.ReadBucket(edgeBucket)
1180
                if edges == nil {
1181
                        return ErrGraphNoEdgesFound
1182
                }
3✔
1183
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1184
                if edgeIndex == nil {
3✔
1185
                        return ErrGraphNoEdgesFound
3✔
1186
                }
6✔
1187

3✔
1188
                var channelID [8]byte
3✔
UNCOV
1189
                byteOrder.PutUint64(channelID[:], chanID)
×
UNCOV
1190

×
1191
                // If the edge doesn't exist, then we'll also check our zombie
1192
                // index.
1193
                if edgeIndex.Get(channelID[:]) == nil {
1194
                        exists = false
1195
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
1196
                        if zombieIndex != nil {
3✔
UNCOV
1197
                                isZombie, _, _ = isZombieEdge(
×
UNCOV
1198
                                        zombieIndex, chanID,
×
1199
                                )
1200
                        }
3✔
1201

1202
                        return nil
1203
                }
1204

1205
                exists = true
1206
                isZombie = false
1207

1208
                // If the channel has been found in the graph, then retrieve
1209
                // the edges itself so we can return the last updated
1210
                // timestamps.
3✔
1211
                nodes := tx.ReadBucket(nodeBucket)
3✔
1212
                if nodes == nil {
3✔
1213
                        return ErrGraphNodeNotFound
3✔
1214
                }
3✔
1215

3✔
1216
                e1, e2, err := fetchChanEdgePolicies(
3✔
1217
                        edgeIndex, edges, channelID[:],
3✔
1218
                )
3✔
1219
                if err != nil {
3✔
1220
                        return err
3✔
1221
                }
3✔
1222

6✔
1223
                // As we may have only one of the edges populated, only set the
3✔
1224
                // update time if the edge was found in the database.
3✔
1225
                if e1 != nil {
3✔
1226
                        upd1Time = e1.LastUpdate
3✔
1227
                }
3✔
1228
                if e2 != nil {
3✔
1229
                        upd2Time = e2.LastUpdate
3✔
1230
                }
3✔
1231

3✔
1232
                return nil
3✔
1233
        }, func() {}); err != nil {
3✔
1234
                return time.Time{}, time.Time{}, exists, isZombie, err
3✔
1235
        }
3✔
1236

3✔
1237
        c.rejectCache.insert(chanID, rejectCacheEntry{
3✔
1238
                upd1Time: upd1Time.Unix(),
6✔
1239
                upd2Time: upd2Time.Unix(),
3✔
1240
                flags:    packRejectFlags(exists, isZombie),
3✔
1241
        })
3✔
1242

3✔
1243
        return upd1Time, upd2Time, exists, isZombie, nil
3✔
1244
}
3✔
1245

1246
// AddEdgeProof sets the proof of an existing edge in the graph database.
6✔
1247
func (c *KVStore) AddEdgeProof(chanID lnwire.ShortChannelID,
3✔
1248
        proof *models.ChannelAuthProof) error {
3✔
UNCOV
1249

×
UNCOV
1250
        // Construct the channel's primary key which is the 8-byte channel ID.
×
1251
        var chanKey [8]byte
3✔
1252
        binary.BigEndian.PutUint64(chanKey[:], chanID.ToUint64())
3✔
UNCOV
1253

×
UNCOV
1254
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
1255
                edges := tx.ReadWriteBucket(edgeBucket)
1256
                if edges == nil {
3✔
1257
                        return ErrEdgeNotFound
3✔
1258
                }
3✔
1259

3✔
1260
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1261
                if edgeIndex == nil {
6✔
1262
                        return ErrEdgeNotFound
3✔
1263
                }
3✔
1264

6✔
1265
                edge, err := fetchChanEdgeInfo(edgeIndex, chanKey[:])
3✔
1266
                if err != nil {
3✔
1267
                        return err
3✔
1268
                }
3✔
1269

1270
                edge.AuthProof = proof
3✔
1271

1272
                return putChanEdgeInfo(edgeIndex, &edge, chanKey)
1273
        }, func() {})
3✔
1274
}
3✔
1275

3✔
1276
const (
3✔
1277
        // pruneTipBytes is the total size of the value which stores a prune
3✔
1278
        // entry of the graph in the prune log. The "prune tip" is the last
3✔
1279
        // entry in the prune log, and indicates if the channel graph is in
3✔
1280
        // sync with the current UTXO state. The structure of the value
3✔
UNCOV
1281
        // is: blockHash, taking 32 bytes total.
×
UNCOV
1282
        pruneTipBytes = 32
×
1283
)
1284

3✔
1285
// PruneGraph prunes newly closed channels from the channel graph in response
3✔
1286
// to a new block being solved on the network. Any transactions which spend the
3✔
1287
// funding output of any known channels within he graph will be deleted.
3✔
UNCOV
1288
// Additionally, the "prune tip", or the last block which has been used to
×
UNCOV
1289
// prune the graph is stored so callers can ensure the graph is fully in sync
×
1290
// with the current UTXO state. A slice of channels that have been closed by
1291
// the target block along with any pruned nodes are returned if the function
1292
// succeeds without error.
1293
func (c *KVStore) PruneGraph(spentOutputs []*wire.OutPoint,
6✔
1294
        blockHash *chainhash.Hash, blockHeight uint32) (
3✔
1295
        []*models.ChannelEdgeInfo, []route.Vertex, error) {
3✔
1296

6✔
1297
        c.cacheMu.Lock()
3✔
1298
        defer c.cacheMu.Unlock()
3✔
1299

1300
        var (
3✔
1301
                chansClosed []*models.ChannelEdgeInfo
3✔
UNCOV
1302
                prunedNodes []route.Vertex
×
UNCOV
1303
        )
×
1304

1305
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
3✔
1306
                // First grab the edges bucket which houses the information
3✔
1307
                // we'd like to delete
3✔
1308
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1309
                if err != nil {
3✔
1310
                        return err
3✔
1311
                }
3✔
1312

1313
                // Next grab the two edge indexes which will also need to be
1314
                // updated.
1315
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1316
                if err != nil {
3✔
1317
                        return err
3✔
1318
                }
3✔
1319
                chanIndex, err := edges.CreateBucketIfNotExists(
3✔
1320
                        channelPointBucket,
3✔
1321
                )
3✔
1322
                if err != nil {
6✔
1323
                        return err
3✔
1324
                }
3✔
UNCOV
1325
                nodes := tx.ReadWriteBucket(nodeBucket)
×
UNCOV
1326
                if nodes == nil {
×
1327
                        return ErrSourceNodeNotSet
1328
                }
3✔
1329
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
UNCOV
1330
                if err != nil {
×
1331
                        return err
×
1332
                }
1333

3✔
1334
                // For each of the outpoints that have been spent within the
3✔
UNCOV
1335
                // block, we attempt to delete them from the graph as if that
×
UNCOV
1336
                // outpoint was a channel, then it has now been closed.
×
1337
                for _, chanPoint := range spentOutputs {
1338
                        // TODO(roasbeef): load channel bloom filter, continue
3✔
1339
                        // if NOT if filter
3✔
1340

3✔
1341
                        var opBytes bytes.Buffer
3✔
1342
                        err := WriteOutpoint(&opBytes, chanPoint)
1343
                        if err != nil {
1344
                                return err
1345
                        }
1346

1347
                        // First attempt to see if the channel exists within
1348
                        // the database, if not, then we can exit early.
1349
                        chanID := chanIndex.Get(opBytes.Bytes())
1350
                        if chanID == nil {
1351
                                continue
1352
                        }
1353

1354
                        // Attempt to delete the channel, an ErrEdgeNotFound
1355
                        // will be returned if that outpoint isn't known to be
1356
                        // a channel. If no error is returned, then a channel
1357
                        // was successfully pruned.
1358
                        edgeInfo, err := c.delChannelEdgeUnsafe(
1359
                                edges, edgeIndex, chanIndex, zombieIndex,
1360
                                chanID, false, false,
1361
                        )
1362
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
1363
                                return err
3✔
1364
                        }
3✔
1365

3✔
1366
                        chansClosed = append(chansClosed, edgeInfo)
3✔
1367
                }
3✔
1368

3✔
1369
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
3✔
1370
                if err != nil {
3✔
1371
                        return err
3✔
1372
                }
3✔
1373

6✔
1374
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
3✔
1375
                        pruneLogBucket,
3✔
1376
                )
3✔
1377
                if err != nil {
3✔
1378
                        return err
×
1379
                }
×
1380

1381
                // With the graph pruned, add a new entry to the prune log,
1382
                // which can be used to check if the graph is fully synced with
1383
                // the current UTXO state.
3✔
1384
                var blockHeightBytes [4]byte
3✔
UNCOV
1385
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
×
UNCOV
1386

×
1387
                var newTip [pruneTipBytes]byte
3✔
1388
                copy(newTip[:], blockHash[:])
3✔
1389

3✔
1390
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
3✔
UNCOV
1391
                if err != nil {
×
1392
                        return err
×
1393
                }
3✔
1394

3✔
UNCOV
1395
                // Now that the graph has been pruned, we'll also attempt to
×
UNCOV
1396
                // prune any nodes that have had a channel closed within the
×
1397
                // latest block.
3✔
1398
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
UNCOV
1399

×
UNCOV
1400
                return err
×
1401
        }, func() {
1402
                chansClosed = nil
1403
                prunedNodes = nil
1404
        })
1405
        if err != nil {
6✔
1406
                return nil, nil, err
3✔
1407
        }
3✔
1408

3✔
1409
        for _, channel := range chansClosed {
3✔
1410
                c.rejectCache.remove(channel.ChannelID)
3✔
1411
                c.chanCache.remove(channel.ChannelID)
3✔
UNCOV
1412
        }
×
UNCOV
1413

×
1414
        return chansClosed, prunedNodes, nil
1415
}
1416

1417
// PruneGraphNodes is a garbage collection method which attempts to prune out
3✔
1418
// any nodes from the channel graph that are currently unconnected. This ensure
3✔
UNCOV
1419
// that we only maintain a graph of reachable nodes. In the event that a pruned
×
1420
// node gains more channels, it will be re-added back to the graph.
1421
func (c *KVStore) PruneGraphNodes() ([]route.Vertex, error) {
1422
        var prunedNodes []route.Vertex
1423
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
1424
                nodes := tx.ReadWriteBucket(nodeBucket)
1425
                if nodes == nil {
1426
                        return ErrGraphNodesNotFound
3✔
1427
                }
3✔
1428
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1429
                if edges == nil {
3✔
1430
                        return ErrGraphNotFound
3✔
1431
                }
×
UNCOV
1432
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
×
1433
                if edgeIndex == nil {
1434
                        return ErrGraphNoEdgesFound
3✔
1435
                }
1436

1437
                var err error
3✔
1438
                prunedNodes, err = c.pruneGraphNodes(nodes, edgeIndex)
3✔
UNCOV
1439
                if err != nil {
×
1440
                        return err
×
1441
                }
1442

3✔
1443
                return nil
3✔
1444
        }, func() {
3✔
1445
                prunedNodes = nil
3✔
UNCOV
1446
        })
×
UNCOV
1447

×
1448
        return prunedNodes, err
1449
}
1450

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

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

3✔
1459
        // We'll retrieve the graph's source node to ensure we don't remove it
3✔
UNCOV
1460
        // even if it no longer has any open channels.
×
UNCOV
1461
        sourceNode, err := c.sourceNode(nodes)
×
1462
        if err != nil {
1463
                return nil, err
1464
        }
1465

1466
        // We'll use this map to keep count the number of references to a node
3✔
1467
        // in the graph. A node should only be removed once it has no more
3✔
1468
        // references in the graph.
3✔
1469
        nodeRefCounts := make(map[[33]byte]int)
3✔
1470
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
3✔
1471
                // If this is the source key, then we skip this
3✔
1472
                // iteration as the value for this key is a pubKey
3✔
1473
                // rather than raw node information.
3✔
UNCOV
1474
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
×
UNCOV
1475
                        return nil
×
1476
                }
1477

6✔
1478
                var nodePub [33]byte
3✔
1479
                copy(nodePub[:], pubKey)
3✔
1480
                nodeRefCounts[nodePub] = 0
3✔
1481

1482
                return nil
3✔
1483
        })
1484
        if err != nil {
1485
                return nil, err
1486
        }
1487

1488
        // To ensure we never delete the source node, we'll start off by
1489
        // bumping its ref count to 1.
3✔
1490
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
3✔
1491

6✔
1492
        // Next, we'll run through the edgeIndex which maps a channel ID to the
3✔
1493
        // edge info. We'll use this scan to populate our reference count map
3✔
UNCOV
1494
        // above.
×
UNCOV
1495
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
×
1496
                // The first 66 bytes of the edge info contain the pubkeys of
3✔
1497
                // the nodes that this edge attaches. We'll extract them, and
3✔
UNCOV
1498
                // add them to the ref count map.
×
UNCOV
1499
                var node1, node2 [33]byte
×
1500
                copy(node1[:], edgeInfoBytes[:33])
3✔
1501
                copy(node2[:], edgeInfoBytes[33:])
3✔
UNCOV
1502

×
UNCOV
1503
                // With the nodes extracted, we'll increase the ref count of
×
1504
                // each of the nodes.
1505
                nodeRefCounts[node1]++
3✔
1506
                nodeRefCounts[node2]++
3✔
1507

3✔
UNCOV
1508
                return nil
×
UNCOV
1509
        })
×
1510
        if err != nil {
1511
                return nil, err
3✔
1512
        }
3✔
1513

3✔
1514
        // Finally, we'll make a second pass over the set of nodes, and delete
3✔
1515
        // any nodes that have a ref count of zero.
1516
        var pruned []route.Vertex
3✔
1517
        for nodePubKey, refCount := range nodeRefCounts {
1518
                // If the ref count of the node isn't zero, then we can safely
1519
                // skip it as it still has edges to or from it within the
1520
                // graph.
1521
                if refCount != 0 {
1522
                        continue
1523
                }
3✔
1524

3✔
1525
                // If we reach this point, then there are no longer any edges
3✔
1526
                // that connect this node, so we can delete it.
3✔
1527
                err := c.deleteLightningNode(nodes, nodePubKey[:])
3✔
1528
                if err != nil {
3✔
1529
                        if errors.Is(err, ErrGraphNodeNotFound) ||
3✔
1530
                                errors.Is(err, ErrGraphNodesNotFound) {
3✔
1531

×
1532
                                log.Warnf("Unable to prune node %x from the "+
×
1533
                                        "graph: %v", nodePubKey, err)
1534
                                continue
1535
                        }
1536

1537
                        return nil, err
3✔
1538
                }
6✔
1539

3✔
1540
                log.Infof("Pruned unconnected node %x from channel graph",
3✔
1541
                        nodePubKey[:])
3✔
1542

6✔
1543
                pruned = append(pruned, nodePubKey)
3✔
1544
        }
3✔
1545

1546
        if len(pruned) > 0 {
3✔
1547
                log.Infof("Pruned %v unconnected nodes from the channel graph",
3✔
1548
                        len(pruned))
3✔
1549
        }
3✔
1550

3✔
1551
        return pruned, err
1552
}
3✔
UNCOV
1553

×
UNCOV
1554
// DisconnectBlockAtHeight is used to indicate that the block specified
×
1555
// by the passed height has been disconnected from the main chain. This
1556
// will "rewind" the graph back to the height below, deleting channels
1557
// that are no longer confirmed from the graph. The prune log will be
1558
// set to the last prune height valid for the remaining chain.
3✔
1559
// Channels that were removed from the graph resulting from the
3✔
1560
// disconnected block are returned.
3✔
1561
func (c *KVStore) DisconnectBlockAtHeight(height uint32) (
3✔
1562
        []*models.ChannelEdgeInfo, error) {
3✔
1563

6✔
1564
        // Every channel having a ShortChannelID starting at 'height'
3✔
1565
        // will no longer be confirmed.
3✔
1566
        startShortChanID := lnwire.ShortChannelID{
3✔
1567
                BlockHeight: height,
3✔
1568
        }
3✔
1569

3✔
1570
        // Delete everything after this height from the db up until the
3✔
1571
        // SCID alias range.
3✔
1572
        endShortChanID := aliasmgr.StartingAlias
3✔
1573

3✔
1574
        // The block height will be the 3 first bytes of the channel IDs.
3✔
1575
        var chanIDStart [8]byte
3✔
1576
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
3✔
1577
        var chanIDEnd [8]byte
3✔
1578
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
3✔
UNCOV
1579

×
UNCOV
1580
        c.cacheMu.Lock()
×
1581
        defer c.cacheMu.Unlock()
1582

1583
        // Keep track of the channels that are removed from the graph.
1584
        var removedChans []*models.ChannelEdgeInfo
3✔
1585

6✔
1586
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
3✔
1587
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1588
                if err != nil {
3✔
1589
                        return err
6✔
1590
                }
3✔
1591
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1592
                if err != nil {
1593
                        return err
1594
                }
1595
                chanIndex, err := edges.CreateBucketIfNotExists(
3✔
1596
                        channelPointBucket,
3✔
UNCOV
1597
                )
×
UNCOV
1598
                if err != nil {
×
1599
                        return err
×
1600
                }
×
UNCOV
1601
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
×
UNCOV
1602
                if err != nil {
×
1603
                        return err
1604
                }
UNCOV
1605

×
1606
                // Scan from chanIDStart to chanIDEnd, deleting every
1607
                // found edge.
1608
                // NOTE: we must delete the edges after the cursor loop, since
3✔
1609
                // modifying the bucket while traversing is not safe.
3✔
1610
                // NOTE: We use a < comparison in bytes.Compare instead of <=
3✔
1611
                // so that the StartingAlias itself isn't deleted.
3✔
1612
                var keys [][]byte
1613
                cursor := edgeIndex.ReadWriteCursor()
1614

6✔
1615
                //nolint:ll
3✔
1616
                for k, _ := cursor.Seek(chanIDStart[:]); k != nil &&
3✔
1617
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, _ = cursor.Next() {
3✔
1618
                        keys = append(keys, k)
1619
                }
3✔
1620

1621
                for _, k := range keys {
1622
                        edgeInfo, err := c.delChannelEdgeUnsafe(
1623
                                edges, edgeIndex, chanIndex, zombieIndex,
1624
                                k, false, false,
1625
                        )
1626
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
1627
                                return err
1628
                        }
1629

1630
                        removedChans = append(removedChans, edgeInfo)
2✔
1631
                }
2✔
1632

2✔
1633
                // Delete all the entries in the prune log having a height
2✔
1634
                // greater or equal to the block disconnected.
2✔
1635
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
2✔
1636
                if err != nil {
2✔
1637
                        return err
2✔
1638
                }
2✔
1639

2✔
1640
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
2✔
1641
                        pruneLogBucket,
2✔
1642
                )
2✔
1643
                if err != nil {
2✔
1644
                        return err
2✔
1645
                }
2✔
1646

2✔
1647
                var pruneKeyStart [4]byte
2✔
1648
                byteOrder.PutUint32(pruneKeyStart[:], height)
2✔
1649

2✔
1650
                var pruneKeyEnd [4]byte
2✔
1651
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
2✔
1652

2✔
1653
                // To avoid modifying the bucket while traversing, we delete
2✔
1654
                // the keys in a second loop.
4✔
1655
                var pruneKeys [][]byte
2✔
1656
                pruneCursor := pruneBucket.ReadWriteCursor()
2✔
UNCOV
1657
                //nolint:ll
×
UNCOV
1658
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
×
1659
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
2✔
1660
                        pruneKeys = append(pruneKeys, k)
2✔
UNCOV
1661
                }
×
UNCOV
1662

×
1663
                for _, k := range pruneKeys {
2✔
1664
                        if err := pruneBucket.Delete(k); err != nil {
2✔
1665
                                return err
2✔
1666
                        }
2✔
UNCOV
1667
                }
×
UNCOV
1668

×
1669
                return nil
2✔
1670
        }, func() {
2✔
UNCOV
1671
                removedChans = nil
×
UNCOV
1672
        }); err != nil {
×
1673
                return nil, err
1674
        }
1675

1676
        for _, channel := range removedChans {
1677
                c.rejectCache.remove(channel.ChannelID)
1678
                c.chanCache.remove(channel.ChannelID)
1679
        }
1680

2✔
1681
        return removedChans, nil
2✔
1682
}
2✔
1683

2✔
1684
// PruneTip returns the block height and hash of the latest block that has been
2✔
1685
// used to prune channels in the graph. Knowing the "prune tip" allows callers
4✔
1686
// to tell if the graph is currently in sync with the current best known UTXO
2✔
1687
// state.
2✔
1688
func (c *KVStore) PruneTip() (*chainhash.Hash, uint32, error) {
1689
        var (
4✔
1690
                tipHash   chainhash.Hash
2✔
1691
                tipHeight uint32
2✔
1692
        )
2✔
1693

2✔
1694
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
2✔
UNCOV
1695
                graphMeta := tx.ReadBucket(graphMetaBucket)
×
UNCOV
1696
                if graphMeta == nil {
×
1697
                        return ErrGraphNotFound
1698
                }
2✔
1699
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
1700
                if pruneBucket == nil {
1701
                        return ErrGraphNeverPruned
1702
                }
1703

2✔
1704
                pruneCursor := pruneBucket.ReadCursor()
2✔
UNCOV
1705

×
UNCOV
1706
                // The prune key with the largest block height will be our
×
1707
                // prune tip.
1708
                k, v := pruneCursor.Last()
2✔
1709
                if k == nil {
2✔
1710
                        return ErrGraphNeverPruned
2✔
1711
                }
2✔
UNCOV
1712

×
UNCOV
1713
                // Once we have the prune tip, the value will be the block hash,
×
1714
                // and the key the block height.
1715
                copy(tipHash[:], v)
2✔
1716
                tipHeight = byteOrder.Uint32(k)
2✔
1717

2✔
1718
                return nil
2✔
1719
        }, func() {})
2✔
1720
        if err != nil {
2✔
1721
                return nil, 0, err
2✔
1722
        }
2✔
1723

2✔
1724
        return &tipHash, tipHeight, nil
2✔
1725
}
2✔
1726

2✔
1727
// DeleteChannelEdges removes edges with the given channel IDs from the
4✔
1728
// database and marks them as zombies. This ensures that we're unable to re-add
2✔
1729
// it to our database once again. If an edge does not exist within the
2✔
1730
// database, then ErrEdgeNotFound will be returned. If strictZombiePruning is
1731
// true, then when we mark these edges as zombies, we'll set up the keys such
4✔
1732
// that we require the node that failed to send the fresh update to be the one
2✔
UNCOV
1733
// that resurrects the channel from its zombie state. The markZombie bool
×
UNCOV
1734
// denotes whether or not to mark the channel as a zombie.
×
1735
func (c *KVStore) DeleteChannelEdges(strictZombiePruning, markZombie bool,
1736
        chanIDs ...uint64) ([]*models.ChannelEdgeInfo, error) {
1737

2✔
1738
        // TODO(roasbeef): possibly delete from node bucket if node has no more
2✔
1739
        // channels
2✔
1740
        // TODO(roasbeef): don't delete both edges?
2✔
UNCOV
1741

×
UNCOV
1742
        c.cacheMu.Lock()
×
1743
        defer c.cacheMu.Unlock()
1744

4✔
1745
        var infos []*models.ChannelEdgeInfo
2✔
1746
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
2✔
1747
                edges := tx.ReadWriteBucket(edgeBucket)
2✔
1748
                if edges == nil {
1749
                        return ErrEdgeNotFound
2✔
1750
                }
1751
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
1752
                if edgeIndex == nil {
1753
                        return ErrEdgeNotFound
1754
                }
1755
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
1756
                if chanIndex == nil {
3✔
1757
                        return ErrEdgeNotFound
3✔
1758
                }
3✔
1759
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1760
                if nodes == nil {
3✔
1761
                        return ErrGraphNodeNotFound
3✔
1762
                }
6✔
1763
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1764
                if err != nil {
3✔
1765
                        return err
×
1766
                }
×
1767

3✔
1768
                var rawChanID [8]byte
3✔
UNCOV
1769
                for _, chanID := range chanIDs {
×
UNCOV
1770
                        byteOrder.PutUint64(rawChanID[:], chanID)
×
1771
                        edgeInfo, err := c.delChannelEdgeUnsafe(
1772
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1773
                                rawChanID[:], markZombie, strictZombiePruning,
3✔
1774
                        )
3✔
1775
                        if err != nil {
3✔
1776
                                return err
3✔
1777
                        }
6✔
1778

3✔
1779
                        infos = append(infos, edgeInfo)
3✔
1780
                }
1781

1782
                return nil
1783
        }, func() {
3✔
1784
                infos = nil
3✔
1785
        })
3✔
1786
        if err != nil {
3✔
1787
                return nil, err
3✔
1788
        }
6✔
1789

3✔
1790
        for _, chanID := range chanIDs {
3✔
1791
                c.rejectCache.remove(chanID)
1792
                c.chanCache.remove(chanID)
3✔
1793
        }
1794

1795
        return infos, nil
1796
}
1797

1798
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1799
// passed channel point (outpoint). If the passed channel doesn't exist within
1800
// the database, then ErrEdgeNotFound is returned.
1801
func (c *KVStore) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
1802
        var chanID uint64
1803
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
1804
                var err error
3✔
1805
                chanID, err = getChanID(tx, chanPoint)
3✔
1806
                return err
3✔
1807
        }, func() {
3✔
1808
                chanID = 0
3✔
1809
        }); err != nil {
3✔
1810
                return 0, err
3✔
1811
        }
3✔
1812

3✔
1813
        return chanID, nil
3✔
1814
}
6✔
1815

3✔
1816
// getChanID returns the assigned channel ID for a given channel point.
3✔
UNCOV
1817
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
×
UNCOV
1818
        var b bytes.Buffer
×
1819
        if err := WriteOutpoint(&b, chanPoint); err != nil {
3✔
1820
                return 0, err
3✔
1821
        }
×
UNCOV
1822

×
1823
        edges := tx.ReadBucket(edgeBucket)
3✔
1824
        if edges == nil {
3✔
1825
                return 0, ErrGraphNoEdgesFound
×
1826
        }
×
1827
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1828
        if chanIndex == nil {
3✔
1829
                return 0, ErrGraphNoEdgesFound
×
1830
        }
×
1831

3✔
1832
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
UNCOV
1833
        if chanIDBytes == nil {
×
UNCOV
1834
                return 0, ErrEdgeNotFound
×
1835
        }
1836

3✔
1837
        chanID := byteOrder.Uint64(chanIDBytes)
6✔
1838

3✔
1839
        return chanID, nil
3✔
1840
}
3✔
1841

3✔
1842
// TODO(roasbeef): allow updates to use Batch?
3✔
1843

3✔
UNCOV
1844
// HighestChanID returns the "highest" known channel ID in the channel graph.
×
UNCOV
1845
// This represents the "newest" channel from the PoV of the chain. This method
×
1846
// can be used by peers to quickly determine if they're graphs are in sync.
1847
func (c *KVStore) HighestChanID() (uint64, error) {
3✔
1848
        var cid uint64
1849

1850
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
3✔
1851
                edges := tx.ReadBucket(edgeBucket)
3✔
1852
                if edges == nil {
3✔
1853
                        return ErrGraphNoEdgesFound
3✔
1854
                }
3✔
UNCOV
1855
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
×
UNCOV
1856
                if edgeIndex == nil {
×
1857
                        return ErrGraphNoEdgesFound
1858
                }
6✔
1859

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

3✔
1864
                lastChanID, _ := cidCursor.Last()
1865

1866
                // If there's no key, then this means that we don't actually
1867
                // know of any channels, so we'll return a predicable error.
1868
                if lastChanID == nil {
1869
                        return ErrGraphNoEdgesFound
3✔
1870
                }
3✔
1871

6✔
1872
                // Otherwise, we'll de serialize the channel ID and return it
3✔
1873
                // to the caller.
3✔
1874
                cid = byteOrder.Uint64(lastChanID)
3✔
1875

6✔
1876
                return nil
3✔
1877
        }, func() {
6✔
1878
                cid = 0
3✔
1879
        })
3✔
1880
        if err != nil && !errors.Is(err, ErrGraphNoEdgesFound) {
1881
                return 0, err
3✔
1882
        }
1883

1884
        return cid, nil
1885
}
3✔
1886

3✔
1887
// ChannelEdge represents the complete set of information for a channel edge in
3✔
UNCOV
1888
// the known channel graph. This struct couples the core information of the
×
UNCOV
1889
// edge as well as each of the known advertised edge policies.
×
1890
type ChannelEdge struct {
1891
        // Info contains all the static information describing the channel.
3✔
1892
        Info *models.ChannelEdgeInfo
3✔
UNCOV
1893

×
UNCOV
1894
        // Policy1 points to the "first" edge policy of the channel containing
×
1895
        // the dynamic information required to properly route through the edge.
3✔
1896
        Policy1 *models.ChannelEdgePolicy
3✔
UNCOV
1897

×
UNCOV
1898
        // Policy2 points to the "second" edge policy of the channel containing
×
1899
        // the dynamic information required to properly route through the edge.
1900
        Policy2 *models.ChannelEdgePolicy
3✔
1901

6✔
1902
        // Node1 is "node 1" in the channel. This is the node that would have
3✔
1903
        // produced Policy1 if it exists.
3✔
1904
        Node1 *models.LightningNode
1905

3✔
1906
        // Node2 is "node 2" in the channel. This is the node that would have
3✔
1907
        // produced Policy2 if it exists.
3✔
1908
        Node2 *models.LightningNode
1909
}
1910

1911
// ChanUpdatesInHorizon returns all the known channel edges which have at least
1912
// one edge that has an update timestamp within the specified horizon.
1913
func (c *KVStore) ChanUpdatesInHorizon(startTime,
1914
        endTime time.Time) ([]ChannelEdge, error) {
1915

3✔
1916
        // To ensure we don't return duplicate ChannelEdges, we'll use an
3✔
1917
        // additional map to keep track of the edges already seen to prevent
3✔
1918
        // re-adding it.
6✔
1919
        var edgesSeen map[uint64]struct{}
3✔
1920
        var edgesToCache map[uint64]ChannelEdge
3✔
UNCOV
1921
        var edgesInHorizon []ChannelEdge
×
UNCOV
1922

×
1923
        c.cacheMu.Lock()
3✔
1924
        defer c.cacheMu.Unlock()
3✔
UNCOV
1925

×
UNCOV
1926
        var hits int
×
1927
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
1928
                edges := tx.ReadBucket(edgeBucket)
1929
                if edges == nil {
1930
                        return ErrGraphNoEdgesFound
3✔
1931
                }
3✔
1932
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1933
                if edgeIndex == nil {
3✔
1934
                        return ErrGraphNoEdgesFound
3✔
1935
                }
3✔
1936
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
6✔
1937
                if edgeUpdateIndex == nil {
3✔
1938
                        return ErrGraphNoEdgesFound
3✔
1939
                }
1940

1941
                nodes := tx.ReadBucket(nodeBucket)
1942
                if nodes == nil {
3✔
1943
                        return ErrGraphNodesNotFound
3✔
1944
                }
3✔
1945

3✔
1946
                // We'll now obtain a cursor to perform a range query within
3✔
1947
                // the index to find all channels within the horizon.
3✔
1948
                updateCursor := edgeUpdateIndex.ReadCursor()
3✔
UNCOV
1949

×
UNCOV
1950
                var startTimeBytes, endTimeBytes [8 + 8]byte
×
1951
                byteOrder.PutUint64(
1952
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
1953
                )
1954
                byteOrder.PutUint64(
1955
                        endTimeBytes[:8], uint64(endTime.Unix()),
1956
                )
1957

1958
                // With our start and end times constructed, we'll step through
1959
                // the index collecting the info and policy of each update of
1960
                // each channel that has a last update within the time range.
1961
                //
1962
                //nolint:ll
1963
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
1964
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
1965
                        // We have a new eligible entry, so we'll slice of the
1966
                        // chan ID so we can query it in the DB.
1967
                        chanID := indexKey[8:]
1968

1969
                        // If we've already retrieved the info and policies for
1970
                        // this edge, then we can skip it as we don't need to do
1971
                        // so again.
1972
                        chanIDInt := byteOrder.Uint64(chanID)
1973
                        if _, ok := edgesSeen[chanIDInt]; ok {
1974
                                continue
1975
                        }
1976

1977
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
1978
                                hits++
1979
                                edgesSeen[chanIDInt] = struct{}{}
1980
                                edgesInHorizon = append(edgesInHorizon, channel)
1981

1982
                                continue
3✔
1983
                        }
3✔
1984

3✔
1985
                        // First, we'll fetch the static edge information.
3✔
1986
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
1987
                        if err != nil {
3✔
1988
                                chanID := byteOrder.Uint64(chanID)
3✔
1989
                                return fmt.Errorf("unable to fetch info for "+
3✔
1990
                                        "edge with chan_id=%v: %v", chanID, err)
3✔
1991
                        }
3✔
1992

3✔
1993
                        // With the static information obtained, we'll now
3✔
1994
                        // fetch the dynamic policy info.
3✔
1995
                        edge1, edge2, err := fetchChanEdgePolicies(
6✔
1996
                                edgeIndex, edges, chanID,
3✔
1997
                        )
3✔
UNCOV
1998
                        if err != nil {
×
1999
                                chanID := byteOrder.Uint64(chanID)
×
2000
                                return fmt.Errorf("unable to fetch policies "+
3✔
2001
                                        "for edge with chan_id=%v: %v", chanID,
3✔
2002
                                        err)
×
2003
                        }
×
2004

3✔
2005
                        node1, err := fetchLightningNode(
3✔
UNCOV
2006
                                nodes, edgeInfo.NodeKey1Bytes[:],
×
UNCOV
2007
                        )
×
2008
                        if err != nil {
2009
                                return err
3✔
2010
                        }
3✔
UNCOV
2011

×
UNCOV
2012
                        node2, err := fetchLightningNode(
×
2013
                                nodes, edgeInfo.NodeKey2Bytes[:],
2014
                        )
2015
                        if err != nil {
2016
                                return err
3✔
2017
                        }
3✔
2018

3✔
2019
                        // Finally, we'll collate this edge with the rest of
3✔
2020
                        // edges to be returned.
3✔
2021
                        edgesSeen[chanIDInt] = struct{}{}
3✔
2022
                        channel := ChannelEdge{
3✔
2023
                                Info:    &edgeInfo,
3✔
2024
                                Policy1: edge1,
3✔
2025
                                Policy2: edge2,
3✔
2026
                                Node1:   &node1,
3✔
2027
                                Node2:   &node2,
3✔
2028
                        }
3✔
2029
                        edgesInHorizon = append(edgesInHorizon, channel)
3✔
2030
                        edgesToCache[chanIDInt] = channel
3✔
2031
                }
3✔
2032

6✔
2033
                return nil
3✔
2034
        }, func() {
3✔
2035
                edgesSeen = make(map[uint64]struct{})
3✔
2036
                edgesToCache = make(map[uint64]ChannelEdge)
3✔
2037
                edgesInHorizon = nil
3✔
2038
        })
3✔
2039
        switch {
3✔
2040
        case errors.Is(err, ErrGraphNoEdgesFound):
3✔
2041
                fallthrough
3✔
2042
        case errors.Is(err, ErrGraphNodesNotFound):
×
2043
                break
2044

2045
        case err != nil:
6✔
2046
                return nil, err
3✔
2047
        }
3✔
2048

3✔
2049
        // Insert any edges loaded from disk into the cache.
3✔
2050
        for chanid, channel := range edgesToCache {
3✔
2051
                c.chanCache.insert(chanid, channel)
2052
        }
2053

2054
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
3✔
2055
                float64(hits)/float64(len(edgesInHorizon)), hits,
3✔
UNCOV
2056
                len(edgesInHorizon))
×
UNCOV
2057

×
UNCOV
2058
        return edgesInHorizon, nil
×
UNCOV
2059
}
×
2060

2061
// NodeUpdatesInHorizon returns all the known lightning node which have an
2062
// update timestamp within the passed range. This method can be used by two
2063
// nodes to quickly determine if they have the same set of up to date node
3✔
2064
// announcements.
3✔
2065
func (c *KVStore) NodeUpdatesInHorizon(startTime,
3✔
2066
        endTime time.Time) ([]models.LightningNode, error) {
3✔
UNCOV
2067

×
UNCOV
2068
        var nodesInHorizon []models.LightningNode
×
UNCOV
2069

×
UNCOV
2070
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
2071
                nodes := tx.ReadBucket(nodeBucket)
×
2072
                if nodes == nil {
2073
                        return ErrGraphNodesNotFound
3✔
2074
                }
3✔
2075

3✔
2076
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
3✔
UNCOV
2077
                if nodeUpdateIndex == nil {
×
2078
                        return ErrGraphNodesNotFound
×
2079
                }
2080

3✔
2081
                // We'll now obtain a cursor to perform a range query within
3✔
2082
                // the index to find all node announcements within the horizon.
3✔
2083
                updateCursor := nodeUpdateIndex.ReadCursor()
3✔
UNCOV
2084

×
UNCOV
2085
                var startTimeBytes, endTimeBytes [8 + 33]byte
×
2086
                byteOrder.PutUint64(
2087
                        startTimeBytes[:8], uint64(startTime.Unix()),
2088
                )
2089
                byteOrder.PutUint64(
3✔
2090
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2091
                )
3✔
2092

3✔
2093
                // With our start and end times constructed, we'll step through
3✔
2094
                // the index collecting info for each node within the time
3✔
2095
                // range.
3✔
2096
                //
3✔
2097
                //nolint:ll
3✔
2098
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2099
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
2100
                        nodePub := indexKey[8:]
2101
                        node, err := fetchLightningNode(nodes, nodePub)
3✔
2102
                        if err != nil {
3✔
2103
                                return err
3✔
2104
                        }
3✔
2105

3✔
2106
                        nodesInHorizon = append(nodesInHorizon, node)
3✔
2107
                }
3✔
UNCOV
2108

×
UNCOV
2109
                return nil
×
UNCOV
2110
        }, func() {
×
UNCOV
2111
                nodesInHorizon = nil
×
2112
        })
UNCOV
2113
        switch {
×
2114
        case errors.Is(err, ErrGraphNoEdgesFound):
×
2115
                fallthrough
2116
        case errors.Is(err, ErrGraphNodesNotFound):
2117
                break
2118

6✔
2119
        case err != nil:
3✔
2120
                return nil, err
3✔
2121
        }
2122

3✔
2123
        return nodesInHorizon, nil
3✔
2124
}
3✔
2125

3✔
2126
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
3✔
2127
// ID's that we don't know and are not known zombies of the passed set. In other
2128
// words, we perform a set difference of our set of chan ID's and the ones
2129
// passed in. This method can be used by callers to determine the set of
2130
// channels another peer knows of that we don't. The ChannelUpdateInfos for the
2131
// known zombies is also returned.
2132
func (c *KVStore) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo) ([]uint64,
2133
        []ChannelUpdateInfo, error) {
2134

3✔
2135
        var (
3✔
2136
                newChanIDs   []uint64
3✔
2137
                knownZombies []ChannelUpdateInfo
3✔
2138
        )
6✔
2139

3✔
2140
        c.cacheMu.Lock()
3✔
UNCOV
2141
        defer c.cacheMu.Unlock()
×
UNCOV
2142

×
2143
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
2144
                edges := tx.ReadBucket(edgeBucket)
3✔
2145
                if edges == nil {
3✔
2146
                        return ErrGraphNoEdgesFound
×
2147
                }
×
2148
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
2149
                if edgeIndex == nil {
2150
                        return ErrGraphNoEdgesFound
2151
                }
3✔
2152

3✔
2153
                // Fetch the zombie index, it may not exist if no edges have
3✔
2154
                // ever been marked as zombies. If the index has been
3✔
2155
                // initialized, we will use it later to skip known zombie edges.
3✔
2156
                zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
2157

3✔
2158
                // We'll run through the set of chanIDs and collate only the
3✔
2159
                // set of channel that are unable to be found within our db.
3✔
2160
                var cidBytes [8]byte
3✔
2161
                for _, info := range chansInfo {
3✔
2162
                        scid := info.ShortChannelID.ToUint64()
3✔
2163
                        byteOrder.PutUint64(cidBytes[:], scid)
3✔
2164

3✔
2165
                        // If the edge is already known, skip it.
3✔
2166
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
3✔
2167
                                continue
6✔
2168
                        }
3✔
2169

3✔
2170
                        // If the edge is a known zombie, skip it.
3✔
UNCOV
2171
                        if zombieIndex != nil {
×
UNCOV
2172
                                isZombie, _, _ := isZombieEdge(
×
2173
                                        zombieIndex, scid,
2174
                                )
3✔
2175

2176
                                if isZombie {
2177
                                        knownZombies = append(
3✔
2178
                                                knownZombies, info,
3✔
2179
                                        )
3✔
2180

3✔
2181
                                        continue
3✔
UNCOV
2182
                                }
×
UNCOV
2183
                        }
×
UNCOV
2184

×
UNCOV
2185
                        newChanIDs = append(newChanIDs, scid)
×
2186
                }
UNCOV
2187

×
UNCOV
2188
                return nil
×
2189
        }, func() {
2190
                newChanIDs = nil
2191
                knownZombies = nil
3✔
2192
        })
2193
        switch {
2194
        // If we don't know of any edges yet, then we'll return the entire set
2195
        // of chan IDs specified.
2196
        case errors.Is(err, ErrGraphNoEdgesFound):
2197
                ogChanIDs := make([]uint64, len(chansInfo))
2198
                for i, info := range chansInfo {
2199
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
2200
                }
2201

3✔
2202
                return ogChanIDs, nil, nil
3✔
2203

3✔
2204
        case err != nil:
3✔
2205
                return nil, nil, err
3✔
2206
        }
3✔
2207

3✔
2208
        return newChanIDs, knownZombies, nil
3✔
2209
}
3✔
2210

3✔
2211
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
6✔
2212
// latest received channel updates for the channel.
3✔
2213
type ChannelUpdateInfo struct {
3✔
UNCOV
2214
        // ShortChannelID is the SCID identifier of the channel.
×
UNCOV
2215
        ShortChannelID lnwire.ShortChannelID
×
2216

3✔
2217
        // Node1UpdateTimestamp is the timestamp of the latest received update
3✔
UNCOV
2218
        // from the node 1 channel peer. This will be set to zero time if no
×
UNCOV
2219
        // update has yet been received from this node.
×
2220
        Node1UpdateTimestamp time.Time
2221

2222
        // Node2UpdateTimestamp is the timestamp of the latest received update
2223
        // from the node 2 channel peer. This will be set to zero time if no
2224
        // update has yet been received from this node.
3✔
2225
        Node2UpdateTimestamp time.Time
3✔
2226
}
3✔
2227

3✔
2228
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
3✔
2229
// timestamps with zero seconds unix timestamp which equals
6✔
2230
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
3✔
2231
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
3✔
2232
        node2Timestamp time.Time) ChannelUpdateInfo {
3✔
2233

3✔
2234
        chanInfo := ChannelUpdateInfo{
6✔
2235
                ShortChannelID:       scid,
3✔
2236
                Node1UpdateTimestamp: node1Timestamp,
2237
                Node2UpdateTimestamp: node2Timestamp,
2238
        }
2239

6✔
2240
        if node1Timestamp.IsZero() {
3✔
2241
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
3✔
2242
        }
3✔
2243

3✔
2244
        if node2Timestamp.IsZero() {
3✔
UNCOV
2245
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
×
UNCOV
2246
        }
×
UNCOV
2247

×
UNCOV
2248
        return chanInfo
×
UNCOV
2249
}
×
2250

2251
// BlockChannelRange represents a range of channels for a given block height.
2252
type BlockChannelRange struct {
2253
        // Height is the height of the block all of the channels below were
3✔
2254
        // included in.
2255
        Height uint32
2256

3✔
2257
        // Channels is the list of channels identified by their short ID
3✔
2258
        // representation known to us that were included in the block height
3✔
2259
        // above. The list may include channel update timestamp information if
3✔
2260
        // requested.
3✔
2261
        Channels []ChannelUpdateInfo
3✔
2262
}
2263

UNCOV
2264
// FilterChannelRange returns the channel ID's of all known channels which were
×
UNCOV
2265
// mined in a block height within the passed range. The channel IDs are grouped
×
UNCOV
2266
// by their common block height. This method can be used to quickly share with a
×
UNCOV
2267
// peer the set of channels we know of within a particular range to catch them
×
UNCOV
2268
// up after a period of time offline. If withTimestamps is true then the
×
2269
// timestamp info of the latest received channel update messages of the channel
UNCOV
2270
// will be included in the response.
×
2271
func (c *KVStore) FilterChannelRange(startHeight,
UNCOV
2272
        endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error) {
×
UNCOV
2273

×
2274
        startChanID := &lnwire.ShortChannelID{
2275
                BlockHeight: startHeight,
2276
        }
3✔
2277

2278
        endChanID := lnwire.ShortChannelID{
2279
                BlockHeight: endHeight,
2280
                TxIndex:     math.MaxUint32 & 0x00ffffff,
2281
                TxPosition:  math.MaxUint16,
2282
        }
2283

2284
        // As we need to perform a range scan, we'll convert the starting and
2285
        // ending height to their corresponding values when encoded using short
2286
        // channel ID's.
2287
        var chanIDStart, chanIDEnd [8]byte
2288
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
2289
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
2290

2291
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
2292
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
2293
                edges := tx.ReadBucket(edgeBucket)
2294
                if edges == nil {
2295
                        return ErrGraphNoEdgesFound
2296
                }
2297
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
2298
                if edgeIndex == nil {
2299
                        return ErrGraphNoEdgesFound
2300
                }
3✔
2301

3✔
2302
                cursor := edgeIndex.ReadCursor()
3✔
2303

3✔
2304
                // We'll now iterate through the database, and find each
3✔
2305
                // channel ID that resides within the specified range.
3✔
2306
                //
3✔
2307
                //nolint:ll
3✔
2308
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
6✔
2309
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
3✔
2310
                        // Don't send alias SCIDs during gossip sync.
3✔
2311
                        edgeReader := bytes.NewReader(v)
2312
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
6✔
2313
                        if err != nil {
3✔
2314
                                return err
3✔
2315
                        }
2316

3✔
2317
                        if edgeInfo.AuthProof == nil {
2318
                                continue
2319
                        }
2320

2321
                        // This channel ID rests within the target range, so
2322
                        // we'll add it to our returned set.
2323
                        rawCid := byteOrder.Uint64(k)
2324
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
2325

2326
                        chanInfo := NewChannelUpdateInfo(
2327
                                cid, time.Time{}, time.Time{},
2328
                        )
2329

2330
                        if !withTimestamps {
2331
                                channelsPerBlock[cid.BlockHeight] = append(
2332
                                        channelsPerBlock[cid.BlockHeight],
2333
                                        chanInfo,
2334
                                )
2335

2336
                                continue
2337
                        }
2338

2339
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
2340

3✔
2341
                        rawPolicy := edges.Get(node1Key)
3✔
2342
                        if len(rawPolicy) != 0 {
3✔
2343
                                r := bytes.NewReader(rawPolicy)
3✔
2344

3✔
2345
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2346
                                if err != nil && !errors.Is(
3✔
2347
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2348
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
2349

3✔
2350
                                        return err
3✔
2351
                                }
3✔
2352

3✔
2353
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
3✔
2354
                        }
3✔
2355

3✔
2356
                        rawPolicy = edges.Get(node2Key)
3✔
2357
                        if len(rawPolicy) != 0 {
3✔
2358
                                r := bytes.NewReader(rawPolicy)
3✔
2359

3✔
2360
                                edge, err := deserializeChanEdgePolicyRaw(r)
6✔
2361
                                if err != nil && !errors.Is(
3✔
2362
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
UNCOV
2363
                                ) && !errors.Is(err, ErrParsingExtraTLVBytes) {
×
2364

×
2365
                                        return err
3✔
2366
                                }
3✔
UNCOV
2367

×
UNCOV
2368
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
×
2369
                        }
2370

3✔
2371
                        channelsPerBlock[cid.BlockHeight] = append(
3✔
2372
                                channelsPerBlock[cid.BlockHeight], chanInfo,
3✔
2373
                        )
3✔
2374
                }
3✔
2375

3✔
2376
                return nil
3✔
2377
        }, func() {
6✔
2378
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
3✔
2379
        })
3✔
2380

3✔
2381
        switch {
3✔
UNCOV
2382
        // If we don't know of any channels yet, then there's nothing to
×
UNCOV
2383
        // filter, so we'll return an empty slice.
×
2384
        case errors.Is(err, ErrGraphNoEdgesFound) || len(channelsPerBlock) == 0:
2385
                return nil, nil
6✔
2386

3✔
2387
        case err != nil:
2388
                return nil, err
2389
        }
2390

2391
        // Return the channel ranges in ascending block height order.
3✔
2392
        blocks := make([]uint32, 0, len(channelsPerBlock))
3✔
2393
        for block := range channelsPerBlock {
3✔
2394
                blocks = append(blocks, block)
3✔
2395
        }
3✔
2396
        sort.Slice(blocks, func(i, j int) bool {
3✔
2397
                return blocks[i] < blocks[j]
3✔
2398
        })
3✔
UNCOV
2399

×
UNCOV
2400
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
×
UNCOV
2401
        for _, block := range blocks {
×
UNCOV
2402
                channelRanges = append(channelRanges, BlockChannelRange{
×
UNCOV
2403
                        Height:   block,
×
UNCOV
2404
                        Channels: channelsPerBlock[block],
×
2405
                })
2406
        }
2407

3✔
2408
        return channelRanges, nil
3✔
2409
}
3✔
2410

6✔
2411
// FetchChanInfos returns the set of channel edges that correspond to the passed
3✔
2412
// channel ID's. If an edge is the query is unknown to the database, it will
3✔
2413
// skipped and the result will contain only those edges that exist at the time
3✔
2414
// of the query. This can be used to respond to peer queries that are seeking to
3✔
2415
// fill in gaps in their view of the channel graph.
3✔
2416
func (c *KVStore) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
3✔
UNCOV
2417
        return c.fetchChanInfos(nil, chanIDs)
×
UNCOV
2418
}
×
UNCOV
2419

×
2420
// fetchChanInfos returns the set of channel edges that correspond to the passed
2421
// channel ID's. If an edge is the query is unknown to the database, it will
3✔
2422
// skipped and the result will contain only those edges that exist at the time
2423
// of the query. This can be used to respond to peer queries that are seeking to
2424
// fill in gaps in their view of the channel graph.
3✔
2425
//
6✔
2426
// NOTE: An optional transaction may be provided. If none is provided, then a
3✔
2427
// new one will be created.
3✔
2428
func (c *KVStore) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
3✔
2429
        []ChannelEdge, error) {
3✔
2430
        // TODO(roasbeef): sort cids?
3✔
2431

3✔
UNCOV
2432
        var (
×
UNCOV
2433
                chanEdges []ChannelEdge
×
UNCOV
2434
                cidBytes  [8]byte
×
2435
        )
2436

3✔
2437
        fetchChanInfos := func(tx kvdb.RTx) error {
2438
                edges := tx.ReadBucket(edgeBucket)
2439
                if edges == nil {
3✔
2440
                        return ErrGraphNoEdgesFound
3✔
2441
                }
3✔
2442
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
2443
                if edgeIndex == nil {
2444
                        return ErrGraphNoEdgesFound
3✔
2445
                }
3✔
2446
                nodes := tx.ReadBucket(nodeBucket)
3✔
2447
                if nodes == nil {
3✔
2448
                        return ErrGraphNotFound
2449
                }
3✔
2450

2451
                for _, cid := range chanIDs {
2452
                        byteOrder.PutUint64(cidBytes[:], cid)
3✔
2453

3✔
2454
                        // First, we'll fetch the static edge information. If
UNCOV
2455
                        // the edge is unknown, we will skip the edge and
×
UNCOV
2456
                        // continue gathering all known edges.
×
2457
                        edgeInfo, err := fetchChanEdgeInfo(
2458
                                edgeIndex, cidBytes[:],
2459
                        )
2460
                        switch {
3✔
2461
                        case errors.Is(err, ErrEdgeNotFound):
6✔
2462
                                continue
3✔
2463
                        case err != nil:
3✔
2464
                                return err
6✔
2465
                        }
3✔
2466

3✔
2467
                        // With the static information obtained, we'll now
2468
                        // fetch the dynamic policy info.
3✔
2469
                        edge1, edge2, err := fetchChanEdgePolicies(
6✔
2470
                                edgeIndex, edges, cidBytes[:],
3✔
2471
                        )
3✔
2472
                        if err != nil {
3✔
2473
                                return err
3✔
2474
                        }
3✔
2475

2476
                        node1, err := fetchLightningNode(
3✔
2477
                                nodes, edgeInfo.NodeKey1Bytes[:],
2478
                        )
2479
                        if err != nil {
2480
                                return err
2481
                        }
2482

2483
                        node2, err := fetchLightningNode(
2484
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2485
                        )
3✔
2486
                        if err != nil {
3✔
2487
                                return err
2488
                        }
2489

2490
                        chanEdges = append(chanEdges, ChannelEdge{
2491
                                Info:    &edgeInfo,
2492
                                Policy1: edge1,
2493
                                Policy2: edge2,
2494
                                Node1:   &node1,
2495
                                Node2:   &node2,
2496
                        })
2497
                }
3✔
2498

3✔
2499
                return nil
3✔
2500
        }
3✔
2501

3✔
2502
        if tx == nil {
3✔
2503
                err := kvdb.View(c.db, fetchChanInfos, func() {
3✔
2504
                        chanEdges = nil
3✔
2505
                })
6✔
2506
                if err != nil {
3✔
2507
                        return nil, err
3✔
2508
                }
×
UNCOV
2509

×
2510
                return chanEdges, nil
3✔
2511
        }
3✔
UNCOV
2512

×
2513
        err := fetchChanInfos(tx)
×
2514
        if err != nil {
3✔
2515
                return nil, err
3✔
2516
        }
×
UNCOV
2517

×
2518
        return chanEdges, nil
2519
}
6✔
2520

3✔
2521
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
3✔
2522
        edge1, edge2 *models.ChannelEdgePolicy) error {
3✔
2523

3✔
2524
        // First, we'll fetch the edge update index bucket which currently
3✔
2525
        // stores an entry for the channel we're about to delete.
3✔
2526
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
3✔
2527
        if updateIndex == nil {
3✔
2528
                // No edges in bucket, return early.
3✔
2529
                return nil
×
2530
        }
×
UNCOV
2531

×
UNCOV
2532
        // Now that we have the bucket, we'll attempt to construct a template
×
2533
        // for the index key: updateTime || chanid.
2534
        var indexKey [8 + 8]byte
2535
        byteOrder.PutUint64(indexKey[8:], chanID)
2536

2537
        // With the template constructed, we'll attempt to delete an entry that
3✔
2538
        // would have been created by both edges: we'll alternate the update
3✔
2539
        // times, as one may had overridden the other.
3✔
2540
        if edge1 != nil {
3✔
UNCOV
2541
                byteOrder.PutUint64(
×
UNCOV
2542
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
×
2543
                )
2544
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2545
                        return err
3✔
2546
                }
3✔
2547
        }
3✔
UNCOV
2548

×
UNCOV
2549
        // We'll also attempt to delete the entry that may have been created by
×
2550
        // the second edge.
2551
        if edge2 != nil {
3✔
2552
                byteOrder.PutUint64(
3✔
2553
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
3✔
2554
                )
3✔
UNCOV
2555
                if err := updateIndex.Delete(indexKey[:]); err != nil {
×
2556
                        return err
×
2557
                }
2558
        }
3✔
2559

3✔
2560
        return nil
3✔
2561
}
3✔
2562

3✔
2563
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
3✔
2564
// cache. It then goes on to delete any policy info and edge info for this
3✔
2565
// channel from the DB and finally, if isZombie is true, it will add an entry
2566
// for this channel in the zombie index.
2567
//
3✔
2568
// NOTE: this method MUST only be called if the cacheMu has already been
2569
// acquired.
2570
func (c *KVStore) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
6✔
2571
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
6✔
2572
        strictZombie bool) (*models.ChannelEdgeInfo, error) {
3✔
2573

3✔
2574
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
UNCOV
2575
        if err != nil {
×
2576
                return nil, err
×
2577
        }
2578

3✔
2579
        // We'll also remove the entry in the edge update index bucket before
2580
        // we delete the edges themselves so we can access their last update
UNCOV
2581
        // times.
×
UNCOV
2582
        cid := byteOrder.Uint64(chanID)
×
UNCOV
2583
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
×
UNCOV
2584
        if err != nil {
×
2585
                return nil, err
2586
        }
×
2587
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
2588
        if err != nil {
2589
                return nil, err
2590
        }
3✔
2591

3✔
2592
        // The edge key is of the format pubKey || chanID. First we construct
3✔
2593
        // the latter half, populating the channel ID.
3✔
2594
        var edgeKey [33 + 8]byte
3✔
2595
        copy(edgeKey[33:], chanID)
3✔
UNCOV
2596

×
UNCOV
2597
        // With the latter half constructed, copy over the first public key to
×
UNCOV
2598
        // delete the edge in this direction, then the second to delete the
×
2599
        // edge in the opposite direction.
2600
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
2601
        if edges.Get(edgeKey[:]) != nil {
2602
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2603
                        return nil, err
3✔
2604
                }
3✔
2605
        }
3✔
2606
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
3✔
2607
        if edges.Get(edgeKey[:]) != nil {
3✔
2608
                if err := edges.Delete(edgeKey[:]); err != nil {
6✔
2609
                        return nil, err
3✔
2610
                }
3✔
2611
        }
3✔
2612

3✔
UNCOV
2613
        // As part of deleting the edge we also remove all disabled entries
×
UNCOV
2614
        // from the edgePolicyDisabledIndex bucket. We do that for both
×
2615
        // directions.
2616
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
2617
        if err != nil {
2618
                return nil, err
2619
        }
6✔
2620
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
3✔
2621
        if err != nil {
3✔
2622
                return nil, err
3✔
2623
        }
3✔
UNCOV
2624

×
UNCOV
2625
        // With the edge data deleted, we can purge the information from the two
×
2626
        // edge indexes.
2627
        if err := edgeIndex.Delete(chanID); err != nil {
2628
                return nil, err
3✔
2629
        }
2630
        var b bytes.Buffer
2631
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
2632
                return nil, err
2633
        }
2634
        if err := chanIndex.Delete(b.Bytes()); err != nil {
2635
                return nil, err
2636
        }
2637

2638
        // Finally, we'll mark the edge as a zombie within our index if it's
2639
        // being removed due to the channel becoming a zombie. We do this to
2640
        // ensure we don't store unnecessary data for spent channels.
3✔
2641
        if !isZombie {
3✔
2642
                return &edgeInfo, nil
3✔
2643
        }
3✔
UNCOV
2644

×
UNCOV
2645
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
×
2646
        if strictZombie {
2647
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
2648
        }
2649

2650
        return &edgeInfo, markEdgeZombie(
3✔
2651
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
3✔
2652
        )
3✔
UNCOV
2653
}
×
UNCOV
2654

×
2655
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
3✔
2656
// particular pair of channel policies. The return values are one of:
3✔
UNCOV
2657
//  1. (pubkey1, pubkey2)
×
UNCOV
2658
//  2. (pubkey1, blank)
×
2659
//  3. (blank, pubkey2)
2660
//
2661
// A blank pubkey means that corresponding node will be unable to resurrect a
2662
// channel on its own. For example, node1 may continue to publish recent
3✔
2663
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
3✔
2664
// we don't want another fresh update from node1 to resurrect, as the edge can
3✔
2665
// only become live once node2 finally sends something recent.
3✔
2666
//
3✔
2667
// In the case where we have neither update, we allow either party to resurrect
3✔
2668
// the channel. If the channel were to be marked zombie again, it would be
3✔
2669
// marked with the correct lagging channel since we received an update from only
6✔
2670
// one side.
3✔
UNCOV
2671
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
×
2672
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
×
2673

2674
        switch {
3✔
2675
        // If we don't have either edge policy, we'll return both pubkeys so
6✔
2676
        // that the channel can be resurrected by either party.
3✔
2677
        case e1 == nil && e2 == nil:
×
2678
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2679

2680
        // If we're missing edge1, or if both edges are present but edge1 is
2681
        // older, we'll return edge1's pubkey and a blank pubkey for edge2. This
2682
        // means that only an update from edge1 will be able to resurrect the
2683
        // channel.
2684
        case e1 == nil || (e2 != nil && e1.LastUpdate.Before(e2.LastUpdate)):
3✔
2685
                return info.NodeKey1Bytes, [33]byte{}
3✔
UNCOV
2686

×
UNCOV
2687
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
×
2688
        // return a blank pubkey for edge1. In this case, only an update from
3✔
2689
        // edge2 can resurect the channel.
3✔
2690
        default:
×
2691
                return [33]byte{}, info.NodeKey2Bytes
×
2692
        }
2693
}
2694

2695
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
3✔
UNCOV
2696
// within the database for the referenced channel. The `flags` attribute within
×
UNCOV
2697
// the ChannelEdgePolicy determines which of the directed edges are being
×
2698
// updated. If the flag is 1, then the first node's information is being
3✔
2699
// updated, otherwise it's the second node's information. The node ordering is
3✔
UNCOV
2700
// determined by the lexicographical ordering of the identity public keys of the
×
UNCOV
2701
// nodes on either side of the channel.
×
2702
func (c *KVStore) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
3✔
UNCOV
2703
        opts ...batch.SchedulerOption) (route.Vertex, route.Vertex, error) {
×
UNCOV
2704

×
2705
        var (
2706
                ctx          = context.TODO()
2707
                isUpdate1    bool
2708
                edgeNotFound bool
2709
                from, to     route.Vertex
6✔
2710
        )
3✔
2711

3✔
2712
        r := &batch.Request[kvdb.RwTx]{
2713
                Opts: batch.NewSchedulerOptions(opts...),
3✔
2714
                Reset: func() {
3✔
UNCOV
2715
                        isUpdate1 = false
×
UNCOV
2716
                        edgeNotFound = false
×
2717
                },
2718
                Do: func(tx kvdb.RwTx) error {
3✔
2719
                        var err error
3✔
2720
                        from, to, isUpdate1, err = updateEdgePolicy(tx, edge)
3✔
2721
                        if err != nil {
2722
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
2723
                        }
2724

2725
                        // Silence ErrEdgeNotFound so that the batch can
2726
                        // succeed, but propagate the error via local state.
2727
                        if errors.Is(err, ErrEdgeNotFound) {
2728
                                edgeNotFound = true
2729
                                return nil
2730
                        }
2731

2732
                        return err
2733
                },
2734
                OnCommit: func(err error) error {
2735
                        switch {
2736
                        case err != nil:
2737
                                return err
2738
                        case edgeNotFound:
2739
                                return ErrEdgeNotFound
UNCOV
2740
                        default:
×
UNCOV
2741
                                c.updateEdgeCache(edge, isUpdate1)
×
UNCOV
2742
                                return nil
×
2743
                        }
2744
                },
UNCOV
2745
        }
×
UNCOV
2746

×
2747
        err := c.chanScheduler.Execute(ctx, r)
2748

2749
        return from, to, err
2750
}
2751

UNCOV
2752
func (c *KVStore) updateEdgeCache(e *models.ChannelEdgePolicy,
×
UNCOV
2753
        isUpdate1 bool) {
×
2754

2755
        // If an entry for this channel is found in reject cache, we'll modify
2756
        // the entry with the updated timestamp for the direction that was just
2757
        // written. If the edge doesn't exist, we'll load the cache entry lazily
UNCOV
2758
        // during the next query for this edge.
×
UNCOV
2759
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
×
2760
                if isUpdate1 {
2761
                        entry.upd1Time = e.LastUpdate.Unix()
2762
                } else {
2763
                        entry.upd2Time = e.LastUpdate.Unix()
2764
                }
2765
                c.rejectCache.insert(e.ChannelID, entry)
2766
        }
2767

2768
        // If an entry for this channel is found in channel cache, we'll modify
2769
        // the entry with the updated policy for the direction that was just
2770
        // written. If the edge doesn't exist, we'll defer loading the info and
2771
        // policies and lazily read from disk during the next query.
3✔
2772
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
3✔
2773
                if isUpdate1 {
3✔
2774
                        channel.Policy1 = e
3✔
2775
                } else {
3✔
2776
                        channel.Policy2 = e
3✔
2777
                }
3✔
2778
                c.chanCache.insert(e.ChannelID, channel)
3✔
2779
        }
3✔
2780
}
3✔
2781

3✔
2782
// updateEdgePolicy attempts to update an edge's policy within the relevant
6✔
2783
// buckets using an existing database transaction. The returned boolean will be
3✔
2784
// true if the updated policy belongs to node1, and false if the policy belonged
3✔
2785
// to node2.
3✔
2786
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy) (
3✔
2787
        route.Vertex, route.Vertex, bool, error) {
3✔
2788

3✔
2789
        var noVertex route.Vertex
3✔
UNCOV
2790

×
UNCOV
2791
        edges := tx.ReadWriteBucket(edgeBucket)
×
2792
        if edges == nil {
2793
                return noVertex, noVertex, false, ErrEdgeNotFound
2794
        }
2795
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
UNCOV
2796
        if edgeIndex == nil {
×
2797
                return noVertex, noVertex, false, ErrEdgeNotFound
×
2798
        }
×
2799

2800
        // Create the channelID key be converting the channel ID
3✔
2801
        // integer into a byte slice.
2802
        var chanID [8]byte
3✔
2803
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
3✔
UNCOV
2804

×
UNCOV
2805
        // With the channel ID, we then fetch the value storing the two
×
UNCOV
2806
        // nodes which connect this channel edge.
×
UNCOV
2807
        nodeInfo := edgeIndex.Get(chanID[:])
×
2808
        if nodeInfo == nil {
3✔
2809
                return noVertex, noVertex, false, ErrEdgeNotFound
3✔
2810
        }
3✔
2811

2812
        // Depending on the flags value passed above, either the first
2813
        // or second edge policy is being updated.
2814
        var fromNode, toNode []byte
2815
        var isUpdate1 bool
3✔
2816
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3✔
2817
                fromNode = nodeInfo[:33]
3✔
2818
                toNode = nodeInfo[33:66]
2819
                isUpdate1 = true
2820
        } else {
2821
                fromNode = nodeInfo[33:66]
3✔
2822
                toNode = nodeInfo[:33]
3✔
2823
                isUpdate1 = false
3✔
2824
        }
3✔
2825

3✔
2826
        // Finally, with the direction of the edge being updated
3✔
2827
        // identified, we update the on-disk edge representation.
6✔
2828
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
6✔
2829
        if err != nil {
3✔
2830
                return noVertex, noVertex, false, err
6✔
2831
        }
3✔
2832

3✔
2833
        var (
3✔
2834
                fromNodePubKey route.Vertex
2835
                toNodePubKey   route.Vertex
2836
        )
2837
        copy(fromNodePubKey[:], fromNode)
2838
        copy(toNodePubKey[:], toNode)
2839

2840
        return fromNodePubKey, toNodePubKey, isUpdate1, nil
6✔
2841
}
6✔
2842

3✔
2843
// isPublic determines whether the node is seen as public within the graph from
6✔
2844
// the source node's point of view. An existing database transaction can also be
3✔
2845
// specified.
3✔
2846
func (c *KVStore) isPublic(tx kvdb.RTx, nodePub route.Vertex,
3✔
2847
        sourcePubKey []byte) (bool, error) {
2848

2849
        // In order to determine whether this node is publicly advertised within
2850
        // the graph, we'll need to look at all of its edges and check whether
2851
        // they extend to any other node than the source node. errDone will be
2852
        // used to terminate the check early.
2853
        nodeIsPublic := false
2854
        errDone := errors.New("done")
2855
        err := c.forEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
3✔
2856
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
3✔
2857
                _ *models.ChannelEdgePolicy) error {
3✔
2858

3✔
2859
                // If this edge doesn't extend to the source node, we'll
3✔
2860
                // terminate our search as we can now conclude that the node is
3✔
UNCOV
2861
                // publicly advertised within the graph due to the local node
×
UNCOV
2862
                // knowing of the current edge.
×
2863
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
3✔
2864
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
3✔
UNCOV
2865

×
UNCOV
2866
                        nodeIsPublic = true
×
2867
                        return errDone
2868
                }
2869

2870
                // Since the edge _does_ extend to the source node, we'll also
3✔
2871
                // need to ensure that this is a public edge.
3✔
2872
                if info.AuthProof != nil {
3✔
2873
                        nodeIsPublic = true
3✔
2874
                        return errDone
3✔
2875
                }
3✔
2876

3✔
UNCOV
2877
                // Otherwise, we'll continue our search.
×
UNCOV
2878
                return nil
×
2879
        })
2880
        if err != nil && !errors.Is(err, errDone) {
2881
                return false, err
2882
        }
3✔
2883

3✔
2884
        return nodeIsPublic, nil
6✔
2885
}
3✔
2886

3✔
2887
// FetchLightningNodeTx attempts to look up a target node by its identity
3✔
2888
// public key. If the node isn't found in the database, then
6✔
2889
// ErrGraphNodeNotFound is returned. An optional transaction may be provided.
3✔
2890
// If none is provided, then a new one will be created.
3✔
2891
func (c *KVStore) FetchLightningNodeTx(tx kvdb.RTx, nodePub route.Vertex) (
3✔
2892
        *models.LightningNode, error) {
3✔
2893

2894
        return c.fetchLightningNode(tx, nodePub)
2895
}
2896

3✔
2897
// FetchLightningNode attempts to look up a target node by its identity public
3✔
UNCOV
2898
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
×
UNCOV
2899
// returned.
×
2900
func (c *KVStore) FetchLightningNode(nodePub route.Vertex) (
2901
        *models.LightningNode, error) {
3✔
2902

3✔
2903
        return c.fetchLightningNode(nil, nodePub)
3✔
2904
}
3✔
2905

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

2913
        var node *models.LightningNode
2914
        fetch := func(tx kvdb.RTx) error {
2915
                // First grab the nodes bucket which stores the mapping from
3✔
2916
                // pubKey to node information.
3✔
2917
                nodes := tx.ReadBucket(nodeBucket)
3✔
2918
                if nodes == nil {
3✔
2919
                        return ErrGraphNotFound
3✔
2920
                }
3✔
2921

3✔
2922
                // If a key for this serialized public key isn't found, then
3✔
2923
                // the target node doesn't exist within the database.
3✔
2924
                nodeBytes := nodes.Get(nodePub[:])
3✔
2925
                if nodeBytes == nil {
6✔
2926
                        return ErrGraphNodeNotFound
3✔
2927
                }
3✔
2928

3✔
2929
                // If the node is found, then we can de deserialize the node
3✔
2930
                // information to return to the user.
3✔
2931
                nodeReader := bytes.NewReader(nodeBytes)
3✔
2932
                n, err := deserializeLightningNode(nodeReader)
6✔
2933
                if err != nil {
3✔
2934
                        return err
3✔
2935
                }
3✔
2936

3✔
2937
                node = &n
2938

2939
                return nil
2940
        }
6✔
2941

3✔
2942
        if tx == nil {
3✔
2943
                err := kvdb.View(
3✔
2944
                        c.db, fetch, func() {
2945
                                node = nil
2946
                        },
3✔
2947
                )
2948
                if err != nil {
3✔
UNCOV
2949
                        return nil, err
×
UNCOV
2950
                }
×
2951

2952
                return node, nil
3✔
2953
        }
2954

2955
        err := fetch(tx)
2956
        if err != nil {
2957
                return nil, err
2958
        }
2959

2960
        return node, nil
3✔
2961
}
3✔
2962

3✔
2963
// HasLightningNode determines if the graph has a vertex identified by the
3✔
2964
// target node identity public key. If the node exists in the database, a
2965
// timestamp of when the data for the node was lasted updated is returned along
2966
// with a true boolean. Otherwise, an empty time.Time is returned with a false
2967
// boolean.
2968
func (c *KVStore) HasLightningNode(nodePub [33]byte) (time.Time, bool,
2969
        error) {
3✔
2970

3✔
2971
        var (
3✔
2972
                updateTime time.Time
3✔
2973
                exists     bool
2974
        )
2975

2976
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
2977
                // First grab the nodes bucket which stores the mapping from
2978
                // pubKey to node information.
2979
                nodes := tx.ReadBucket(nodeBucket)
3✔
2980
                if nodes == nil {
3✔
2981
                        return ErrGraphNotFound
3✔
2982
                }
6✔
2983

3✔
2984
                // If a key for this serialized public key isn't found, we can
3✔
2985
                // exit early.
3✔
2986
                nodeBytes := nodes.Get(nodePub[:])
3✔
UNCOV
2987
                if nodeBytes == nil {
×
UNCOV
2988
                        exists = false
×
2989
                        return nil
2990
                }
2991

2992
                // Otherwise we continue on to obtain the time stamp
3✔
2993
                // representing the last time the data for this node was
6✔
2994
                // updated.
3✔
2995
                nodeReader := bytes.NewReader(nodeBytes)
3✔
2996
                node, err := deserializeLightningNode(nodeReader)
2997
                if err != nil {
2998
                        return err
2999
                }
3✔
3000

3✔
3001
                exists = true
3✔
UNCOV
3002
                updateTime = node.LastUpdate
×
UNCOV
3003

×
3004
                return nil
3005
        }, func() {
3✔
3006
                updateTime = time.Time{}
3✔
3007
                exists = false
3✔
3008
        })
3009
        if err != nil {
3010
                return time.Time{}, exists, err
6✔
3011
        }
3✔
3012

6✔
3013
        return updateTime, exists, nil
3✔
3014
}
3✔
3015

3016
// nodeTraversal is used to traverse all channels of a node given by its
6✔
3017
// public key and passes channel information into the specified callback.
3✔
3018
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3✔
3019
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3020
                *models.ChannelEdgePolicy) error) error {
3✔
3021

3022
        traversal := func(tx kvdb.RTx) error {
UNCOV
3023
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3024
                if edges == nil {
×
3025
                        return ErrGraphNotFound
×
3026
                }
×
3027
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
UNCOV
3028
                if edgeIndex == nil {
×
3029
                        return ErrGraphNoEdgesFound
3030
                }
3031

3032
                // In order to reach all the edges for this node, we take
3033
                // advantage of the construction of the key-space within the
3034
                // edge bucket. The keys are stored in the form: pubKey ||
3035
                // chanID. Therefore, starting from a chanID of zero, we can
3036
                // scan forward in the bucket, grabbing all the edges for the
3037
                // node. Once the prefix no longer matches, then we know we're
3✔
3038
                // done.
3✔
3039
                var nodeStart [33 + 8]byte
3✔
3040
                copy(nodeStart[:], nodePub)
3✔
3041
                copy(nodeStart[33:], chanStart[:])
3✔
3042

3✔
3043
                // Starting from the key pubKey || 0, we seek forward in the
3✔
3044
                // bucket until the retrieved key no longer has the public key
6✔
3045
                // as its prefix. This indicates that we've stepped over into
3✔
3046
                // another node's edges, so we can terminate our scan.
3✔
3047
                edgeCursor := edges.ReadCursor()
3✔
3048
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
3✔
UNCOV
3049
                        // If the prefix still matches, the channel id is
×
UNCOV
3050
                        // returned in nodeEdge. Channel id is used to lookup
×
3051
                        // the node at the other end of the channel and both
3052
                        // edge policies.
3053
                        chanID := nodeEdge[33:]
3054
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3055
                        if err != nil {
6✔
3056
                                return err
3✔
3057
                        }
3✔
3058

3✔
3059
                        outgoingPolicy, err := fetchChanEdgePolicy(
3060
                                edges, chanID, nodePub,
3061
                        )
3062
                        if err != nil {
3063
                                return err
3✔
3064
                        }
3✔
3065

3✔
UNCOV
3066
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
×
UNCOV
3067
                        if err != nil {
×
3068
                                return err
3069
                        }
3✔
3070

3✔
3071
                        incomingPolicy, err := fetchChanEdgePolicy(
3✔
3072
                                edges, chanID, otherNode[:],
3✔
3073
                        )
3✔
3074
                        if err != nil {
3✔
3075
                                return err
3✔
3076
                        }
3✔
3077

3✔
UNCOV
3078
                        // Finally, we execute the callback.
×
UNCOV
3079
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
×
3080
                        if err != nil {
3081
                                return err
3✔
3082
                        }
3083
                }
3084

3085
                return nil
3086
        }
3087

3088
        // If no transaction was provided, then we'll create a new transaction
3✔
3089
        // to execute the transaction within.
3✔
3090
        if tx == nil {
6✔
3091
                return kvdb.View(db, traversal, func() {})
3✔
3092
        }
3✔
UNCOV
3093

×
UNCOV
3094
        // Otherwise, we re-use the existing transaction to execute the graph
×
3095
        // traversal.
3✔
3096
        return traversal(tx)
3✔
UNCOV
3097
}
×
UNCOV
3098

×
3099
// ForEachNodeChannel iterates through all channels of the given node,
3100
// executing the passed callback with an edge info structure and the policies
3101
// of each end of the channel. The first edge policy is the outgoing edge *to*
3102
// the connecting node, while the second is the incoming edge *from* the
3103
// connecting node. If the callback returns an error, then the iteration is
3104
// halted with the error propagated back up to the caller.
3105
//
3106
// Unknown policies are passed into the callback as nil values.
3107
func (c *KVStore) ForEachNodeChannel(nodePub route.Vertex,
3✔
3108
        cb func(*models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3✔
3109
                *models.ChannelEdgePolicy) error) error {
3✔
3110

3✔
3111
        return nodeTraversal(nil, nodePub[:], c.db, func(_ kvdb.RTx,
3✔
3112
                info *models.ChannelEdgeInfo, policy,
3✔
3113
                policy2 *models.ChannelEdgePolicy) error {
3✔
3114

3✔
3115
                return cb(info, policy, policy2)
3✔
3116
        })
6✔
3117
}
3✔
3118

3✔
3119
// ForEachSourceNodeChannel iterates through all channels of the source node,
3✔
3120
// executing the passed callback on each. The callback is provided with the
3✔
3121
// channel's outpoint, whether we have a policy for the channel and the channel
3✔
3122
// peer's node information.
3✔
3123
func (c *KVStore) ForEachSourceNodeChannel(cb func(chanPoint wire.OutPoint,
3✔
UNCOV
3124
        havePolicy bool, otherNode *models.LightningNode) error) error {
×
UNCOV
3125

×
3126
        return kvdb.View(c.db, func(tx kvdb.RTx) error {
3127
                nodes := tx.ReadBucket(nodeBucket)
3✔
3128
                if nodes == nil {
3✔
3129
                        return ErrGraphNotFound
3✔
3130
                }
3✔
UNCOV
3131

×
UNCOV
3132
                node, err := c.sourceNode(nodes)
×
3133
                if err != nil {
3134
                        return err
3✔
3135
                }
3✔
UNCOV
3136

×
UNCOV
3137
                return nodeTraversal(
×
3138
                        tx, node.PubKeyBytes[:], c.db, func(tx kvdb.RTx,
3139
                                info *models.ChannelEdgeInfo,
3✔
3140
                                policy, _ *models.ChannelEdgePolicy) error {
3✔
3141

3✔
3142
                                peer, err := c.fetchOtherNode(
3✔
UNCOV
3143
                                        tx, info, node.PubKeyBytes[:],
×
UNCOV
3144
                                )
×
3145
                                if err != nil {
3146
                                        return err
3147
                                }
3✔
3148

6✔
3149
                                return cb(
3✔
3150
                                        info.ChannelPoint, policy != nil, peer,
3✔
3151
                                )
3152
                        },
3153
                )
3✔
3154
        }, func() {})
3155
}
3156

3157
// forEachNodeChannelTx iterates through all channels of the given node,
3158
// executing the passed callback with an edge info structure and the policies
6✔
3159
// of each end of the channel. The first edge policy is the outgoing edge *to*
6✔
3160
// the connecting node, while the second is the incoming edge *from* the
3161
// connecting node. If the callback returns an error, then the iteration is
3162
// halted with the error propagated back up to the caller.
3163
//
3164
// Unknown policies are passed into the callback as nil values.
3✔
3165
//
3166
// If the caller wishes to re-use an existing boltdb transaction, then it
3167
// should be passed as the first argument.  Otherwise, the first argument should
3168
// be nil and a fresh transaction will be created to execute the graph
3169
// traversal.
3170
func (c *KVStore) forEachNodeChannelTx(tx kvdb.RTx,
3171
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3172
                *models.ChannelEdgePolicy,
3173
                *models.ChannelEdgePolicy) error) error {
3174

3175
        return nodeTraversal(tx, nodePub[:], c.db, cb)
3176
}
3177

3✔
3178
// fetchOtherNode attempts to fetch the full LightningNode that's opposite of
3✔
3179
// the target node in the channel. This is useful when one knows the pubkey of
3✔
3180
// one of the nodes, and wishes to obtain the full LightningNode for the other
3✔
3181
// end of the channel.
6✔
3182
func (c *KVStore) fetchOtherNode(tx kvdb.RTx,
3✔
3183
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3✔
3184
        *models.LightningNode, error) {
3✔
3185

3186
        // Ensure that the node passed in is actually a member of the channel.
3187
        var targetNodeBytes [33]byte
3188
        switch {
3189
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3190
                targetNodeBytes = channel.NodeKey2Bytes
3191
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3192
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3193
        default:
3✔
3194
                return nil, fmt.Errorf("node not participating in this channel")
6✔
3195
        }
3✔
3196

3✔
UNCOV
3197
        var targetNode *models.LightningNode
×
UNCOV
3198
        fetchNodeFunc := func(tx kvdb.RTx) error {
×
3199
                // First grab the nodes bucket which stores the mapping from
3200
                // pubKey to node information.
3✔
3201
                nodes := tx.ReadBucket(nodeBucket)
3✔
UNCOV
3202
                if nodes == nil {
×
3203
                        return ErrGraphNotFound
×
3204
                }
3205

3✔
3206
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3207
                if err != nil {
3✔
3208
                        return err
6✔
3209
                }
3✔
3210

3✔
3211
                targetNode = &node
3✔
3212

3✔
3213
                return nil
3✔
UNCOV
3214
        }
×
UNCOV
3215

×
3216
        // If the transaction is nil, then we'll need to create a new one,
3217
        // otherwise we can use the existing db transaction.
3✔
3218
        var err error
3✔
3219
        if tx == nil {
3✔
3220
                err = kvdb.View(c.db, fetchNodeFunc, func() {
3221
                        targetNode = nil
3222
                })
3✔
3223
        } else {
3224
                err = fetchNodeFunc(tx)
3225
        }
3226

3227
        return targetNode, err
3228
}
3229

3230
// computeEdgePolicyKeys is a helper function that can be used to compute the
3231
// keys used to index the channel edge policy info for the two nodes of the
3232
// edge. The keys for node 1 and node 2 are returned respectively.
3233
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
3234
        var (
3235
                node1Key [33 + 8]byte
3236
                node2Key [33 + 8]byte
3237
        )
3238

3239
        copy(node1Key[:], info.NodeKey1Bytes[:])
3240
        copy(node2Key[:], info.NodeKey2Bytes[:])
3241

3✔
3242
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
3✔
3243
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
3✔
3244

3✔
3245
        return node1Key[:], node2Key[:]
3246
}
3247

3248
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3249
// the channel identified by the funding outpoint. If the channel can't be
3250
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3251
// information for the channel itself is returned as well as two structs that
3252
// contain the routing policies for the channel in either direction.
3✔
3253
func (c *KVStore) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3✔
3254
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3✔
3255
        *models.ChannelEdgePolicy, error) {
3✔
3256

3✔
3257
        var (
3✔
3258
                edgeInfo *models.ChannelEdgeInfo
3✔
3259
                policy1  *models.ChannelEdgePolicy
3✔
3260
                policy2  *models.ChannelEdgePolicy
3✔
UNCOV
3261
        )
×
UNCOV
3262

×
3263
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
3264
                // First, grab the node bucket. This will be used to populate
3265
                // the Node pointers in each edge read from disk.
3✔
3266
                nodes := tx.ReadBucket(nodeBucket)
6✔
3267
                if nodes == nil {
3✔
3268
                        return ErrGraphNotFound
3✔
3269
                }
3✔
3270

3✔
UNCOV
3271
                // Next, grab the edge bucket which stores the edges, and also
×
UNCOV
3272
                // the index itself so we can group the directed edges together
×
3273
                // logically.
3274
                edges := tx.ReadBucket(edgeBucket)
3✔
3275
                if edges == nil {
3✔
3276
                        return ErrGraphNoEdgesFound
×
3277
                }
×
3278
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3279
                if edgeIndex == nil {
3✔
3280
                        return ErrGraphNoEdgesFound
3✔
3281
                }
3✔
3282

3283
                // If the channel's outpoint doesn't exist within the outpoint
3284
                // index, then the edge does not exist.
3285
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3286
                if chanIndex == nil {
3✔
3287
                        return ErrGraphNoEdgesFound
3✔
3288
                }
×
UNCOV
3289
                var b bytes.Buffer
×
UNCOV
3290
                if err := WriteOutpoint(&b, op); err != nil {
×
3291
                        return err
3✔
3292
                }
3✔
3293
                chanID := chanIndex.Get(b.Bytes())
3✔
3294
                if chanID == nil {
3295
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
3✔
3296
                }
3297

3298
                // If the channel is found to exists, then we'll first retrieve
3299
                // the general information for the channel.
3300
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
3301
                if err != nil {
3✔
3302
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
3✔
3303
                }
3✔
3304
                edgeInfo = &edge
3✔
3305

3✔
3306
                // Once we have the information about the channels' parameters,
3✔
3307
                // we'll fetch the routing policies for each for the directed
3✔
3308
                // edges.
3✔
3309
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
3310
                if err != nil {
3✔
3311
                        return fmt.Errorf("failed to find policy: %w", err)
3✔
3312
                }
3✔
3313

3✔
3314
                policy1 = e1
3✔
3315
                policy2 = e2
3316

3317
                return nil
3318
        }, func() {
3319
                edgeInfo = nil
3320
                policy1 = nil
3321
                policy2 = nil
3322
        })
3323
        if err != nil {
3✔
3324
                return nil, nil, nil, err
3✔
3325
        }
3✔
3326

3✔
3327
        return edgeInfo, policy1, policy2, nil
3✔
3328
}
3✔
3329

3✔
3330
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3✔
3331
// channel identified by the channel ID. If the channel can't be found, then
6✔
3332
// ErrEdgeNotFound is returned. A struct which houses the general information
3✔
3333
// for the channel itself is returned as well as two structs that contain the
3✔
3334
// routing policies for the channel in either direction.
3✔
3335
//
3✔
UNCOV
3336
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
×
UNCOV
3337
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
×
3338
// the ChannelEdgeInfo will only include the public keys of each node.
3339
func (c *KVStore) FetchChannelEdgesByID(chanID uint64) (
3340
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3341
        *models.ChannelEdgePolicy, error) {
3342

3✔
3343
        var (
3✔
UNCOV
3344
                edgeInfo  *models.ChannelEdgeInfo
×
UNCOV
3345
                policy1   *models.ChannelEdgePolicy
×
3346
                policy2   *models.ChannelEdgePolicy
3✔
3347
                channelID [8]byte
3✔
UNCOV
3348
        )
×
UNCOV
3349

×
3350
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
3351
                // First, grab the node bucket. This will be used to populate
3352
                // the Node pointers in each edge read from disk.
3353
                nodes := tx.ReadBucket(nodeBucket)
3✔
3354
                if nodes == nil {
3✔
3355
                        return ErrGraphNotFound
×
3356
                }
×
3357

3✔
3358
                // Next, grab the edge bucket which stores the edges, and also
3✔
UNCOV
3359
                // the index itself so we can group the directed edges together
×
UNCOV
3360
                // logically.
×
3361
                edges := tx.ReadBucket(edgeBucket)
3✔
3362
                if edges == nil {
6✔
3363
                        return ErrGraphNoEdgesFound
3✔
3364
                }
3✔
3365
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3366
                if edgeIndex == nil {
3367
                        return ErrGraphNoEdgesFound
3368
                }
3✔
3369

3✔
UNCOV
3370
                byteOrder.PutUint64(channelID[:], chanID)
×
UNCOV
3371

×
3372
                // Now, attempt to fetch edge.
3✔
3373
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
3✔
3374

3✔
3375
                // If it doesn't exist, we'll quickly check our zombie index to
3✔
3376
                // see if we've previously marked it as so.
3✔
3377
                if errors.Is(err, ErrEdgeNotFound) {
3✔
3378
                        // If the zombie index doesn't exist, or the edge is not
3✔
UNCOV
3379
                        // marked as a zombie within it, then we'll return the
×
UNCOV
3380
                        // original ErrEdgeNotFound error.
×
3381
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3382
                        if zombieIndex == nil {
3✔
3383
                                return ErrEdgeNotFound
3✔
3384
                        }
3✔
3385

3✔
3386
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3387
                                zombieIndex, chanID,
3✔
3388
                        )
3✔
3389
                        if !isZombie {
3✔
3390
                                return ErrEdgeNotFound
3✔
3391
                        }
6✔
3392

3✔
3393
                        // Otherwise, the edge is marked as a zombie, so we'll
3✔
3394
                        // populate the edge info with the public keys of each
3395
                        // party as this is the only information we have about
3✔
3396
                        // it and return an error signaling so.
3397
                        edgeInfo = &models.ChannelEdgeInfo{
3398
                                NodeKey1Bytes: pubKey1,
3399
                                NodeKey2Bytes: pubKey2,
3400
                        }
3401

3402
                        return ErrZombieEdge
3403
                }
3404

3405
                // Otherwise, we'll just return the error if any.
3406
                if err != nil {
3407
                        return err
3408
                }
3409

3✔
3410
                edgeInfo = &edge
3✔
3411

3✔
3412
                // Then we'll attempt to fetch the accompanying policies of this
3✔
3413
                // edge.
3✔
3414
                e1, e2, err := fetchChanEdgePolicies(
3✔
3415
                        edgeIndex, edges, channelID[:],
3✔
3416
                )
3✔
3417
                if err != nil {
3✔
3418
                        return err
6✔
3419
                }
3✔
3420

3✔
3421
                policy1 = e1
3✔
3422
                policy2 = e2
3✔
UNCOV
3423

×
UNCOV
3424
                return nil
×
3425
        }, func() {
3426
                edgeInfo = nil
3427
                policy1 = nil
3428
                policy2 = nil
3429
        })
3✔
3430
        if errors.Is(err, ErrZombieEdge) {
3✔
UNCOV
3431
                return edgeInfo, nil, nil, err
×
UNCOV
3432
        }
×
3433
        if err != nil {
3✔
3434
                return nil, nil, nil, err
3✔
UNCOV
3435
        }
×
UNCOV
3436

×
3437
        return edgeInfo, policy1, policy2, nil
3438
}
3✔
3439

3✔
3440
// IsPublicNode is a helper method that determines whether the node with the
3✔
3441
// given public key is seen as a public node in the graph from the graph's
3✔
3442
// source node's point of view.
3✔
3443
func (c *KVStore) IsPublicNode(pubKey [33]byte) (bool, error) {
3✔
3444
        var nodeIsPublic bool
3✔
3445
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3446
                nodes := tx.ReadBucket(nodeBucket)
3✔
3447
                if nodes == nil {
3✔
3448
                        return ErrGraphNodesNotFound
3✔
3449
                }
3✔
3450
                ourPubKey := nodes.Get(sourceKey)
3✔
UNCOV
3451
                if ourPubKey == nil {
×
3452
                        return ErrSourceNodeNotSet
×
3453
                }
3454
                node, err := fetchLightningNode(nodes, pubKey[:])
3✔
3455
                if err != nil {
3✔
3456
                        return err
3✔
3457
                }
6✔
3458

3✔
3459
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
3✔
3460

3461
                return err
3462
        }, func() {
3463
                nodeIsPublic = false
3464
        })
3465
        if err != nil {
3✔
3466
                return false, err
3✔
3467
        }
3✔
3468

3✔
3469
        return nodeIsPublic, nil
3✔
3470
}
3✔
3471

3472
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3473
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
3474
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
3✔
UNCOV
3475
        if err != nil {
×
3476
                return nil, err
×
3477
        }
3478

3✔
3479
        // With the witness script generated, we'll now turn it into a p2wsh
3✔
3480
        // script:
3✔
3481
        //  * OP_0 <sha256(script)>
3✔
3482
        bldr := txscript.NewScriptBuilder(
3✔
3483
                txscript.WithScriptAllocSize(input.P2WSHSize),
3✔
3484
        )
3✔
3485
        bldr.AddOp(txscript.OP_0)
3✔
UNCOV
3486
        scriptHash := sha256.Sum256(witnessScript)
×
UNCOV
3487
        bldr.AddData(scriptHash[:])
×
3488

3489
        return bldr.Script()
3✔
3490
}
3✔
3491

3✔
3492
// EdgePoint couples the outpoint of a channel with the funding script that it
3✔
3493
// creates. The FilteredChainView will use this to watch for spends of this
3✔
3494
// edge point on chain. We require both of these values as depending on the
3✔
3495
// concrete implementation, either the pkScript, or the out point will be used.
3✔
3496
type EdgePoint struct {
3✔
3497
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3✔
3498
        FundingPkScript []byte
6✔
3499

3✔
3500
        // OutPoint is the outpoint of the target channel.
3✔
3501
        OutPoint wire.OutPoint
6✔
3502
}
3✔
3503

3✔
3504
// String returns a human readable version of the target EdgePoint. We return
3505
// the outpoint directly as it is enough to uniquely identify the edge point.
3✔
3506
func (e *EdgePoint) String() string {
3507
        return e.OutPoint.String()
3508
}
3509

3510
// ChannelView returns the verifiable edge information for each active channel
3511
// within the known channel graph. The set of UTXO's (along with their scripts)
3✔
3512
// returned are the ones that need to be watched on chain to detect channel
3✔
3513
// closes on the resident blockchain.
6✔
3514
func (c *KVStore) ChannelView() ([]EdgePoint, error) {
3✔
3515
        var edgePoints []EdgePoint
3✔
UNCOV
3516
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
UNCOV
3517
                // We're going to iterate over the entire channel index, so
×
3518
                // we'll need to fetch the edgeBucket to get to the index as
3✔
3519
                // it's a sub-bucket.
3✔
UNCOV
3520
                edges := tx.ReadBucket(edgeBucket)
×
UNCOV
3521
                if edges == nil {
×
3522
                        return ErrGraphNoEdgesFound
3✔
3523
                }
3✔
UNCOV
3524
                chanIndex := edges.NestedReadBucket(channelPointBucket)
×
UNCOV
3525
                if chanIndex == nil {
×
3526
                        return ErrGraphNoEdgesFound
3527
                }
3✔
3528
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3529
                if edgeIndex == nil {
3✔
3530
                        return ErrGraphNoEdgesFound
3✔
3531
                }
3✔
3532

3✔
3533
                // Once we have the proper bucket, we'll range over each key
3✔
UNCOV
3534
                // (which is the channel point for the channel) and decode it,
×
UNCOV
3535
                // accumulating each entry.
×
3536
                return chanIndex.ForEach(
3537
                        func(chanPointBytes, chanID []byte) error {
3✔
3538
                                chanPointReader := bytes.NewReader(
3539
                                        chanPointBytes,
3540
                                )
3541

3✔
3542
                                var chanPoint wire.OutPoint
3✔
3543
                                err := ReadOutpoint(chanPointReader, &chanPoint)
3✔
UNCOV
3544
                                if err != nil {
×
3545
                                        return err
×
3546
                                }
3547

3548
                                edgeInfo, err := fetchChanEdgeInfo(
3549
                                        edgeIndex, chanID,
3550
                                )
3✔
3551
                                if err != nil {
3✔
3552
                                        return err
3✔
3553
                                }
3✔
3554

3✔
3555
                                pkScript, err := genMultiSigP2WSH(
3✔
3556
                                        edgeInfo.BitcoinKey1Bytes[:],
3✔
3557
                                        edgeInfo.BitcoinKey2Bytes[:],
3✔
3558
                                )
3559
                                if err != nil {
3560
                                        return err
3561
                                }
3562

3563
                                edgePoints = append(edgePoints, EdgePoint{
3564
                                        FundingPkScript: pkScript,
3565
                                        OutPoint:        chanPoint,
3566
                                })
3567

3568
                                return nil
3569
                        },
3570
                )
3571
        }, func() {
3572
                edgePoints = nil
3573
        }); err != nil {
3574
                return nil, err
×
3575
        }
×
UNCOV
3576

×
3577
        return edgePoints, nil
3578
}
3579

3580
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3581
// zombie. This method is used on an ad-hoc basis, when channels need to be
3582
// marked as zombies outside the normal pruning cycle.
3✔
3583
func (c *KVStore) MarkEdgeZombie(chanID uint64,
3✔
3584
        pubKey1, pubKey2 [33]byte) error {
6✔
3585

3✔
3586
        c.cacheMu.Lock()
3✔
3587
        defer c.cacheMu.Unlock()
3✔
3588

3✔
3589
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
3✔
3590
                edges := tx.ReadWriteBucket(edgeBucket)
×
3591
                if edges == nil {
×
3592
                        return ErrGraphNoEdgesFound
3✔
3593
                }
3✔
3594
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
×
3595
                if err != nil {
×
3596
                        return fmt.Errorf("unable to create zombie "+
3✔
3597
                                "bucket: %w", err)
3✔
3598
                }
×
UNCOV
3599

×
3600
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
3601
        })
3602
        if err != nil {
3603
                return err
3604
        }
3✔
3605

6✔
3606
        c.rejectCache.remove(chanID)
3✔
3607
        c.chanCache.remove(chanID)
3✔
3608

3✔
3609
        return nil
3✔
3610
}
3✔
3611

3✔
3612
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3✔
UNCOV
3613
// keys should represent the node public keys of the two parties involved in the
×
UNCOV
3614
// edge.
×
3615
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3616
        pubKey2 [33]byte) error {
3✔
3617

3✔
3618
        var k [8]byte
3✔
3619
        byteOrder.PutUint64(k[:], chanID)
3✔
UNCOV
3620

×
UNCOV
3621
        var v [66]byte
×
3622
        copy(v[:33], pubKey1[:])
3623
        copy(v[33:], pubKey2[:])
3✔
3624

3✔
3625
        return zombieIndex.Put(k[:], v[:])
3✔
3626
}
3✔
3627

3✔
UNCOV
3628
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
×
3629
func (c *KVStore) MarkEdgeLive(chanID uint64) error {
×
3630
        c.cacheMu.Lock()
3631
        defer c.cacheMu.Unlock()
3✔
3632

3✔
3633
        return c.markEdgeLiveUnsafe(nil, chanID)
3✔
3634
}
3✔
3635

3✔
3636
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3✔
3637
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3638
// case a new transaction will be created.
3639
//
3✔
3640
// NOTE: this method MUST only be called if the cacheMu has already been
3✔
3641
// acquired.
3✔
3642
func (c *KVStore) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
×
3643
        dbFn := func(tx kvdb.RwTx) error {
×
3644
                edges := tx.ReadWriteBucket(edgeBucket)
3645
                if edges == nil {
3✔
3646
                        return ErrGraphNoEdgesFound
3647
                }
3648
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
3649
                if zombieIndex == nil {
3650
                        return nil
3651
                }
UNCOV
3652

×
3653
                var k [8]byte
×
3654
                byteOrder.PutUint64(k[:], chanID)
×
3655

×
3656
                if len(zombieIndex.Get(k[:])) == 0 {
×
3657
                        return ErrZombieEdgeNotFound
×
3658
                }
×
UNCOV
3659

×
3660
                return zombieIndex.Delete(k[:])
×
UNCOV
3661
        }
×
UNCOV
3662

×
UNCOV
3663
        // If the transaction is nil, we'll create a new one. Otherwise, we use
×
UNCOV
3664
        // the existing transaction
×
3665
        var err error
×
3666
        if tx == nil {
×
3667
                err = kvdb.Update(c.db, dbFn, func() {})
3668
        } else {
×
3669
                err = dbFn(tx)
3670
        }
×
3671
        if err != nil {
×
3672
                return err
×
3673
        }
UNCOV
3674

×
3675
        c.rejectCache.remove(chanID)
×
3676
        c.chanCache.remove(chanID)
×
3677

×
3678
        return nil
3679
}
3680

3681
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3682
// zombie, then the two node public keys corresponding to this edge are also
3683
// returned.
3684
func (c *KVStore) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
3✔
3685
        var (
3✔
3686
                isZombie         bool
3✔
3687
                pubKey1, pubKey2 [33]byte
3✔
3688
        )
3✔
3689

3✔
3690
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
3✔
3691
                edges := tx.ReadBucket(edgeBucket)
3✔
3692
                if edges == nil {
3✔
3693
                        return ErrGraphNoEdgesFound
3✔
3694
                }
3✔
3695
                zombieIndex := edges.NestedReadBucket(zombieBucket)
3696
                if zombieIndex == nil {
3697
                        return nil
×
3698
                }
×
UNCOV
3699

×
3700
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
×
3701

×
3702
                return nil
×
3703
        }, func() {
3704
                isZombie = false
3705
                pubKey1 = [33]byte{}
3706
                pubKey2 = [33]byte{}
3707
        })
3708
        if err != nil {
3709
                return false, [33]byte{}, [33]byte{}
3710
        }
×
UNCOV
3711

×
3712
        return isZombie, pubKey1, pubKey2
×
UNCOV
3713
}
×
UNCOV
3714

×
UNCOV
3715
// isZombieEdge returns whether an entry exists for the given channel in the
×
UNCOV
3716
// zombie index. If an entry exists, then the two node public keys corresponding
×
UNCOV
3717
// to this edge are also returned.
×
UNCOV
3718
func isZombieEdge(zombieIndex kvdb.RBucket,
×
UNCOV
3719
        chanID uint64) (bool, [33]byte, [33]byte) {
×
3720

UNCOV
3721
        var k [8]byte
×
UNCOV
3722
        byteOrder.PutUint64(k[:], chanID)
×
UNCOV
3723

×
UNCOV
3724
        v := zombieIndex.Get(k[:])
×
UNCOV
3725
        if v == nil {
×
UNCOV
3726
                return false, [33]byte{}, [33]byte{}
×
3727
        }
UNCOV
3728

×
3729
        var pubKey1, pubKey2 [33]byte
3730
        copy(pubKey1[:], v[:33])
3731
        copy(pubKey2[:], v[33:])
3732

UNCOV
3733
        return true, pubKey1, pubKey2
×
UNCOV
3734
}
×
UNCOV
3735

×
UNCOV
3736
// NumZombies returns the current number of zombie channels in the graph.
×
3737
func (c *KVStore) NumZombies() (uint64, error) {
×
3738
        var numZombies uint64
×
3739
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
3740
                edges := tx.ReadBucket(edgeBucket)
×
3741
                if edges == nil {
×
3742
                        return nil
3743
                }
×
3744
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
3745
                if zombieIndex == nil {
×
3746
                        return nil
×
3747
                }
3748

3749
                return zombieIndex.ForEach(func(_, _ []byte) error {
3750
                        numZombies++
3751
                        return nil
3752
                })
×
3753
        }, func() {
×
3754
                numZombies = 0
×
3755
        })
×
3756
        if err != nil {
×
3757
                return 0, err
×
3758
        }
×
UNCOV
3759

×
3760
        return numZombies, nil
×
UNCOV
3761
}
×
UNCOV
3762

×
UNCOV
3763
// PutClosedScid stores a SCID for a closed channel in the database. This is so
×
UNCOV
3764
// that we can ignore channel announcements that we know to be closed without
×
UNCOV
3765
// having to validate them and fetch a block.
×
3766
func (c *KVStore) PutClosedScid(scid lnwire.ShortChannelID) error {
×
3767
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
3768
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
×
3769
                if err != nil {
×
3770
                        return err
×
3771
                }
×
UNCOV
3772

×
3773
                var k [8]byte
×
3774
                byteOrder.PutUint64(k[:], scid.ToUint64())
×
3775

×
3776
                return closedScids.Put(k[:], []byte{})
×
3777
        }, func() {})
×
UNCOV
3778
}
×
3779

UNCOV
3780
// IsClosedScid checks whether a channel identified by the passed in scid is
×
3781
// closed. This helps avoid having to perform expensive validation checks.
3782
// TODO: Add an LRU cache to cut down on disc reads.
3783
func (c *KVStore) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
3784
        var isClosed bool
3785
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
3786
                closedScids := tx.ReadBucket(closedScidBucket)
3787
                if closedScids == nil {
3✔
3788
                        return ErrClosedScidsNotFound
3✔
3789
                }
3✔
3790

3✔
3791
                var k [8]byte
3✔
3792
                byteOrder.PutUint64(k[:], scid.ToUint64())
3✔
3793

6✔
3794
                if closedScids.Get(k[:]) != nil {
3✔
3795
                        isClosed = true
3✔
3796
                        return nil
3797
                }
3✔
3798

3✔
3799
                return nil
3✔
3800
        }, func() {
3✔
3801
                isClosed = false
3✔
3802
        })
3803
        if err != nil {
3804
                return false, err
3805
        }
×
UNCOV
3806

×
UNCOV
3807
        return isClosed, nil
×
UNCOV
3808
}
×
UNCOV
3809

×
UNCOV
3810
// GraphSession will provide the call-back with access to a NodeTraverser
×
UNCOV
3811
// instance which can be used to perform queries against the channel graph.
×
3812
func (c *KVStore) GraphSession(cb func(graph NodeTraverser) error) error {
×
3813
        return c.db.View(func(tx walletdb.ReadTx) error {
×
3814
                return cb(&nodeTraverserSession{
×
3815
                        db: c,
×
3816
                        tx: tx,
3817
                })
×
3818
        }, func() {})
×
UNCOV
3819
}
×
UNCOV
3820

×
UNCOV
3821
// nodeTraverserSession implements the NodeTraverser interface but with a
×
UNCOV
3822
// backing read only transaction for a consistent view of the graph.
×
UNCOV
3823
type nodeTraverserSession struct {
×
UNCOV
3824
        tx kvdb.RTx
×
UNCOV
3825
        db *KVStore
×
UNCOV
3826
}
×
3827

UNCOV
3828
// ForEachNodeDirectedChannel calls the callback for every channel of the given
×
3829
// node.
3830
//
3831
// NOTE: Part of the NodeTraverser interface.
3832
func (c *nodeTraverserSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
3833
        cb func(channel *DirectedChannel) error) error {
3834

×
3835
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
×
3836
}
×
UNCOV
3837

×
UNCOV
3838
// FetchNodeFeatures returns the features of the given node. If the node is
×
UNCOV
3839
// unknown, assume no additional features are supported.
×
3840
//
UNCOV
3841
// NOTE: Part of the NodeTraverser interface.
×
UNCOV
3842
func (c *nodeTraverserSession) FetchNodeFeatures(nodePub route.Vertex) (
×
3843
        *lnwire.FeatureVector, error) {
×
3844

×
3845
        return c.db.fetchNodeFeatures(c.tx, nodePub)
×
3846
}
3847

3848
func putLightningNode(nodeBucket, aliasBucket, updateIndex kvdb.RwBucket,
3849
        node *models.LightningNode) error {
3850

3851
        var (
3✔
3852
                scratch [16]byte
3✔
3853
                b       bytes.Buffer
6✔
3854
        )
3✔
3855

3✔
UNCOV
3856
        pub, err := node.PubKey()
×
UNCOV
3857
        if err != nil {
×
3858
                return err
3859
        }
3✔
3860
        nodePub := pub.SerializeCompressed()
3✔
3861

3✔
3862
        // If the node has the update time set, write it, else write 0.
3✔
UNCOV
3863
        updateUnix := uint64(0)
×
UNCOV
3864
        if node.LastUpdate.Unix() > 0 {
×
UNCOV
3865
                updateUnix = uint64(node.LastUpdate.Unix())
×
3866
        }
3867

3✔
3868
        byteOrder.PutUint64(scratch[:8], updateUnix)
3✔
3869
        if _, err := b.Write(scratch[:8]); err != nil {
3✔
3870
                return err
3✔
3871
        }
3✔
UNCOV
3872

×
UNCOV
3873
        if _, err := b.Write(nodePub); err != nil {
×
3874
                return err
3875
        }
3✔
3876

3877
        // If we got a node announcement for this node, we will have the rest
3878
        // of the data available. If not we don't have more data to write.
3879
        if !node.HaveNodeAnnouncement {
UNCOV
3880
                // Write HaveNodeAnnouncement=0.
×
UNCOV
3881
                byteOrder.PutUint16(scratch[:2], 0)
×
UNCOV
3882
                if _, err := b.Write(scratch[:2]); err != nil {
×
3883
                        return err
×
3884
                }
×
UNCOV
3885

×
UNCOV
3886
                return nodeBucket.Put(nodePub, b.Bytes())
×
3887
        }
3888

3889
        // Write HaveNodeAnnouncement=1.
3890
        byteOrder.PutUint16(scratch[:2], 1)
3891
        if _, err := b.Write(scratch[:2]); err != nil {
3892
                return err
3893
        }
3894

3895
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
3896
                return err
3897
        }
3898
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
3899
                return err
3900
        }
UNCOV
3901
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
×
3902
                return err
×
3903
        }
×
UNCOV
3904

×
3905
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
3906
                return err
3907
        }
3908

3909
        if err := node.Features.Encode(&b); err != nil {
3910
                return err
3911
        }
×
UNCOV
3912

×
UNCOV
3913
        numAddresses := uint16(len(node.Addresses))
×
UNCOV
3914
        byteOrder.PutUint16(scratch[:2], numAddresses)
×
3915
        if _, err := b.Write(scratch[:2]); err != nil {
3916
                return err
3917
        }
3✔
3918

3✔
3919
        for _, address := range node.Addresses {
3✔
3920
                if err := SerializeAddr(&b, address); err != nil {
3✔
3921
                        return err
3✔
3922
                }
3✔
3923
        }
3✔
3924

3✔
3925
        sigLen := len(node.AuthSigBytes)
3✔
UNCOV
3926
        if sigLen > 80 {
×
3927
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
3928
                        sigLen)
3✔
3929
        }
3✔
3930

3✔
3931
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
3✔
3932
        if err != nil {
6✔
3933
                return err
3✔
3934
        }
3✔
3935

3936
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
3937
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
3✔
3938
        }
×
UNCOV
3939
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
×
3940
        if err != nil {
3941
                return err
3✔
3942
        }
×
UNCOV
3943

×
3944
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
3945
                return err
3946
        }
3947

6✔
3948
        // With the alias bucket updated, we'll now update the index that
3✔
3949
        // tracks the time series of node updates.
3✔
3950
        var indexKey [8 + 33]byte
3✔
UNCOV
3951
        byteOrder.PutUint64(indexKey[:8], updateUnix)
×
UNCOV
3952
        copy(indexKey[8:], nodePub)
×
3953

3954
        // If there was already an old index entry for this node, then we'll
3✔
3955
        // delete the old one before we write the new entry.
3956
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
3957
                // Extract out the old update time to we can reconstruct the
3958
                // prior index key to delete it from the index.
3✔
3959
                oldUpdateTime := nodeBytes[:8]
3✔
UNCOV
3960

×
UNCOV
3961
                var oldIndexKey [8 + 33]byte
×
3962
                copy(oldIndexKey[:8], oldUpdateTime)
3963
                copy(oldIndexKey[8:], nodePub)
3✔
UNCOV
3964

×
UNCOV
3965
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
×
3966
                        return err
3✔
3967
                }
×
UNCOV
3968
        }
×
3969

3✔
UNCOV
3970
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
×
3971
                return err
×
3972
        }
3973

3✔
UNCOV
3974
        return nodeBucket.Put(nodePub, b.Bytes())
×
UNCOV
3975
}
×
3976

3977
func fetchLightningNode(nodeBucket kvdb.RBucket,
3✔
UNCOV
3978
        nodePub []byte) (models.LightningNode, error) {
×
UNCOV
3979

×
3980
        nodeBytes := nodeBucket.Get(nodePub)
3981
        if nodeBytes == nil {
3✔
3982
                return models.LightningNode{}, ErrGraphNodeNotFound
3✔
3983
        }
3✔
UNCOV
3984

×
UNCOV
3985
        nodeReader := bytes.NewReader(nodeBytes)
×
3986

3987
        return deserializeLightningNode(nodeReader)
6✔
3988
}
3✔
UNCOV
3989

×
UNCOV
3990
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
×
3991
        *lnwire.FeatureVector, error) {
3992

3993
        var (
3✔
3994
                pubKey      route.Vertex
3✔
UNCOV
3995
                features    = lnwire.EmptyFeatureVector()
×
UNCOV
3996
                nodeScratch [8]byte
×
UNCOV
3997
        )
×
3998

3999
        // Skip ahead:
3✔
4000
        // - LastUpdate (8 bytes)
3✔
UNCOV
4001
        if _, err := r.Read(nodeScratch[:]); err != nil {
×
4002
                return pubKey, nil, err
×
4003
        }
4004

3✔
UNCOV
4005
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
×
4006
                return pubKey, nil, err
×
4007
        }
3✔
4008

3✔
UNCOV
4009
        // Read the node announcement flag.
×
UNCOV
4010
        if _, err := r.Read(nodeScratch[:2]); err != nil {
×
4011
                return pubKey, nil, err
4012
        }
3✔
UNCOV
4013
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
×
UNCOV
4014

×
4015
        // The rest of the data is optional, and will only be there if we got a
4016
        // node announcement for this node.
4017
        if hasNodeAnn == 0 {
4018
                return pubKey, features, nil
3✔
4019
        }
3✔
4020

3✔
4021
        // We did get a node announcement for this node, so we'll have the rest
3✔
4022
        // of the data available.
3✔
4023
        var rgb uint8
3✔
4024
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
6✔
4025
                return pubKey, nil, err
3✔
4026
        }
3✔
4027
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4028
                return pubKey, nil, err
3✔
4029
        }
3✔
4030
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4031
                return pubKey, nil, err
3✔
4032
        }
3✔
4033

3✔
UNCOV
4034
        if _, err := wire.ReadVarString(r, 0); err != nil {
×
4035
                return pubKey, nil, err
×
4036
        }
4037

4038
        if err := features.Decode(r); err != nil {
3✔
4039
                return pubKey, nil, err
×
4040
        }
×
4041

4042
        return pubKey, features, nil
3✔
4043
}
4044

4045
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
4046
        var (
3✔
4047
                node    models.LightningNode
3✔
4048
                scratch [8]byte
3✔
4049
                err     error
6✔
4050
        )
3✔
4051

3✔
4052
        // Always populate a feature vector, even if we don't have a node
4053
        // announcement and short circuit below.
3✔
4054
        node.Features = lnwire.EmptyFeatureVector()
3✔
4055

3✔
4056
        if _, err := r.Read(scratch[:]); err != nil {
4057
                return models.LightningNode{}, err
4058
        }
4059

3✔
4060
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4061
        node.LastUpdate = time.Unix(unix, 0)
3✔
4062

3✔
4063
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
3✔
4064
                return models.LightningNode{}, err
3✔
4065
        }
3✔
4066

3✔
4067
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4068
                return models.LightningNode{}, err
3✔
4069
        }
3✔
UNCOV
4070

×
UNCOV
4071
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
×
4072
        if hasNodeAnn == 1 {
4073
                node.HaveNodeAnnouncement = true
3✔
UNCOV
4074
        } else {
×
UNCOV
4075
                node.HaveNodeAnnouncement = false
×
4076
        }
4077

4078
        // The rest of the data is optional, and will only be there if we got a
3✔
UNCOV
4079
        // node announcement for this node.
×
UNCOV
4080
        if !node.HaveNodeAnnouncement {
×
4081
                return node, nil
3✔
4082
        }
3✔
4083

3✔
4084
        // We did get a node announcement for this node, so we'll have the rest
3✔
4085
        // of the data available.
6✔
4086
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
3✔
4087
                return models.LightningNode{}, err
3✔
4088
        }
4089
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
4090
                return models.LightningNode{}, err
4091
        }
3✔
4092
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
3✔
4093
                return models.LightningNode{}, err
×
4094
        }
×
4095

3✔
UNCOV
4096
        node.Alias, err = wire.ReadVarString(r, 0)
×
UNCOV
4097
        if err != nil {
×
4098
                return models.LightningNode{}, err
3✔
4099
        }
×
UNCOV
4100

×
4101
        err = node.Features.Decode(r)
4102
        if err != nil {
3✔
4103
                return models.LightningNode{}, err
×
4104
        }
×
4105

4106
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4107
                return models.LightningNode{}, err
×
4108
        }
×
4109
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
4110

3✔
4111
        var addresses []net.Addr
4112
        for i := 0; i < numAddresses; i++ {
4113
                address, err := DeserializeAddr(r)
3✔
4114
                if err != nil {
3✔
4115
                        return models.LightningNode{}, err
3✔
4116
                }
3✔
4117
                addresses = append(addresses, address)
3✔
4118
        }
3✔
4119
        node.Addresses = addresses
3✔
4120

3✔
4121
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4122
        if err != nil {
3✔
4123
                return models.LightningNode{}, err
3✔
4124
        }
3✔
UNCOV
4125

×
UNCOV
4126
        // We'll try and see if there are any opaque bytes left, if not, then
×
4127
        // we'll ignore the EOF error and return the node as is.
4128
        extraBytes, err := wire.ReadVarBytes(
3✔
4129
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4130
        )
3✔
4131
        switch {
3✔
4132
        case errors.Is(err, io.ErrUnexpectedEOF):
×
4133
        case errors.Is(err, io.EOF):
×
4134
        case err != nil:
4135
                return models.LightningNode{}, err
3✔
UNCOV
4136
        }
×
UNCOV
4137

×
4138
        if len(extraBytes) > 0 {
4139
                node.ExtraOpaqueData = extraBytes
3✔
4140
        }
6✔
4141

3✔
4142
        return node, nil
6✔
4143
}
3✔
4144

3✔
4145
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4146
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
4147

4148
        var b bytes.Buffer
6✔
4149

3✔
4150
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4151
                return err
4152
        }
4153
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
4154
                return err
3✔
4155
        }
×
UNCOV
4156
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
×
4157
                return err
3✔
4158
        }
×
UNCOV
4159
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
×
4160
                return err
3✔
4161
        }
×
UNCOV
4162

×
4163
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
4164
                return err
3✔
4165
        }
3✔
UNCOV
4166

×
UNCOV
4167
        authProof := edgeInfo.AuthProof
×
4168
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
4169
        if authProof != nil {
3✔
4170
                nodeSig1 = authProof.NodeSig1Bytes
3✔
UNCOV
4171
                nodeSig2 = authProof.NodeSig2Bytes
×
UNCOV
4172
                bitcoinSig1 = authProof.BitcoinSig1Bytes
×
4173
                bitcoinSig2 = authProof.BitcoinSig2Bytes
4174
        }
3✔
UNCOV
4175

×
UNCOV
4176
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
×
4177
                return err
3✔
4178
        }
3✔
4179
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
3✔
4180
                return err
6✔
4181
        }
3✔
4182
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
3✔
4183
                return err
×
4184
        }
×
4185
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
3✔
4186
                return err
4187
        }
3✔
4188

3✔
4189
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
4190
                return err
3✔
4191
        }
×
UNCOV
4192
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
×
4193
        if err != nil {
4194
                return err
4195
        }
4196
        if _, err := b.Write(chanID[:]); err != nil {
3✔
4197
                return err
3✔
4198
        }
3✔
4199
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
3✔
4200
                return err
×
4201
        }
×
UNCOV
4202

×
UNCOV
4203
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
×
4204
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
4205
        }
4206
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
3✔
UNCOV
4207
        if err != nil {
×
4208
                return err
×
4209
        }
4210

3✔
4211
        return edgeIndex.Put(chanID[:], b.Bytes())
4212
}
4213

4214
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
3✔
4215
        chanID []byte) (models.ChannelEdgeInfo, error) {
3✔
4216

3✔
4217
        edgeInfoBytes := edgeIndex.Get(chanID)
3✔
4218
        if edgeInfoBytes == nil {
3✔
UNCOV
4219
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
×
UNCOV
4220
        }
×
4221

3✔
UNCOV
4222
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
×
UNCOV
4223

×
4224
        return deserializeChanEdgeInfo(edgeInfoReader)
3✔
UNCOV
4225
}
×
UNCOV
4226

×
4227
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
3✔
UNCOV
4228
        var (
×
UNCOV
4229
                err      error
×
4230
                edgeInfo models.ChannelEdgeInfo
4231
        )
3✔
UNCOV
4232

×
UNCOV
4233
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
×
4234
                return models.ChannelEdgeInfo{}, err
4235
        }
3✔
4236
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4237
                return models.ChannelEdgeInfo{}, err
6✔
4238
        }
3✔
4239
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4240
                return models.ChannelEdgeInfo{}, err
3✔
4241
        }
3✔
4242
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4243
                return models.ChannelEdgeInfo{}, err
4244
        }
3✔
UNCOV
4245

×
UNCOV
4246
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
×
4247
        if err != nil {
3✔
4248
                return models.ChannelEdgeInfo{}, err
×
4249
        }
×
4250

3✔
UNCOV
4251
        proof := &models.ChannelAuthProof{}
×
UNCOV
4252

×
4253
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
UNCOV
4254
        if err != nil {
×
4255
                return models.ChannelEdgeInfo{}, err
×
4256
        }
4257
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
UNCOV
4258
        if err != nil {
×
4259
                return models.ChannelEdgeInfo{}, err
×
4260
        }
3✔
4261
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
UNCOV
4262
        if err != nil {
×
4263
                return models.ChannelEdgeInfo{}, err
×
4264
        }
3✔
UNCOV
4265
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
×
UNCOV
4266
        if err != nil {
×
4267
                return models.ChannelEdgeInfo{}, err
3✔
4268
        }
×
UNCOV
4269

×
4270
        if !proof.IsEmpty() {
4271
                edgeInfo.AuthProof = proof
3✔
UNCOV
4272
        }
×
UNCOV
4273

×
4274
        edgeInfo.ChannelPoint = wire.OutPoint{}
3✔
4275
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
3✔
4276
                return models.ChannelEdgeInfo{}, err
×
4277
        }
×
4278
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4279
                return models.ChannelEdgeInfo{}, err
3✔
4280
        }
4281
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4282
                return models.ChannelEdgeInfo{}, err
4283
        }
3✔
4284

3✔
4285
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
3✔
4286
                return models.ChannelEdgeInfo{}, err
6✔
4287
        }
3✔
4288

3✔
4289
        // We'll try and see if there are any opaque bytes left, if not, then
4290
        // we'll ignore the EOF error and return the edge as is.
3✔
4291
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4292
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4293
        )
4294
        switch {
4295
        case errors.Is(err, io.ErrUnexpectedEOF):
3✔
4296
        case errors.Is(err, io.EOF):
3✔
4297
        case err != nil:
3✔
4298
                return models.ChannelEdgeInfo{}, err
3✔
4299
        }
3✔
4300

3✔
4301
        return edgeInfo, nil
3✔
UNCOV
4302
}
×
UNCOV
4303

×
4304
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
3✔
UNCOV
4305
        from, to []byte) error {
×
UNCOV
4306

×
4307
        var edgeKey [33 + 8]byte
3✔
UNCOV
4308
        copy(edgeKey[:], from)
×
UNCOV
4309
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
×
4310

3✔
UNCOV
4311
        var b bytes.Buffer
×
UNCOV
4312
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
×
4313
                return err
4314
        }
3✔
4315

3✔
UNCOV
4316
        // Before we write out the new edge, we'll create a new entry in the
×
UNCOV
4317
        // update index in order to keep it fresh.
×
4318
        updateUnix := uint64(edge.LastUpdate.Unix())
4319
        var indexKey [8 + 8]byte
3✔
4320
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4321
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
3✔
4322

3✔
UNCOV
4323
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
×
UNCOV
4324
        if err != nil {
×
4325
                return err
3✔
4326
        }
3✔
UNCOV
4327

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

3✔
UNCOV
4335
                // In order to delete the old entry, we'll need to obtain the
×
UNCOV
4336
                // *prior* update time in order to delete it. To do this, we'll
×
4337
                // need to deserialize the existing policy within the database
4338
                // (now outdated by the new one), and delete its corresponding
6✔
4339
                // entry within the update index. We'll ignore any
3✔
4340
                // ErrEdgePolicyOptionalFieldNotFound or ErrParsingExtraTLVBytes
3✔
4341
                // errors, as we only need the channel ID and update time to
4342
                // delete the entry.
3✔
4343
                //
3✔
UNCOV
4344
                // TODO(halseth): get rid of these invalid policies in a
×
UNCOV
4345
                // migration.
×
4346
                // TODO(elle): complete the above TODO in migration from kvdb
3✔
UNCOV
4347
                // to SQL.
×
UNCOV
4348
                oldEdgePolicy, err := deserializeChanEdgePolicy(
×
4349
                        bytes.NewReader(edgeBytes),
3✔
UNCOV
4350
                )
×
UNCOV
4351
                if err != nil &&
×
4352
                        !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
4353
                        !errors.Is(err, ErrParsingExtraTLVBytes) {
3✔
4354

×
4355
                        return err
×
4356
                }
4357

4358
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
4359

3✔
4360
                var oldIndexKey [8 + 8]byte
3✔
4361
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
3✔
4362
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
3✔
UNCOV
4363

×
UNCOV
4364
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
×
4365
                        return err
×
4366
                }
×
4367
        }
4368

4369
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4370
                return err
4371
        }
4372

4373
        err = updateEdgePolicyDisabledIndex(
3✔
4374
                edges, edge.ChannelID,
3✔
4375
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
3✔
4376
                edge.IsDisabled(),
3✔
4377
        )
3✔
4378
        if err != nil {
3✔
4379
                return err
3✔
4380
        }
3✔
UNCOV
4381

×
UNCOV
4382
        return edges.Put(edgeKey[:], b.Bytes())
×
4383
}
4384

4385
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4386
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
3✔
4387
// one.
3✔
4388
// The direction represents the direction of the edge and disabled is used for
3✔
4389
// deciding whether to remove or add an entry to the bucket.
3✔
4390
// In general a channel is disabled if two entries for the same chanID exist
3✔
4391
// in this bucket.
3✔
4392
// Maintaining the bucket this way allows a fast retrieval of disabled
3✔
UNCOV
4393
// channels, for example when prune is needed.
×
UNCOV
4394
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
×
4395
        direction bool, disabled bool) error {
4396

4397
        var disabledEdgeKey [8 + 1]byte
4398
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
4399
        if direction {
4400
                disabledEdgeKey[8] = 1
3✔
4401
        }
6✔
4402

3✔
4403
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
3✔
4404
                disabledEdgePolicyBucket,
3✔
4405
        )
3✔
4406
        if err != nil {
3✔
4407
                return err
3✔
4408
        }
3✔
4409

3✔
4410
        if disabled {
3✔
4411
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
3✔
4412
        }
3✔
4413

3✔
4414
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
3✔
4415
}
3✔
4416

3✔
4417
// putChanEdgePolicyUnknown marks the edge policy as unknown
3✔
4418
// in the edges bucket.
3✔
4419
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
3✔
4420
        from []byte) error {
3✔
4421

3✔
UNCOV
4422
        var edgeKey [33 + 8]byte
×
UNCOV
4423
        copy(edgeKey[:], from)
×
UNCOV
4424
        byteOrder.PutUint64(edgeKey[33:], channelID)
×
4425

4426
        if edges.Get(edgeKey[:]) != nil {
3✔
4427
                return fmt.Errorf("cannot write unknown policy for channel %v "+
3✔
4428
                        " when there is already a policy present", channelID)
3✔
4429
        }
3✔
4430

3✔
4431
        return edges.Put(edgeKey[:], unknownPolicy)
3✔
4432
}
3✔
UNCOV
4433

×
UNCOV
4434
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
×
4435
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
4436

4437
        var edgeKey [33 + 8]byte
3✔
UNCOV
4438
        copy(edgeKey[:], nodePub)
×
UNCOV
4439
        copy(edgeKey[33:], chanID)
×
4440

4441
        edgeBytes := edges.Get(edgeKey[:])
3✔
4442
        if edgeBytes == nil {
3✔
4443
                return nil, ErrEdgeNotFound
3✔
4444
        }
3✔
4445

3✔
4446
        // No need to deserialize unknown policy.
3✔
UNCOV
4447
        if bytes.Equal(edgeBytes, unknownPolicy) {
×
UNCOV
4448
                return nil, nil
×
4449
        }
4450

3✔
4451
        edgeReader := bytes.NewReader(edgeBytes)
4452

4453
        ep, err := deserializeChanEdgePolicy(edgeReader)
4454
        switch {
4455
        // If the db policy was missing an expected optional field, we return
4456
        // nil as if the policy was unknown.
4457
        case errors.Is(err, ErrEdgePolicyOptionalFieldNotFound):
4458
                return nil, nil
4459

4460
        // If the policy contains invalid TLV bytes, we return nil as if
4461
        // the policy was unknown.
4462
        case errors.Is(err, ErrParsingExtraTLVBytes):
4463
                return nil, nil
3✔
4464

3✔
4465
        case err != nil:
3✔
4466
                return nil, err
3✔
4467
        }
6✔
4468

3✔
4469
        return ep, nil
3✔
4470
}
4471

3✔
4472
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
3✔
4473
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
3✔
4474
        error) {
3✔
UNCOV
4475

×
UNCOV
4476
        edgeInfo := edgeIndex.Get(chanID)
×
4477
        if edgeInfo == nil {
4478
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
6✔
4479
                        chanID)
3✔
4480
        }
3✔
4481

4482
        // The first node is contained within the first half of the edge
3✔
4483
        // information. We only propagate the error here and below if it's
4484
        // something other than edge non-existence.
4485
        node1Pub := edgeInfo[:33]
4486
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
4487
        if err != nil {
4488
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
3✔
4489
                        node1Pub)
3✔
4490
        }
3✔
4491

3✔
4492
        // Similarly, the second node is contained within the latter
3✔
4493
        // half of the edge information.
3✔
4494
        node2Pub := edgeInfo[33:66]
3✔
UNCOV
4495
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
×
UNCOV
4496
        if err != nil {
×
4497
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4498
                        node2Pub)
4499
        }
3✔
4500

4501
        return edge1, edge2, nil
4502
}
4503

3✔
4504
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
3✔
4505
        to []byte) error {
3✔
4506

3✔
4507
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
3✔
4508
        if err != nil {
3✔
4509
                return err
3✔
4510
        }
3✔
UNCOV
4511

×
UNCOV
4512
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
×
4513
                return err
4514
        }
4515

6✔
4516
        var scratch [8]byte
3✔
4517
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4518
        byteOrder.PutUint64(scratch[:], updateUnix)
4519
        if _, err := w.Write(scratch[:]); err != nil {
3✔
4520
                return err
3✔
4521
        }
3✔
4522

3✔
4523
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
4524
                return err
4525
        }
×
UNCOV
4526
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
×
4527
                return err
4528
        }
4529
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
4530
                return err
×
4531
        }
×
4532
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
4533
                return err
×
4534
        }
×
4535
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
4536
        if err != nil {
4537
                return err
3✔
4538
        }
4539
        err = binary.Write(
4540
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
4541
        )
4542
        if err != nil {
3✔
4543
                return err
3✔
4544
        }
3✔
4545

3✔
UNCOV
4546
        if _, err := w.Write(to); err != nil {
×
4547
                return err
×
4548
        }
×
4549

4550
        // If the max_htlc field is present, we write it. To be compatible with
4551
        // older versions that wasn't aware of this field, we write it as part
4552
        // of the opaque data.
4553
        // TODO(halseth): clean up when moving to TLV.
3✔
4554
        var opaqueBuf bytes.Buffer
3✔
4555
        if edge.MessageFlags.HasMaxHtlc() {
3✔
UNCOV
4556
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
×
UNCOV
4557
                if err != nil {
×
4558
                        return err
×
4559
                }
4560
        }
4561

4562
        // Validate that the ExtraOpaqueData is in fact a valid TLV stream.
3✔
4563
        err = edge.ExtraOpaqueData.ValidateTLV()
3✔
4564
        if err != nil {
3✔
4565
                return fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
4566
        }
×
UNCOV
4567

×
4568
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
4569
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
3✔
4570
        }
4571
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
4572
                return err
4573
        }
3✔
4574

3✔
4575
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
3✔
4576
                return err
3✔
4577
        }
×
UNCOV
4578

×
4579
        return nil
4580
}
3✔
UNCOV
4581

×
UNCOV
4582
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
×
4583
        // Deserialize the policy. Note that in case an optional field is not
4584
        // found or if the edge has invalid TLV data, then both an error and a
3✔
4585
        // populated policy object are returned so that the caller can decide
3✔
4586
        // if it still wants to use the edge or not.
3✔
4587
        edge, err := deserializeChanEdgePolicyRaw(r)
3✔
UNCOV
4588
        if err != nil &&
×
UNCOV
4589
                !errors.Is(err, ErrEdgePolicyOptionalFieldNotFound) &&
×
4590
                !errors.Is(err, ErrParsingExtraTLVBytes) {
4591

3✔
4592
                return nil, err
×
4593
        }
×
4594

3✔
UNCOV
4595
        return edge, err
×
UNCOV
4596
}
×
4597

3✔
UNCOV
4598
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
×
UNCOV
4599
        error) {
×
4600

3✔
UNCOV
4601
        edge := &models.ChannelEdgePolicy{}
×
UNCOV
4602

×
4603
        var err error
3✔
4604
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
UNCOV
4605
        if err != nil {
×
4606
                return nil, err
×
4607
        }
3✔
4608

3✔
4609
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
3✔
4610
                return nil, err
3✔
4611
        }
×
UNCOV
4612

×
4613
        var scratch [8]byte
4614
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4615
                return nil, err
×
4616
        }
×
4617
        unix := int64(byteOrder.Uint64(scratch[:]))
4618
        edge.LastUpdate = time.Unix(unix, 0)
4619

4620
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
4621
                return nil, err
4622
        }
3✔
4623
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
6✔
4624
                return nil, err
3✔
4625
        }
3✔
UNCOV
4626
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
×
4627
                return nil, err
×
4628
        }
4629

4630
        var n uint64
4631
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4632
                return nil, err
3✔
4633
        }
×
UNCOV
4634
        edge.MinHTLC = lnwire.MilliSatoshi(n)
×
4635

4636
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4637
                return nil, err
×
4638
        }
×
4639
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
3✔
UNCOV
4640

×
UNCOV
4641
        if err := binary.Read(r, byteOrder, &n); err != nil {
×
4642
                return nil, err
4643
        }
3✔
UNCOV
4644
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
×
UNCOV
4645

×
4646
        if _, err := r.Read(edge.ToNode[:]); err != nil {
4647
                return nil, err
3✔
4648
        }
4649

4650
        // We'll try and see if there are any opaque bytes left, if not, then
3✔
4651
        // we'll ignore the EOF error and return the edge as is.
3✔
4652
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4653
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4654
        )
3✔
4655
        switch {
3✔
4656
        case errors.Is(err, io.ErrUnexpectedEOF):
3✔
4657
        case errors.Is(err, io.EOF):
3✔
4658
        case err != nil:
3✔
4659
                return nil, err
×
UNCOV
4660
        }
×
UNCOV
4661

×
4662
        // See if optional fields are present.
4663
        if edge.MessageFlags.HasMaxHtlc() {
3✔
4664
                // The max_htlc field should be at the beginning of the opaque
4665
                // bytes.
4666
                opq := edge.ExtraOpaqueData
4667

3✔
4668
                // If the max_htlc field is not present, it might be old data
3✔
4669
                // stored before this field was validated. We'll return the
3✔
4670
                // edge along with an error.
3✔
4671
                if len(opq) < 8 {
3✔
4672
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4673
                }
3✔
UNCOV
4674

×
UNCOV
4675
                maxHtlc := byteOrder.Uint64(opq[:8])
×
4676
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
4677

3✔
UNCOV
4678
                // Exclude the parsed field from the rest of the opaque data.
×
UNCOV
4679
                edge.ExtraOpaqueData = opq[8:]
×
4680
        }
4681

3✔
4682
        // Attempt to extract the inbound fee from the opaque data. If we fail
3✔
UNCOV
4683
        // to parse the TLV here, we return an error we also return the edge
×
UNCOV
4684
        // so that the caller can still use it. This is for backwards
×
4685
        // compatibility in case we have already persisted some policies that
3✔
4686
        // have invalid TLV data.
3✔
4687
        var inboundFee lnwire.Fee
3✔
4688
        typeMap, err := edge.ExtraOpaqueData.ExtractRecords(&inboundFee)
3✔
UNCOV
4689
        if err != nil {
×
4690
                return edge, fmt.Errorf("%w: %w", ErrParsingExtraTLVBytes, err)
×
4691
        }
3✔
UNCOV
4692

×
UNCOV
4693
        val, ok := typeMap[lnwire.FeeRecordType]
×
4694
        if ok && val == nil {
3✔
UNCOV
4695
                edge.InboundFee = fn.Some(inboundFee)
×
UNCOV
4696
        }
×
4697

4698
        return edge, nil
3✔
4699
}
3✔
UNCOV
4700

×
UNCOV
4701
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
×
4702
// KVStore and a kvdb.RTx.
3✔
4703
type chanGraphNodeTx struct {
3✔
4704
        tx   kvdb.RTx
3✔
UNCOV
4705
        db   *KVStore
×
UNCOV
4706
        node *models.LightningNode
×
4707
}
3✔
4708

3✔
4709
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
3✔
UNCOV
4710
// interface.
×
UNCOV
4711
var _ NodeRTx = (*chanGraphNodeTx)(nil)
×
4712

3✔
4713
func newChanGraphNodeTx(tx kvdb.RTx, db *KVStore,
3✔
4714
        node *models.LightningNode) *chanGraphNodeTx {
3✔
UNCOV
4715

×
UNCOV
4716
        return &chanGraphNodeTx{
×
4717
                tx:   tx,
4718
                db:   db,
4719
                node: node,
4720
        }
3✔
4721
}
3✔
4722

3✔
4723
// Node returns the raw information of the node.
3✔
UNCOV
4724
//
×
UNCOV
4725
// NOTE: This is a part of the NodeRTx interface.
×
UNCOV
4726
func (c *chanGraphNodeTx) Node() *models.LightningNode {
×
UNCOV
4727
        return c.node
×
4728
}
4729

4730
// FetchNode fetches the node with the given pub key under the same transaction
4731
// used to fetch the current node. The returned node is also a NodeRTx and any
6✔
4732
// operations on that NodeRTx will also be done under the same transaction.
3✔
4733
//
3✔
4734
// NOTE: This is a part of the NodeRTx interface.
3✔
4735
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
3✔
4736
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
3✔
4737
        if err != nil {
3✔
4738
                return nil, err
3✔
4739
        }
3✔
UNCOV
4740

×
4741
        return newChanGraphNodeTx(c.tx, c.db, node), nil
×
4742
}
4743

3✔
4744
// ForEachChannel can be used to iterate over the node's channels under
3✔
4745
// the same transaction used to fetch the node.
3✔
4746
//
3✔
4747
// NOTE: This is a part of the NodeRTx interface.
3✔
4748
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4749
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
4750

4751
        return c.db.forEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
4752
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
4753
                        policy2 *models.ChannelEdgePolicy) error {
4754

4755
                        return f(info, policy1, policy2)
3✔
4756
                },
3✔
4757
        )
3✔
UNCOV
4758
}
×
UNCOV
4759

×
4760
// MakeTestGraph creates a new instance of the ChannelGraph for testing
4761
// purposes.
3✔
4762
//
6✔
4763
// NOTE: this helper currently creates a ChannelGraph that is only ever backed
3✔
4764
// by the `KVStore` of the `V1Store` interface.
3✔
4765
func MakeTestGraph(t testing.TB, opts ...ChanGraphOption) *ChannelGraph {
4766
        t.Helper()
3✔
4767

4768
        // Next, create KVStore for the first time.
4769
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
4770
        t.Cleanup(backendCleanup)
4771
        require.NoError(t, err)
4772
        t.Cleanup(func() {
4773
                require.NoError(t, backend.Close())
4774
        })
4775

4776
        graphStore, err := NewKVStore(backend)
4777
        require.NoError(t, err)
4778

4779
        graph, err := NewChannelGraph(graphStore, opts...)
4780
        require.NoError(t, err)
4781
        require.NoError(t, graph.Start())
4782
        t.Cleanup(func() {
3✔
4783
                require.NoError(t, graph.Stop())
3✔
4784
        })
3✔
4785

3✔
4786
        return graph
3✔
4787
}
3✔
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