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

lightningnetwork / lnd / 13303171131

13 Feb 2025 08:10AM UTC coverage: 53.102% (+3.7%) from 49.366%
13303171131

Pull #9513

github

ellemouton
graph/db: unexport methods that take a transaction

Unexport and rename the methods that were previously used by the
graphsession package.
Pull Request #9513: graph+routing: refactor to remove `graphsession`

61 of 73 new or added lines in 7 files covered. (83.56%)

126 existing lines in 16 files now uncovered.

47503 of 89456 relevant lines covered (53.1%)

3.51 hits per line

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

68.07
/graph/db/graph.go
1
package graphdb
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

194
        chanScheduler batch.Scheduler
195
        nodeScheduler batch.Scheduler
196
}
197

198
// NewChannelGraph allocates a new ChannelGraph backed by a DB instance. The
199
// returned instance has its own unique reject cache and channel cache.
200
func NewChannelGraph(db kvdb.Backend, options ...OptionModifier) (*ChannelGraph,
201
        error) {
3✔
202

3✔
203
        opts := DefaultOptions()
3✔
204
        for _, o := range options {
6✔
205
                o(opts)
3✔
206
        }
3✔
207

208
        if !opts.NoMigration {
6✔
209
                if err := initChannelGraph(db); err != nil {
3✔
210
                        return nil, err
×
211
                }
×
212
        }
213

214
        g := &ChannelGraph{
3✔
215
                db:          db,
3✔
216
                rejectCache: newRejectCache(opts.RejectCacheSize),
3✔
217
                chanCache:   newChannelCache(opts.ChannelCacheSize),
3✔
218
        }
3✔
219
        g.chanScheduler = batch.NewTimeScheduler(
3✔
220
                db, &g.cacheMu, opts.BatchCommitInterval,
3✔
221
        )
3✔
222
        g.nodeScheduler = batch.NewTimeScheduler(
3✔
223
                db, nil, opts.BatchCommitInterval,
3✔
224
        )
3✔
225

3✔
226
        // The graph cache can be turned off (e.g. for mobile users) for a
3✔
227
        // speed/memory usage tradeoff.
3✔
228
        if opts.UseGraphCache {
6✔
229
                g.graphCache = NewGraphCache(opts.PreAllocCacheNumNodes)
3✔
230
                startTime := time.Now()
3✔
231
                log.Debugf("Populating in-memory channel graph, this might " +
3✔
232
                        "take a while...")
3✔
233

3✔
234
                err := g.ForEachNodeCacheable(func(node route.Vertex,
3✔
235
                        features *lnwire.FeatureVector) error {
6✔
236

3✔
237
                        g.graphCache.AddNodeFeatures(node, features)
3✔
238

3✔
239
                        return nil
3✔
240
                })
3✔
241
                if err != nil {
3✔
242
                        return nil, err
×
243
                }
×
244

245
                err = g.ForEachChannel(func(info *models.ChannelEdgeInfo,
3✔
246
                        policy1, policy2 *models.ChannelEdgePolicy) error {
6✔
247

3✔
248
                        g.graphCache.AddChannel(info, policy1, policy2)
3✔
249

3✔
250
                        return nil
3✔
251
                })
3✔
252
                if err != nil {
3✔
253
                        return nil, err
×
254
                }
×
255

256
                log.Debugf("Finished populating in-memory channel graph (took "+
3✔
257
                        "%v, %s)", time.Since(startTime), g.graphCache.Stats())
3✔
258
        }
259

260
        return g, nil
3✔
261
}
262

263
// channelMapKey is the key structure used for storing channel edge policies.
264
type channelMapKey struct {
265
        nodeKey route.Vertex
266
        chanID  [8]byte
267
}
268

269
// getChannelMap loads all channel edge policies from the database and stores
270
// them in a map.
271
func (c *ChannelGraph) getChannelMap(edges kvdb.RBucket) (
272
        map[channelMapKey]*models.ChannelEdgePolicy, error) {
3✔
273

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

3✔
277
        err := kvdb.ForAll(edges, func(k, edgeBytes []byte) error {
6✔
278
                // Skip embedded buckets.
3✔
279
                if bytes.Equal(k, edgeIndexBucket) ||
3✔
280
                        bytes.Equal(k, edgeUpdateIndexBucket) ||
3✔
281
                        bytes.Equal(k, zombieBucket) ||
3✔
282
                        bytes.Equal(k, disabledEdgePolicyBucket) ||
3✔
283
                        bytes.Equal(k, channelPointBucket) {
6✔
284

3✔
285
                        return nil
3✔
286
                }
3✔
287

288
                // Validate key length.
289
                if len(k) != 33+8 {
3✔
290
                        return fmt.Errorf("invalid edge key %x encountered", k)
×
291
                }
×
292

293
                var key channelMapKey
3✔
294
                copy(key.nodeKey[:], k[:33])
3✔
295
                copy(key.chanID[:], k[33:])
3✔
296

3✔
297
                // No need to deserialize unknown policy.
3✔
298
                if bytes.Equal(edgeBytes, unknownPolicy) {
3✔
299
                        return nil
×
300
                }
×
301

302
                edgeReader := bytes.NewReader(edgeBytes)
3✔
303
                edge, err := deserializeChanEdgePolicyRaw(
3✔
304
                        edgeReader,
3✔
305
                )
3✔
306

3✔
307
                switch {
3✔
308
                // If the db policy was missing an expected optional field, we
309
                // return nil as if the policy was unknown.
310
                case err == ErrEdgePolicyOptionalFieldNotFound:
×
311
                        return nil
×
312

313
                case err != nil:
×
314
                        return err
×
315
                }
316

317
                channelMap[key] = edge
3✔
318

3✔
319
                return nil
3✔
320
        })
321
        if err != nil {
3✔
322
                return nil, err
×
323
        }
×
324

325
        return channelMap, nil
3✔
326
}
327

328
var graphTopLevelBuckets = [][]byte{
329
        nodeBucket,
330
        edgeBucket,
331
        graphMetaBucket,
332
        closedScidBucket,
333
}
334

335
// Wipe completely deletes all saved state within all used buckets within the
336
// database. The deletion is done in a single transaction, therefore this
337
// operation is fully atomic.
338
func (c *ChannelGraph) Wipe() error {
×
339
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
340
                for _, tlb := range graphTopLevelBuckets {
×
341
                        err := tx.DeleteTopLevelBucket(tlb)
×
342
                        if err != nil && err != kvdb.ErrBucketNotFound {
×
343
                                return err
×
344
                        }
×
345
                }
346
                return nil
×
347
        }, func() {})
×
348
        if err != nil {
×
349
                return err
×
350
        }
×
351

352
        return initChannelGraph(c.db)
×
353
}
354

355
// createChannelDB creates and initializes a fresh version of  In
356
// the case that the target path has not yet been created or doesn't yet exist,
357
// then the path is created. Additionally, all required top-level buckets used
358
// within the database are created.
359
func initChannelGraph(db kvdb.Backend) error {
3✔
360
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
6✔
361
                for _, tlb := range graphTopLevelBuckets {
6✔
362
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
3✔
363
                                return err
×
364
                        }
×
365
                }
366

367
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
368
                _, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
3✔
369
                if err != nil {
3✔
370
                        return err
×
371
                }
×
372
                _, err = nodes.CreateBucketIfNotExists(nodeUpdateIndexBucket)
3✔
373
                if err != nil {
3✔
374
                        return err
×
375
                }
×
376

377
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
378
                _, err = edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
379
                if err != nil {
3✔
380
                        return err
×
381
                }
×
382
                _, err = edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
383
                if err != nil {
3✔
384
                        return err
×
385
                }
×
386
                _, err = edges.CreateBucketIfNotExists(channelPointBucket)
3✔
387
                if err != nil {
3✔
388
                        return err
×
389
                }
×
390
                _, err = edges.CreateBucketIfNotExists(zombieBucket)
3✔
391
                if err != nil {
3✔
392
                        return err
×
393
                }
×
394

395
                graphMeta := tx.ReadWriteBucket(graphMetaBucket)
3✔
396
                _, err = graphMeta.CreateBucketIfNotExists(pruneLogBucket)
3✔
397
                return err
3✔
398
        }, func() {})
3✔
399
        if err != nil {
3✔
400
                return fmt.Errorf("unable to create new channel graph: %w", err)
×
401
        }
×
402

403
        return nil
3✔
404
}
405

406
// AddrsForNode returns all known addresses for the target node public key that
407
// the graph DB is aware of. The returned boolean indicates if the given node is
408
// unknown to the graph DB or not.
409
//
410
// NOTE: this is part of the channeldb.AddrSource interface.
411
func (c *ChannelGraph) AddrsForNode(nodePub *btcec.PublicKey) (bool, []net.Addr,
412
        error) {
3✔
413

3✔
414
        pubKey, err := route.NewVertexFromBytes(nodePub.SerializeCompressed())
3✔
415
        if err != nil {
3✔
416
                return false, nil, err
×
417
        }
×
418

419
        node, err := c.FetchLightningNode(pubKey)
3✔
420
        // We don't consider it an error if the graph is unaware of the node.
3✔
421
        switch {
3✔
422
        case err != nil && !errors.Is(err, ErrGraphNodeNotFound):
×
423
                return false, nil, err
×
424

425
        case errors.Is(err, ErrGraphNodeNotFound):
3✔
426
                return false, nil, nil
3✔
427
        }
428

429
        return true, node.Addresses, nil
3✔
430
}
431

432
// ForEachChannel iterates through all the channel edges stored within the
433
// graph and invokes the passed callback for each edge. The callback takes two
434
// edges as since this is a directed graph, both the in/out edges are visited.
435
// If the callback returns an error, then the transaction is aborted and the
436
// iteration stops early.
437
//
438
// NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer
439
// for that particular channel edge routing policy will be passed into the
440
// callback.
441
func (c *ChannelGraph) ForEachChannel(cb func(*models.ChannelEdgeInfo,
442
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
3✔
443

3✔
444
        return c.db.View(func(tx kvdb.RTx) error {
6✔
445
                edges := tx.ReadBucket(edgeBucket)
3✔
446
                if edges == nil {
3✔
447
                        return ErrGraphNoEdgesFound
×
448
                }
×
449

450
                // First, load all edges in memory indexed by node and channel
451
                // id.
452
                channelMap, err := c.getChannelMap(edges)
3✔
453
                if err != nil {
3✔
454
                        return err
×
455
                }
×
456

457
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
458
                if edgeIndex == nil {
3✔
459
                        return ErrGraphNoEdgesFound
×
460
                }
×
461

462
                // Load edge index, recombine each channel with the policies
463
                // loaded above and invoke the callback.
464
                return kvdb.ForAll(
3✔
465
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
6✔
466
                                var chanID [8]byte
3✔
467
                                copy(chanID[:], k)
3✔
468

3✔
469
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
470
                                info, err := deserializeChanEdgeInfo(
3✔
471
                                        edgeInfoReader,
3✔
472
                                )
3✔
473
                                if err != nil {
3✔
474
                                        return err
×
475
                                }
×
476

477
                                policy1 := channelMap[channelMapKey{
3✔
478
                                        nodeKey: info.NodeKey1Bytes,
3✔
479
                                        chanID:  chanID,
3✔
480
                                }]
3✔
481

3✔
482
                                policy2 := channelMap[channelMapKey{
3✔
483
                                        nodeKey: info.NodeKey2Bytes,
3✔
484
                                        chanID:  chanID,
3✔
485
                                }]
3✔
486

3✔
487
                                return cb(&info, policy1, policy2)
3✔
488
                        },
489
                )
490
        }, func() {})
3✔
491
}
492

493
// forEachNodeDirectedChannel iterates through all channels of a given node,
494
// executing the passed callback on the directed edge representing the channel
495
// and its incoming policy. If the callback returns an error, then the iteration
496
// is halted with the error propagated back up to the caller. An optional read
497
// transaction may be provided. If none is provided, a new one will be created.
498
//
499
// Unknown policies are passed into the callback as nil values.
500
func (c *ChannelGraph) forEachNodeDirectedChannel(tx kvdb.RTx,
501
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
3✔
502

3✔
503
        if c.graphCache != nil {
6✔
504
                return c.graphCache.ForEachChannel(node, cb)
3✔
505
        }
3✔
506

507
        // Fallback that uses the database.
508
        toNodeCallback := func() route.Vertex {
6✔
509
                return node
3✔
510
        }
3✔
511
        toNodeFeatures, err := c.fetchNodeFeatures(tx, node)
3✔
512
        if err != nil {
3✔
513
                return err
×
514
        }
×
515

516
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
3✔
517
                p2 *models.ChannelEdgePolicy) error {
6✔
518

3✔
519
                var cachedInPolicy *models.CachedEdgePolicy
3✔
520
                if p2 != nil {
6✔
521
                        cachedInPolicy = models.NewCachedPolicy(p2)
3✔
522
                        cachedInPolicy.ToNodePubKey = toNodeCallback
3✔
523
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
3✔
524
                }
3✔
525

526
                var inboundFee lnwire.Fee
3✔
527
                if p1 != nil {
6✔
528
                        // Extract inbound fee. If there is a decoding error,
3✔
529
                        // skip this edge.
3✔
530
                        _, err := p1.ExtraOpaqueData.ExtractRecords(&inboundFee)
3✔
531
                        if err != nil {
3✔
532
                                return nil
×
533
                        }
×
534
                }
535

536
                directedChannel := &DirectedChannel{
3✔
537
                        ChannelID:    e.ChannelID,
3✔
538
                        IsNode1:      node == e.NodeKey1Bytes,
3✔
539
                        OtherNode:    e.NodeKey2Bytes,
3✔
540
                        Capacity:     e.Capacity,
3✔
541
                        OutPolicySet: p1 != nil,
3✔
542
                        InPolicy:     cachedInPolicy,
3✔
543
                        InboundFee:   inboundFee,
3✔
544
                }
3✔
545

3✔
546
                if node == e.NodeKey2Bytes {
6✔
547
                        directedChannel.OtherNode = e.NodeKey1Bytes
3✔
548
                }
3✔
549

550
                return cb(directedChannel)
3✔
551
        }
552
        return nodeTraversal(tx, node[:], c.db, dbCallback)
3✔
553
}
554

555
// fetchNodeFeatures returns the features of a given node. If no features are
556
// known for the node, an empty feature vector is returned. An optional read
557
// transaction may be provided. If none is provided, a new one will be created.
558
func (c *ChannelGraph) fetchNodeFeatures(tx kvdb.RTx,
559
        node route.Vertex) (*lnwire.FeatureVector, error) {
3✔
560

3✔
561
        if c.graphCache != nil {
6✔
562
                return c.graphCache.GetFeatures(node), nil
3✔
563
        }
3✔
564

565
        // Fallback that uses the database.
566
        targetNode, err := c.FetchLightningNodeTx(tx, node)
3✔
567
        switch err {
3✔
568
        // If the node exists and has features, return them directly.
569
        case nil:
3✔
570
                return targetNode.Features, nil
3✔
571

572
        // If we couldn't find a node announcement, populate a blank feature
573
        // vector.
574
        case ErrGraphNodeNotFound:
×
575
                return lnwire.EmptyFeatureVector(), nil
×
576

577
        // Otherwise, bubble the error up.
578
        default:
×
579
                return nil, err
×
580
        }
581
}
582

583
// ForEachNodeDirectedChannel iterates through all channels of a given node,
584
// executing the passed callback on the directed edge representing the channel
585
// and its incoming policy. If the callback returns an error, then the iteration
586
// is halted with the error propagated back up to the caller. If the graphCache
587
// is available, then it will be used to retrieve the node's channels instead
588
// of the database.
589
//
590
// Unknown policies are passed into the callback as nil values.
591
//
592
// NOTE: this is part of the graphdb.CachedGraph interface.
593
func (c *ChannelGraph) ForEachNodeDirectedChannel(nodePub route.Vertex,
594
        cb func(channel *DirectedChannel) error) error {
3✔
595

3✔
596
        return c.forEachNodeDirectedChannel(nil, nodePub, cb)
3✔
597
}
3✔
598

599
// FetchNodeFeatures returns the features of the given node. If no features are
600
// known for the node, an empty feature vector is returned.
601
// If the graphCache is available, then it will be used to retrieve the node's
602
// features instead of the database.
603
//
604
// NOTE: this is part of the graphdb.CachedGraph interface.
605
func (c *ChannelGraph) FetchNodeFeatures(nodePub route.Vertex) (
606
        *lnwire.FeatureVector, error) {
3✔
607

3✔
608
        return c.fetchNodeFeatures(nil, nodePub)
3✔
609
}
3✔
610

611
// ForEachNodeCached is similar to forEachNode, but it utilizes the channel
612
// graph cache instead. Note that this doesn't return all the information the
613
// regular forEachNode method does.
614
//
615
// NOTE: The callback contents MUST not be modified.
616
func (c *ChannelGraph) ForEachNodeCached(cb func(node route.Vertex,
617
        chans map[uint64]*DirectedChannel) error) error {
×
618

×
619
        if c.graphCache != nil {
×
620
                return c.graphCache.ForEachNode(cb)
×
621
        }
×
622

623
        // Otherwise call back to a version that uses the database directly.
624
        // We'll iterate over each node, then the set of channels for each
625
        // node, and construct a similar callback functiopn signature as the
626
        // main funcotin expects.
627
        return c.forEachNode(func(tx kvdb.RTx,
×
628
                node *models.LightningNode) error {
×
629

×
630
                channels := make(map[uint64]*DirectedChannel)
×
631

×
632
                err := c.ForEachNodeChannelTx(tx, node.PubKeyBytes,
×
633
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
×
634
                                p1 *models.ChannelEdgePolicy,
×
635
                                p2 *models.ChannelEdgePolicy) error {
×
636

×
637
                                toNodeCallback := func() route.Vertex {
×
638
                                        return node.PubKeyBytes
×
639
                                }
×
NEW
640
                                toNodeFeatures, err := c.fetchNodeFeatures(
×
NEW
641
                                        tx, node.PubKeyBytes,
×
642
                                )
×
643
                                if err != nil {
×
644
                                        return err
×
645
                                }
×
646

647
                                var cachedInPolicy *models.CachedEdgePolicy
×
648
                                if p2 != nil {
×
649
                                        cachedInPolicy =
×
650
                                                models.NewCachedPolicy(p2)
×
651
                                        cachedInPolicy.ToNodePubKey =
×
652
                                                toNodeCallback
×
653
                                        cachedInPolicy.ToNodeFeatures =
×
654
                                                toNodeFeatures
×
655
                                }
×
656

657
                                directedChannel := &DirectedChannel{
×
658
                                        ChannelID: e.ChannelID,
×
659
                                        IsNode1: node.PubKeyBytes ==
×
660
                                                e.NodeKey1Bytes,
×
661
                                        OtherNode:    e.NodeKey2Bytes,
×
662
                                        Capacity:     e.Capacity,
×
663
                                        OutPolicySet: p1 != nil,
×
664
                                        InPolicy:     cachedInPolicy,
×
665
                                }
×
666

×
667
                                if node.PubKeyBytes == e.NodeKey2Bytes {
×
668
                                        directedChannel.OtherNode =
×
669
                                                e.NodeKey1Bytes
×
670
                                }
×
671

672
                                channels[e.ChannelID] = directedChannel
×
673

×
674
                                return nil
×
675
                        })
676
                if err != nil {
×
677
                        return err
×
678
                }
×
679

680
                return cb(node.PubKeyBytes, channels)
×
681
        })
682
}
683

684
// DisabledChannelIDs returns the channel ids of disabled channels.
685
// A channel is disabled when two of the associated ChanelEdgePolicies
686
// have their disabled bit on.
687
func (c *ChannelGraph) DisabledChannelIDs() ([]uint64, error) {
×
688
        var disabledChanIDs []uint64
×
689
        var chanEdgeFound map[uint64]struct{}
×
690

×
691
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
692
                edges := tx.ReadBucket(edgeBucket)
×
693
                if edges == nil {
×
694
                        return ErrGraphNoEdgesFound
×
695
                }
×
696

697
                disabledEdgePolicyIndex := edges.NestedReadBucket(
×
698
                        disabledEdgePolicyBucket,
×
699
                )
×
700
                if disabledEdgePolicyIndex == nil {
×
701
                        return nil
×
702
                }
×
703

704
                // We iterate over all disabled policies and we add each channel
705
                // that has more than one disabled policy to disabledChanIDs
706
                // array.
707
                return disabledEdgePolicyIndex.ForEach(
×
708
                        func(k, v []byte) error {
×
709
                                chanID := byteOrder.Uint64(k[:8])
×
710
                                _, edgeFound := chanEdgeFound[chanID]
×
711
                                if edgeFound {
×
712
                                        delete(chanEdgeFound, chanID)
×
713
                                        disabledChanIDs = append(
×
714
                                                disabledChanIDs, chanID,
×
715
                                        )
×
716

×
717
                                        return nil
×
718
                                }
×
719

720
                                chanEdgeFound[chanID] = struct{}{}
×
721

×
722
                                return nil
×
723
                        },
724
                )
725
        }, func() {
×
726
                disabledChanIDs = nil
×
727
                chanEdgeFound = make(map[uint64]struct{})
×
728
        })
×
729
        if err != nil {
×
730
                return nil, err
×
731
        }
×
732

733
        return disabledChanIDs, nil
×
734
}
735

736
// ForEachNode iterates through all the stored vertices/nodes in the graph,
737
// executing the passed callback with each node encountered. If the callback
738
// returns an error, then the transaction is aborted and the iteration stops
739
// early. Any operations performed on the NodeTx passed to the call-back are
740
// executed under the same read transaction and so, methods on the NodeTx object
741
// _MUST_ only be called from within the call-back.
742
func (c *ChannelGraph) ForEachNode(cb func(tx NodeRTx) error) error {
3✔
743
        return c.forEachNode(func(tx kvdb.RTx,
3✔
744
                node *models.LightningNode) error {
6✔
745

3✔
746
                return cb(newChanGraphNodeTx(tx, c, node))
3✔
747
        })
3✔
748
}
749

750
// forEachNode iterates through all the stored vertices/nodes in the graph,
751
// executing the passed callback with each node encountered. If the callback
752
// returns an error, then the transaction is aborted and the iteration stops
753
// early.
754
//
755
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
756
// traversal when graph gets mega
757
func (c *ChannelGraph) forEachNode(
758
        cb func(kvdb.RTx, *models.LightningNode) error) error {
3✔
759

3✔
760
        traversal := func(tx kvdb.RTx) error {
6✔
761
                // First grab the nodes bucket which stores the mapping from
3✔
762
                // pubKey to node information.
3✔
763
                nodes := tx.ReadBucket(nodeBucket)
3✔
764
                if nodes == nil {
3✔
765
                        return ErrGraphNotFound
×
766
                }
×
767

768
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
769
                        // If this is the source key, then we skip this
3✔
770
                        // iteration as the value for this key is a pubKey
3✔
771
                        // rather than raw node information.
3✔
772
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
773
                                return nil
3✔
774
                        }
3✔
775

776
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
777
                        node, err := deserializeLightningNode(nodeReader)
3✔
778
                        if err != nil {
3✔
779
                                return err
×
780
                        }
×
781

782
                        // Execute the callback, the transaction will abort if
783
                        // this returns an error.
784
                        return cb(tx, &node)
3✔
785
                })
786
        }
787

788
        return kvdb.View(c.db, traversal, func() {})
6✔
789
}
790

791
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
792
// graph, executing the passed callback with each node encountered. If the
793
// callback returns an error, then the transaction is aborted and the iteration
794
// stops early.
795
func (c *ChannelGraph) ForEachNodeCacheable(cb func(route.Vertex,
796
        *lnwire.FeatureVector) error) error {
3✔
797

3✔
798
        traversal := func(tx kvdb.RTx) error {
6✔
799
                // First grab the nodes bucket which stores the mapping from
3✔
800
                // pubKey to node information.
3✔
801
                nodes := tx.ReadBucket(nodeBucket)
3✔
802
                if nodes == nil {
3✔
803
                        return ErrGraphNotFound
×
804
                }
×
805

806
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
807
                        // If this is the source key, then we skip this
3✔
808
                        // iteration as the value for this key is a pubKey
3✔
809
                        // rather than raw node information.
3✔
810
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
811
                                return nil
3✔
812
                        }
3✔
813

814
                        nodeReader := bytes.NewReader(nodeBytes)
3✔
815
                        node, features, err := deserializeLightningNodeCacheable( //nolint:ll
3✔
816
                                nodeReader,
3✔
817
                        )
3✔
818
                        if err != nil {
3✔
819
                                return err
×
820
                        }
×
821

822
                        // Execute the callback, the transaction will abort if
823
                        // this returns an error.
824
                        return cb(node, features)
3✔
825
                })
826
        }
827

828
        return kvdb.View(c.db, traversal, func() {})
6✔
829
}
830

831
// SourceNode returns the source node of the graph. The source node is treated
832
// as the center node within a star-graph. This method may be used to kick off
833
// a path finding algorithm in order to explore the reachability of another
834
// node based off the source node.
835
func (c *ChannelGraph) SourceNode() (*models.LightningNode, error) {
3✔
836
        var source *models.LightningNode
3✔
837
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
838
                // First grab the nodes bucket which stores the mapping from
3✔
839
                // pubKey to node information.
3✔
840
                nodes := tx.ReadBucket(nodeBucket)
3✔
841
                if nodes == nil {
3✔
842
                        return ErrGraphNotFound
×
843
                }
×
844

845
                node, err := c.sourceNode(nodes)
3✔
846
                if err != nil {
3✔
847
                        return err
×
848
                }
×
849
                source = node
3✔
850

3✔
851
                return nil
3✔
852
        }, func() {
3✔
853
                source = nil
3✔
854
        })
3✔
855
        if err != nil {
3✔
856
                return nil, err
×
857
        }
×
858

859
        return source, nil
3✔
860
}
861

862
// sourceNode uses an existing database transaction and returns the source node
863
// of the graph. The source node is treated as the center node within a
864
// star-graph. This method may be used to kick off a path finding algorithm in
865
// order to explore the reachability of another node based off the source node.
866
func (c *ChannelGraph) sourceNode(nodes kvdb.RBucket) (*models.LightningNode,
867
        error) {
3✔
868

3✔
869
        selfPub := nodes.Get(sourceKey)
3✔
870
        if selfPub == nil {
3✔
871
                return nil, ErrSourceNodeNotSet
×
872
        }
×
873

874
        // With the pubKey of the source node retrieved, we're able to
875
        // fetch the full node information.
876
        node, err := fetchLightningNode(nodes, selfPub)
3✔
877
        if err != nil {
3✔
878
                return nil, err
×
879
        }
×
880

881
        return &node, nil
3✔
882
}
883

884
// SetSourceNode sets the source node within the graph database. The source
885
// node is to be used as the center of a star-graph within path finding
886
// algorithms.
887
func (c *ChannelGraph) SetSourceNode(node *models.LightningNode) error {
3✔
888
        nodePubBytes := node.PubKeyBytes[:]
3✔
889

3✔
890
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
891
                // First grab the nodes bucket which stores the mapping from
3✔
892
                // pubKey to node information.
3✔
893
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
894
                if err != nil {
3✔
895
                        return err
×
896
                }
×
897

898
                // Next we create the mapping from source to the targeted
899
                // public key.
900
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
3✔
901
                        return err
×
902
                }
×
903

904
                // Finally, we commit the information of the lightning node
905
                // itself.
906
                return addLightningNode(tx, node)
3✔
907
        }, func() {})
3✔
908
}
909

910
// AddLightningNode adds a vertex/node to the graph database. If the node is not
911
// in the database from before, this will add a new, unconnected one to the
912
// graph. If it is present from before, this will update that node's
913
// information. Note that this method is expected to only be called to update an
914
// already present node from a node announcement, or to insert a node found in a
915
// channel update.
916
//
917
// TODO(roasbeef): also need sig of announcement
918
func (c *ChannelGraph) AddLightningNode(node *models.LightningNode,
919
        op ...batch.SchedulerOption) error {
3✔
920

3✔
921
        r := &batch.Request{
3✔
922
                Update: func(tx kvdb.RwTx) error {
6✔
923
                        if c.graphCache != nil {
6✔
924
                                c.graphCache.AddNodeFeatures(
3✔
925
                                        node.PubKeyBytes, node.Features,
3✔
926
                                )
3✔
927
                        }
3✔
928

929
                        return addLightningNode(tx, node)
3✔
930
                },
931
        }
932

933
        for _, f := range op {
6✔
934
                f(r)
3✔
935
        }
3✔
936

937
        return c.nodeScheduler.Execute(r)
3✔
938
}
939

940
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
3✔
941
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
942
        if err != nil {
3✔
943
                return err
×
944
        }
×
945

946
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
3✔
947
        if err != nil {
3✔
948
                return err
×
949
        }
×
950

951
        updateIndex, err := nodes.CreateBucketIfNotExists(
3✔
952
                nodeUpdateIndexBucket,
3✔
953
        )
3✔
954
        if err != nil {
3✔
955
                return err
×
956
        }
×
957

958
        return putLightningNode(nodes, aliases, updateIndex, node)
3✔
959
}
960

961
// LookupAlias attempts to return the alias as advertised by the target node.
962
// TODO(roasbeef): currently assumes that aliases are unique...
963
func (c *ChannelGraph) LookupAlias(pub *btcec.PublicKey) (string, error) {
3✔
964
        var alias string
3✔
965

3✔
966
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
967
                nodes := tx.ReadBucket(nodeBucket)
3✔
968
                if nodes == nil {
3✔
969
                        return ErrGraphNodesNotFound
×
970
                }
×
971

972
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
3✔
973
                if aliases == nil {
3✔
974
                        return ErrGraphNodesNotFound
×
975
                }
×
976

977
                nodePub := pub.SerializeCompressed()
3✔
978
                a := aliases.Get(nodePub)
3✔
979
                if a == nil {
3✔
980
                        return ErrNodeAliasNotFound
×
981
                }
×
982

983
                // TODO(roasbeef): should actually be using the utf-8
984
                // package...
985
                alias = string(a)
3✔
986
                return nil
3✔
987
        }, func() {
3✔
988
                alias = ""
3✔
989
        })
3✔
990
        if err != nil {
3✔
991
                return "", err
×
992
        }
×
993

994
        return alias, nil
3✔
995
}
996

997
// DeleteLightningNode starts a new database transaction to remove a vertex/node
998
// from the database according to the node's public key.
999
func (c *ChannelGraph) DeleteLightningNode(nodePub route.Vertex) error {
×
1000
        // TODO(roasbeef): ensure dangling edges are removed...
×
1001
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
1002
                nodes := tx.ReadWriteBucket(nodeBucket)
×
1003
                if nodes == nil {
×
1004
                        return ErrGraphNodeNotFound
×
1005
                }
×
1006

1007
                if c.graphCache != nil {
×
1008
                        c.graphCache.RemoveNode(nodePub)
×
1009
                }
×
1010

1011
                return c.deleteLightningNode(nodes, nodePub[:])
×
1012
        }, func() {})
×
1013
}
1014

1015
// deleteLightningNode uses an existing database transaction to remove a
1016
// vertex/node from the database according to the node's public key.
1017
func (c *ChannelGraph) deleteLightningNode(nodes kvdb.RwBucket,
1018
        compressedPubKey []byte) error {
3✔
1019

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

1025
        if err := aliases.Delete(compressedPubKey); err != nil {
3✔
1026
                return err
×
1027
        }
×
1028

1029
        // Before we delete the node, we'll fetch its current state so we can
1030
        // determine when its last update was to clear out the node update
1031
        // index.
1032
        node, err := fetchLightningNode(nodes, compressedPubKey)
3✔
1033
        if err != nil {
3✔
1034
                return err
×
1035
        }
×
1036

1037
        if err := nodes.Delete(compressedPubKey); err != nil {
3✔
1038
                return err
×
1039
        }
×
1040

1041
        // Finally, we'll delete the index entry for the node within the
1042
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
1043
        // need to track its last update.
1044
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
3✔
1045
        if nodeUpdateIndex == nil {
3✔
1046
                return ErrGraphNodesNotFound
×
1047
        }
×
1048

1049
        // In order to delete the entry, we'll need to reconstruct the key for
1050
        // its last update.
1051
        updateUnix := uint64(node.LastUpdate.Unix())
3✔
1052
        var indexKey [8 + 33]byte
3✔
1053
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
1054
        copy(indexKey[8:], compressedPubKey)
3✔
1055

3✔
1056
        return nodeUpdateIndex.Delete(indexKey[:])
3✔
1057
}
1058

1059
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
1060
// undirected edge from the two target nodes are created. The information stored
1061
// denotes the static attributes of the channel, such as the channelID, the keys
1062
// involved in creation of the channel, and the set of features that the channel
1063
// supports. The chanPoint and chanID are used to uniquely identify the edge
1064
// globally within the database.
1065
func (c *ChannelGraph) AddChannelEdge(edge *models.ChannelEdgeInfo,
1066
        op ...batch.SchedulerOption) error {
3✔
1067

3✔
1068
        var alreadyExists bool
3✔
1069
        r := &batch.Request{
3✔
1070
                Reset: func() {
6✔
1071
                        alreadyExists = false
3✔
1072
                },
3✔
1073
                Update: func(tx kvdb.RwTx) error {
3✔
1074
                        err := c.addChannelEdge(tx, edge)
3✔
1075

3✔
1076
                        // Silence ErrEdgeAlreadyExist so that the batch can
3✔
1077
                        // succeed, but propagate the error via local state.
3✔
1078
                        if err == ErrEdgeAlreadyExist {
3✔
1079
                                alreadyExists = true
×
1080
                                return nil
×
1081
                        }
×
1082

1083
                        return err
3✔
1084
                },
1085
                OnCommit: func(err error) error {
3✔
1086
                        switch {
3✔
1087
                        case err != nil:
×
1088
                                return err
×
1089
                        case alreadyExists:
×
1090
                                return ErrEdgeAlreadyExist
×
1091
                        default:
3✔
1092
                                c.rejectCache.remove(edge.ChannelID)
3✔
1093
                                c.chanCache.remove(edge.ChannelID)
3✔
1094
                                return nil
3✔
1095
                        }
1096
                },
1097
        }
1098

1099
        for _, f := range op {
6✔
1100
                if f == nil {
3✔
1101
                        return fmt.Errorf("nil scheduler option was used")
×
1102
                }
×
1103

1104
                f(r)
3✔
1105
        }
1106

1107
        return c.chanScheduler.Execute(r)
3✔
1108
}
1109

1110
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1111
// utilize an existing db transaction.
1112
func (c *ChannelGraph) addChannelEdge(tx kvdb.RwTx,
1113
        edge *models.ChannelEdgeInfo) error {
3✔
1114

3✔
1115
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1116
        var chanKey [8]byte
3✔
1117
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1118

3✔
1119
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
1120
        if err != nil {
3✔
1121
                return err
×
1122
        }
×
1123
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1124
        if err != nil {
3✔
1125
                return err
×
1126
        }
×
1127
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1128
        if err != nil {
3✔
1129
                return err
×
1130
        }
×
1131
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
3✔
1132
        if err != nil {
3✔
1133
                return err
×
1134
        }
×
1135

1136
        // First, attempt to check if this edge has already been created. If
1137
        // so, then we can exit early as this method is meant to be idempotent.
1138
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
3✔
1139
                return ErrEdgeAlreadyExist
×
1140
        }
×
1141

1142
        if c.graphCache != nil {
6✔
1143
                c.graphCache.AddChannel(edge, nil, nil)
3✔
1144
        }
3✔
1145

1146
        // Before we insert the channel into the database, we'll ensure that
1147
        // both nodes already exist in the channel graph. If either node
1148
        // doesn't, then we'll insert a "shell" node that just includes its
1149
        // public key, so subsequent validation and queries can work properly.
1150
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
3✔
1151
        switch {
3✔
1152
        case node1Err == ErrGraphNodeNotFound:
3✔
1153
                node1Shell := models.LightningNode{
3✔
1154
                        PubKeyBytes:          edge.NodeKey1Bytes,
3✔
1155
                        HaveNodeAnnouncement: false,
3✔
1156
                }
3✔
1157
                err := addLightningNode(tx, &node1Shell)
3✔
1158
                if err != nil {
3✔
1159
                        return fmt.Errorf("unable to create shell node "+
×
1160
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1161
                }
×
1162
        case node1Err != nil:
×
1163
                return node1Err
×
1164
        }
1165

1166
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
3✔
1167
        switch {
3✔
1168
        case node2Err == ErrGraphNodeNotFound:
3✔
1169
                node2Shell := models.LightningNode{
3✔
1170
                        PubKeyBytes:          edge.NodeKey2Bytes,
3✔
1171
                        HaveNodeAnnouncement: false,
3✔
1172
                }
3✔
1173
                err := addLightningNode(tx, &node2Shell)
3✔
1174
                if err != nil {
3✔
1175
                        return fmt.Errorf("unable to create shell node "+
×
1176
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
1177
                }
×
1178
        case node2Err != nil:
×
1179
                return node2Err
×
1180
        }
1181

1182
        // If the edge hasn't been created yet, then we'll first add it to the
1183
        // edge index in order to associate the edge between two nodes and also
1184
        // store the static components of the channel.
1185
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
3✔
1186
                return err
×
1187
        }
×
1188

1189
        // Mark edge policies for both sides as unknown. This is to enable
1190
        // efficient incoming channel lookup for a node.
1191
        keys := []*[33]byte{
3✔
1192
                &edge.NodeKey1Bytes,
3✔
1193
                &edge.NodeKey2Bytes,
3✔
1194
        }
3✔
1195
        for _, key := range keys {
6✔
1196
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
3✔
1197
                if err != nil {
3✔
1198
                        return err
×
1199
                }
×
1200
        }
1201

1202
        // Finally we add it to the channel index which maps channel points
1203
        // (outpoints) to the shorter channel ID's.
1204
        var b bytes.Buffer
3✔
1205
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
3✔
1206
                return err
×
1207
        }
×
1208
        return chanIndex.Put(b.Bytes(), chanKey[:])
3✔
1209
}
1210

1211
// HasChannelEdge returns true if the database knows of a channel edge with the
1212
// passed channel ID, and false otherwise. If an edge with that ID is found
1213
// within the graph, then two time stamps representing the last time the edge
1214
// was updated for both directed edges are returned along with the boolean. If
1215
// it is not found, then the zombie index is checked and its result is returned
1216
// as the second boolean.
1217
func (c *ChannelGraph) HasChannelEdge(
1218
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
3✔
1219

3✔
1220
        var (
3✔
1221
                upd1Time time.Time
3✔
1222
                upd2Time time.Time
3✔
1223
                exists   bool
3✔
1224
                isZombie bool
3✔
1225
        )
3✔
1226

3✔
1227
        // We'll query the cache with the shared lock held to allow multiple
3✔
1228
        // readers to access values in the cache concurrently if they exist.
3✔
1229
        c.cacheMu.RLock()
3✔
1230
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1231
                c.cacheMu.RUnlock()
3✔
1232
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1233
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1234
                exists, isZombie = entry.flags.unpack()
3✔
1235
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1236
        }
3✔
1237
        c.cacheMu.RUnlock()
3✔
1238

3✔
1239
        c.cacheMu.Lock()
3✔
1240
        defer c.cacheMu.Unlock()
3✔
1241

3✔
1242
        // The item was not found with the shared lock, so we'll acquire the
3✔
1243
        // exclusive lock and check the cache again in case another method added
3✔
1244
        // the entry to the cache while no lock was held.
3✔
1245
        if entry, ok := c.rejectCache.get(chanID); ok {
6✔
1246
                upd1Time = time.Unix(entry.upd1Time, 0)
3✔
1247
                upd2Time = time.Unix(entry.upd2Time, 0)
3✔
1248
                exists, isZombie = entry.flags.unpack()
3✔
1249
                return upd1Time, upd2Time, exists, isZombie, nil
3✔
1250
        }
3✔
1251

1252
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1253
                edges := tx.ReadBucket(edgeBucket)
3✔
1254
                if edges == nil {
3✔
1255
                        return ErrGraphNoEdgesFound
×
1256
                }
×
1257
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1258
                if edgeIndex == nil {
3✔
1259
                        return ErrGraphNoEdgesFound
×
1260
                }
×
1261

1262
                var channelID [8]byte
3✔
1263
                byteOrder.PutUint64(channelID[:], chanID)
3✔
1264

3✔
1265
                // If the edge doesn't exist, then we'll also check our zombie
3✔
1266
                // index.
3✔
1267
                if edgeIndex.Get(channelID[:]) == nil {
6✔
1268
                        exists = false
3✔
1269
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
1270
                        if zombieIndex != nil {
6✔
1271
                                isZombie, _, _ = isZombieEdge(
3✔
1272
                                        zombieIndex, chanID,
3✔
1273
                                )
3✔
1274
                        }
3✔
1275

1276
                        return nil
3✔
1277
                }
1278

1279
                exists = true
3✔
1280
                isZombie = false
3✔
1281

3✔
1282
                // If the channel has been found in the graph, then retrieve
3✔
1283
                // the edges itself so we can return the last updated
3✔
1284
                // timestamps.
3✔
1285
                nodes := tx.ReadBucket(nodeBucket)
3✔
1286
                if nodes == nil {
3✔
1287
                        return ErrGraphNodeNotFound
×
1288
                }
×
1289

1290
                e1, e2, err := fetchChanEdgePolicies(
3✔
1291
                        edgeIndex, edges, channelID[:],
3✔
1292
                )
3✔
1293
                if err != nil {
3✔
1294
                        return err
×
1295
                }
×
1296

1297
                // As we may have only one of the edges populated, only set the
1298
                // update time if the edge was found in the database.
1299
                if e1 != nil {
6✔
1300
                        upd1Time = e1.LastUpdate
3✔
1301
                }
3✔
1302
                if e2 != nil {
6✔
1303
                        upd2Time = e2.LastUpdate
3✔
1304
                }
3✔
1305

1306
                return nil
3✔
1307
        }, func() {}); err != nil {
3✔
1308
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1309
        }
×
1310

1311
        c.rejectCache.insert(chanID, rejectCacheEntry{
3✔
1312
                upd1Time: upd1Time.Unix(),
3✔
1313
                upd2Time: upd2Time.Unix(),
3✔
1314
                flags:    packRejectFlags(exists, isZombie),
3✔
1315
        })
3✔
1316

3✔
1317
        return upd1Time, upd2Time, exists, isZombie, nil
3✔
1318
}
1319

1320
// UpdateChannelEdge retrieves and update edge of the graph database. Method
1321
// only reserved for updating an edge info after its already been created.
1322
// In order to maintain this constraints, we return an error in the scenario
1323
// that an edge info hasn't yet been created yet, but someone attempts to update
1324
// it.
1325
func (c *ChannelGraph) UpdateChannelEdge(edge *models.ChannelEdgeInfo) error {
3✔
1326
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1327
        var chanKey [8]byte
3✔
1328
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1329

3✔
1330
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1331
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1332
                if edge == nil {
3✔
1333
                        return ErrEdgeNotFound
×
1334
                }
×
1335

1336
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1337
                if edgeIndex == nil {
3✔
1338
                        return ErrEdgeNotFound
×
1339
                }
×
1340

1341
                if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo == nil {
3✔
1342
                        return ErrEdgeNotFound
×
1343
                }
×
1344

1345
                if c.graphCache != nil {
6✔
1346
                        c.graphCache.UpdateChannel(edge)
3✔
1347
                }
3✔
1348

1349
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
3✔
1350
        }, func() {})
3✔
1351
}
1352

1353
const (
1354
        // pruneTipBytes is the total size of the value which stores a prune
1355
        // entry of the graph in the prune log. The "prune tip" is the last
1356
        // entry in the prune log, and indicates if the channel graph is in
1357
        // sync with the current UTXO state. The structure of the value
1358
        // is: blockHash, taking 32 bytes total.
1359
        pruneTipBytes = 32
1360
)
1361

1362
// PruneGraph prunes newly closed channels from the channel graph in response
1363
// to a new block being solved on the network. Any transactions which spend the
1364
// funding output of any known channels within he graph will be deleted.
1365
// Additionally, the "prune tip", or the last block which has been used to
1366
// prune the graph is stored so callers can ensure the graph is fully in sync
1367
// with the current UTXO state. A slice of channels that have been closed by
1368
// the target block are returned if the function succeeds without error.
1369
func (c *ChannelGraph) PruneGraph(spentOutputs []*wire.OutPoint,
1370
        blockHash *chainhash.Hash, blockHeight uint32) (
1371
        []*models.ChannelEdgeInfo, error) {
3✔
1372

3✔
1373
        c.cacheMu.Lock()
3✔
1374
        defer c.cacheMu.Unlock()
3✔
1375

3✔
1376
        var chansClosed []*models.ChannelEdgeInfo
3✔
1377

3✔
1378
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1379
                // First grab the edges bucket which houses the information
3✔
1380
                // we'd like to delete
3✔
1381
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1382
                if err != nil {
3✔
1383
                        return err
×
1384
                }
×
1385

1386
                // Next grab the two edge indexes which will also need to be
1387
                // updated.
1388
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1389
                if err != nil {
3✔
1390
                        return err
×
1391
                }
×
1392
                chanIndex, err := edges.CreateBucketIfNotExists(
3✔
1393
                        channelPointBucket,
3✔
1394
                )
3✔
1395
                if err != nil {
3✔
1396
                        return err
×
1397
                }
×
1398
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1399
                if nodes == nil {
3✔
1400
                        return ErrSourceNodeNotSet
×
1401
                }
×
1402
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1403
                if err != nil {
3✔
1404
                        return err
×
1405
                }
×
1406

1407
                // For each of the outpoints that have been spent within the
1408
                // block, we attempt to delete them from the graph as if that
1409
                // outpoint was a channel, then it has now been closed.
1410
                for _, chanPoint := range spentOutputs {
6✔
1411
                        // TODO(roasbeef): load channel bloom filter, continue
3✔
1412
                        // if NOT if filter
3✔
1413

3✔
1414
                        var opBytes bytes.Buffer
3✔
1415
                        err := WriteOutpoint(&opBytes, chanPoint)
3✔
1416
                        if err != nil {
3✔
1417
                                return err
×
1418
                        }
×
1419

1420
                        // First attempt to see if the channel exists within
1421
                        // the database, if not, then we can exit early.
1422
                        chanID := chanIndex.Get(opBytes.Bytes())
3✔
1423
                        if chanID == nil {
3✔
1424
                                continue
×
1425
                        }
1426

1427
                        // However, if it does, then we'll read out the full
1428
                        // version so we can add it to the set of deleted
1429
                        // channels.
1430
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
1431
                        if err != nil {
3✔
1432
                                return err
×
1433
                        }
×
1434

1435
                        // Attempt to delete the channel, an ErrEdgeNotFound
1436
                        // will be returned if that outpoint isn't known to be
1437
                        // a channel. If no error is returned, then a channel
1438
                        // was successfully pruned.
1439
                        err = c.delChannelEdgeUnsafe(
3✔
1440
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1441
                                chanID, false, false,
3✔
1442
                        )
3✔
1443
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
3✔
1444
                                return err
×
1445
                        }
×
1446

1447
                        chansClosed = append(chansClosed, &edgeInfo)
3✔
1448
                }
1449

1450
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
3✔
1451
                if err != nil {
3✔
1452
                        return err
×
1453
                }
×
1454

1455
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
3✔
1456
                        pruneLogBucket,
3✔
1457
                )
3✔
1458
                if err != nil {
3✔
1459
                        return err
×
1460
                }
×
1461

1462
                // With the graph pruned, add a new entry to the prune log,
1463
                // which can be used to check if the graph is fully synced with
1464
                // the current UTXO state.
1465
                var blockHeightBytes [4]byte
3✔
1466
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
3✔
1467

3✔
1468
                var newTip [pruneTipBytes]byte
3✔
1469
                copy(newTip[:], blockHash[:])
3✔
1470

3✔
1471
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
3✔
1472
                if err != nil {
3✔
1473
                        return err
×
1474
                }
×
1475

1476
                // Now that the graph has been pruned, we'll also attempt to
1477
                // prune any nodes that have had a channel closed within the
1478
                // latest block.
1479
                return c.pruneGraphNodes(nodes, edgeIndex)
3✔
1480
        }, func() {
3✔
1481
                chansClosed = nil
3✔
1482
        })
3✔
1483
        if err != nil {
3✔
1484
                return nil, err
×
1485
        }
×
1486

1487
        for _, channel := range chansClosed {
6✔
1488
                c.rejectCache.remove(channel.ChannelID)
3✔
1489
                c.chanCache.remove(channel.ChannelID)
3✔
1490
        }
3✔
1491

1492
        if c.graphCache != nil {
6✔
1493
                log.Debugf("Pruned graph, cache now has %s",
3✔
1494
                        c.graphCache.Stats())
3✔
1495
        }
3✔
1496

1497
        return chansClosed, nil
3✔
1498
}
1499

1500
// PruneGraphNodes is a garbage collection method which attempts to prune out
1501
// any nodes from the channel graph that are currently unconnected. This ensure
1502
// that we only maintain a graph of reachable nodes. In the event that a pruned
1503
// node gains more channels, it will be re-added back to the graph.
1504
func (c *ChannelGraph) PruneGraphNodes() error {
3✔
1505
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1506
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1507
                if nodes == nil {
3✔
1508
                        return ErrGraphNodesNotFound
×
1509
                }
×
1510
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1511
                if edges == nil {
3✔
1512
                        return ErrGraphNotFound
×
1513
                }
×
1514
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1515
                if edgeIndex == nil {
3✔
1516
                        return ErrGraphNoEdgesFound
×
1517
                }
×
1518

1519
                return c.pruneGraphNodes(nodes, edgeIndex)
3✔
1520
        }, func() {})
3✔
1521
}
1522

1523
// pruneGraphNodes attempts to remove any nodes from the graph who have had a
1524
// channel closed within the current block. If the node still has existing
1525
// channels in the graph, this will act as a no-op.
1526
func (c *ChannelGraph) pruneGraphNodes(nodes kvdb.RwBucket,
1527
        edgeIndex kvdb.RwBucket) error {
3✔
1528

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

3✔
1531
        // We'll retrieve the graph's source node to ensure we don't remove it
3✔
1532
        // even if it no longer has any open channels.
3✔
1533
        sourceNode, err := c.sourceNode(nodes)
3✔
1534
        if err != nil {
3✔
1535
                return err
×
1536
        }
×
1537

1538
        // We'll use this map to keep count the number of references to a node
1539
        // in the graph. A node should only be removed once it has no more
1540
        // references in the graph.
1541
        nodeRefCounts := make(map[[33]byte]int)
3✔
1542
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
1543
                // If this is the source key, then we skip this
3✔
1544
                // iteration as the value for this key is a pubKey
3✔
1545
                // rather than raw node information.
3✔
1546
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
1547
                        return nil
3✔
1548
                }
3✔
1549

1550
                var nodePub [33]byte
3✔
1551
                copy(nodePub[:], pubKey)
3✔
1552
                nodeRefCounts[nodePub] = 0
3✔
1553

3✔
1554
                return nil
3✔
1555
        })
1556
        if err != nil {
3✔
1557
                return err
×
1558
        }
×
1559

1560
        // To ensure we never delete the source node, we'll start off by
1561
        // bumping its ref count to 1.
1562
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
3✔
1563

3✔
1564
        // Next, we'll run through the edgeIndex which maps a channel ID to the
3✔
1565
        // edge info. We'll use this scan to populate our reference count map
3✔
1566
        // above.
3✔
1567
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
6✔
1568
                // The first 66 bytes of the edge info contain the pubkeys of
3✔
1569
                // the nodes that this edge attaches. We'll extract them, and
3✔
1570
                // add them to the ref count map.
3✔
1571
                var node1, node2 [33]byte
3✔
1572
                copy(node1[:], edgeInfoBytes[:33])
3✔
1573
                copy(node2[:], edgeInfoBytes[33:])
3✔
1574

3✔
1575
                // With the nodes extracted, we'll increase the ref count of
3✔
1576
                // each of the nodes.
3✔
1577
                nodeRefCounts[node1]++
3✔
1578
                nodeRefCounts[node2]++
3✔
1579

3✔
1580
                return nil
3✔
1581
        })
3✔
1582
        if err != nil {
3✔
1583
                return err
×
1584
        }
×
1585

1586
        // Finally, we'll make a second pass over the set of nodes, and delete
1587
        // any nodes that have a ref count of zero.
1588
        var numNodesPruned int
3✔
1589
        for nodePubKey, refCount := range nodeRefCounts {
6✔
1590
                // If the ref count of the node isn't zero, then we can safely
3✔
1591
                // skip it as it still has edges to or from it within the
3✔
1592
                // graph.
3✔
1593
                if refCount != 0 {
6✔
1594
                        continue
3✔
1595
                }
1596

1597
                if c.graphCache != nil {
6✔
1598
                        c.graphCache.RemoveNode(nodePubKey)
3✔
1599
                }
3✔
1600

1601
                // If we reach this point, then there are no longer any edges
1602
                // that connect this node, so we can delete it.
1603
                err := c.deleteLightningNode(nodes, nodePubKey[:])
3✔
1604
                if err != nil {
3✔
1605
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1606
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1607

×
1608
                                log.Warnf("Unable to prune node %x from the "+
×
1609
                                        "graph: %v", nodePubKey, err)
×
1610
                                continue
×
1611
                        }
1612

1613
                        return err
×
1614
                }
1615

1616
                log.Infof("Pruned unconnected node %x from channel graph",
3✔
1617
                        nodePubKey[:])
3✔
1618

3✔
1619
                numNodesPruned++
3✔
1620
        }
1621

1622
        if numNodesPruned > 0 {
6✔
1623
                log.Infof("Pruned %v unconnected nodes from the channel graph",
3✔
1624
                        numNodesPruned)
3✔
1625
        }
3✔
1626

1627
        return nil
3✔
1628
}
1629

1630
// DisconnectBlockAtHeight is used to indicate that the block specified
1631
// by the passed height has been disconnected from the main chain. This
1632
// will "rewind" the graph back to the height below, deleting channels
1633
// that are no longer confirmed from the graph. The prune log will be
1634
// set to the last prune height valid for the remaining chain.
1635
// Channels that were removed from the graph resulting from the
1636
// disconnected block are returned.
1637
func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) (
1638
        []*models.ChannelEdgeInfo, error) {
2✔
1639

2✔
1640
        // Every channel having a ShortChannelID starting at 'height'
2✔
1641
        // will no longer be confirmed.
2✔
1642
        startShortChanID := lnwire.ShortChannelID{
2✔
1643
                BlockHeight: height,
2✔
1644
        }
2✔
1645

2✔
1646
        // Delete everything after this height from the db up until the
2✔
1647
        // SCID alias range.
2✔
1648
        endShortChanID := aliasmgr.StartingAlias
2✔
1649

2✔
1650
        // The block height will be the 3 first bytes of the channel IDs.
2✔
1651
        var chanIDStart [8]byte
2✔
1652
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
2✔
1653
        var chanIDEnd [8]byte
2✔
1654
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
2✔
1655

2✔
1656
        c.cacheMu.Lock()
2✔
1657
        defer c.cacheMu.Unlock()
2✔
1658

2✔
1659
        // Keep track of the channels that are removed from the graph.
2✔
1660
        var removedChans []*models.ChannelEdgeInfo
2✔
1661

2✔
1662
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
4✔
1663
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
2✔
1664
                if err != nil {
2✔
1665
                        return err
×
1666
                }
×
1667
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
2✔
1668
                if err != nil {
2✔
1669
                        return err
×
1670
                }
×
1671
                chanIndex, err := edges.CreateBucketIfNotExists(
2✔
1672
                        channelPointBucket,
2✔
1673
                )
2✔
1674
                if err != nil {
2✔
1675
                        return err
×
1676
                }
×
1677
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
2✔
1678
                if err != nil {
2✔
1679
                        return err
×
1680
                }
×
1681

1682
                // Scan from chanIDStart to chanIDEnd, deleting every
1683
                // found edge.
1684
                // NOTE: we must delete the edges after the cursor loop, since
1685
                // modifying the bucket while traversing is not safe.
1686
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1687
                // so that the StartingAlias itself isn't deleted.
1688
                var keys [][]byte
2✔
1689
                cursor := edgeIndex.ReadWriteCursor()
2✔
1690

2✔
1691
                //nolint:ll
2✔
1692
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
2✔
1693
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
4✔
1694
                        edgeInfoReader := bytes.NewReader(v)
2✔
1695
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
2✔
1696
                        if err != nil {
2✔
1697
                                return err
×
1698
                        }
×
1699

1700
                        keys = append(keys, k)
2✔
1701
                        removedChans = append(removedChans, &edgeInfo)
2✔
1702
                }
1703

1704
                for _, k := range keys {
4✔
1705
                        err = c.delChannelEdgeUnsafe(
2✔
1706
                                edges, edgeIndex, chanIndex, zombieIndex,
2✔
1707
                                k, false, false,
2✔
1708
                        )
2✔
1709
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
2✔
1710
                                return err
×
1711
                        }
×
1712
                }
1713

1714
                // Delete all the entries in the prune log having a height
1715
                // greater or equal to the block disconnected.
1716
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
2✔
1717
                if err != nil {
2✔
1718
                        return err
×
1719
                }
×
1720

1721
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
2✔
1722
                        pruneLogBucket,
2✔
1723
                )
2✔
1724
                if err != nil {
2✔
1725
                        return err
×
1726
                }
×
1727

1728
                var pruneKeyStart [4]byte
2✔
1729
                byteOrder.PutUint32(pruneKeyStart[:], height)
2✔
1730

2✔
1731
                var pruneKeyEnd [4]byte
2✔
1732
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
2✔
1733

2✔
1734
                // To avoid modifying the bucket while traversing, we delete
2✔
1735
                // the keys in a second loop.
2✔
1736
                var pruneKeys [][]byte
2✔
1737
                pruneCursor := pruneBucket.ReadWriteCursor()
2✔
1738
                //nolint:ll
2✔
1739
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
2✔
1740
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
4✔
1741
                        pruneKeys = append(pruneKeys, k)
2✔
1742
                }
2✔
1743

1744
                for _, k := range pruneKeys {
4✔
1745
                        if err := pruneBucket.Delete(k); err != nil {
2✔
1746
                                return err
×
1747
                        }
×
1748
                }
1749

1750
                return nil
2✔
1751
        }, func() {
2✔
1752
                removedChans = nil
2✔
1753
        }); err != nil {
2✔
1754
                return nil, err
×
1755
        }
×
1756

1757
        for _, channel := range removedChans {
4✔
1758
                c.rejectCache.remove(channel.ChannelID)
2✔
1759
                c.chanCache.remove(channel.ChannelID)
2✔
1760
        }
2✔
1761

1762
        return removedChans, nil
2✔
1763
}
1764

1765
// PruneTip returns the block height and hash of the latest block that has been
1766
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1767
// to tell if the graph is currently in sync with the current best known UTXO
1768
// state.
1769
func (c *ChannelGraph) PruneTip() (*chainhash.Hash, uint32, error) {
3✔
1770
        var (
3✔
1771
                tipHash   chainhash.Hash
3✔
1772
                tipHeight uint32
3✔
1773
        )
3✔
1774

3✔
1775
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1776
                graphMeta := tx.ReadBucket(graphMetaBucket)
3✔
1777
                if graphMeta == nil {
3✔
1778
                        return ErrGraphNotFound
×
1779
                }
×
1780
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
3✔
1781
                if pruneBucket == nil {
3✔
1782
                        return ErrGraphNeverPruned
×
1783
                }
×
1784

1785
                pruneCursor := pruneBucket.ReadCursor()
3✔
1786

3✔
1787
                // The prune key with the largest block height will be our
3✔
1788
                // prune tip.
3✔
1789
                k, v := pruneCursor.Last()
3✔
1790
                if k == nil {
6✔
1791
                        return ErrGraphNeverPruned
3✔
1792
                }
3✔
1793

1794
                // Once we have the prune tip, the value will be the block hash,
1795
                // and the key the block height.
1796
                copy(tipHash[:], v[:])
3✔
1797
                tipHeight = byteOrder.Uint32(k[:])
3✔
1798

3✔
1799
                return nil
3✔
1800
        }, func() {})
3✔
1801
        if err != nil {
6✔
1802
                return nil, 0, err
3✔
1803
        }
3✔
1804

1805
        return &tipHash, tipHeight, nil
3✔
1806
}
1807

1808
// DeleteChannelEdges removes edges with the given channel IDs from the
1809
// database and marks them as zombies. This ensures that we're unable to re-add
1810
// it to our database once again. If an edge does not exist within the
1811
// database, then ErrEdgeNotFound will be returned. If strictZombiePruning is
1812
// true, then when we mark these edges as zombies, we'll set up the keys such
1813
// that we require the node that failed to send the fresh update to be the one
1814
// that resurrects the channel from its zombie state. The markZombie bool
1815
// denotes whether or not to mark the channel as a zombie.
1816
func (c *ChannelGraph) DeleteChannelEdges(strictZombiePruning, markZombie bool,
1817
        chanIDs ...uint64) error {
3✔
1818

3✔
1819
        // TODO(roasbeef): possibly delete from node bucket if node has no more
3✔
1820
        // channels
3✔
1821
        // TODO(roasbeef): don't delete both edges?
3✔
1822

3✔
1823
        c.cacheMu.Lock()
3✔
1824
        defer c.cacheMu.Unlock()
3✔
1825

3✔
1826
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1827
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1828
                if edges == nil {
3✔
1829
                        return ErrEdgeNotFound
×
1830
                }
×
1831
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1832
                if edgeIndex == nil {
3✔
1833
                        return ErrEdgeNotFound
×
1834
                }
×
1835
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
3✔
1836
                if chanIndex == nil {
3✔
1837
                        return ErrEdgeNotFound
×
1838
                }
×
1839
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1840
                if nodes == nil {
3✔
1841
                        return ErrGraphNodeNotFound
×
1842
                }
×
1843
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1844
                if err != nil {
3✔
1845
                        return err
×
1846
                }
×
1847

1848
                var rawChanID [8]byte
3✔
1849
                for _, chanID := range chanIDs {
6✔
1850
                        byteOrder.PutUint64(rawChanID[:], chanID)
3✔
1851
                        err := c.delChannelEdgeUnsafe(
3✔
1852
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1853
                                rawChanID[:], markZombie, strictZombiePruning,
3✔
1854
                        )
3✔
1855
                        if err != nil {
3✔
1856
                                return err
×
1857
                        }
×
1858
                }
1859

1860
                return nil
3✔
1861
        }, func() {})
3✔
1862
        if err != nil {
3✔
1863
                return err
×
1864
        }
×
1865

1866
        for _, chanID := range chanIDs {
6✔
1867
                c.rejectCache.remove(chanID)
3✔
1868
                c.chanCache.remove(chanID)
3✔
1869
        }
3✔
1870

1871
        return nil
3✔
1872
}
1873

1874
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1875
// passed channel point (outpoint). If the passed channel doesn't exist within
1876
// the database, then ErrEdgeNotFound is returned.
1877
func (c *ChannelGraph) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
3✔
1878
        var chanID uint64
3✔
1879
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1880
                var err error
3✔
1881
                chanID, err = getChanID(tx, chanPoint)
3✔
1882
                return err
3✔
1883
        }, func() {
6✔
1884
                chanID = 0
3✔
1885
        }); err != nil {
6✔
1886
                return 0, err
3✔
1887
        }
3✔
1888

1889
        return chanID, nil
3✔
1890
}
1891

1892
// getChanID returns the assigned channel ID for a given channel point.
1893
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
3✔
1894
        var b bytes.Buffer
3✔
1895
        if err := WriteOutpoint(&b, chanPoint); err != nil {
3✔
1896
                return 0, err
×
1897
        }
×
1898

1899
        edges := tx.ReadBucket(edgeBucket)
3✔
1900
        if edges == nil {
3✔
1901
                return 0, ErrGraphNoEdgesFound
×
1902
        }
×
1903
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1904
        if chanIndex == nil {
3✔
1905
                return 0, ErrGraphNoEdgesFound
×
1906
        }
×
1907

1908
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
1909
        if chanIDBytes == nil {
6✔
1910
                return 0, ErrEdgeNotFound
3✔
1911
        }
3✔
1912

1913
        chanID := byteOrder.Uint64(chanIDBytes)
3✔
1914

3✔
1915
        return chanID, nil
3✔
1916
}
1917

1918
// TODO(roasbeef): allow updates to use Batch?
1919

1920
// HighestChanID returns the "highest" known channel ID in the channel graph.
1921
// This represents the "newest" channel from the PoV of the chain. This method
1922
// can be used by peers to quickly determine if they're graphs are in sync.
1923
func (c *ChannelGraph) HighestChanID() (uint64, error) {
3✔
1924
        var cid uint64
3✔
1925

3✔
1926
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1927
                edges := tx.ReadBucket(edgeBucket)
3✔
1928
                if edges == nil {
3✔
1929
                        return ErrGraphNoEdgesFound
×
1930
                }
×
1931
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1932
                if edgeIndex == nil {
3✔
1933
                        return ErrGraphNoEdgesFound
×
1934
                }
×
1935

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

3✔
1940
                lastChanID, _ := cidCursor.Last()
3✔
1941

3✔
1942
                // If there's no key, then this means that we don't actually
3✔
1943
                // know of any channels, so we'll return a predicable error.
3✔
1944
                if lastChanID == nil {
6✔
1945
                        return ErrGraphNoEdgesFound
3✔
1946
                }
3✔
1947

1948
                // Otherwise, we'll de serialize the channel ID and return it
1949
                // to the caller.
1950
                cid = byteOrder.Uint64(lastChanID)
3✔
1951
                return nil
3✔
1952
        }, func() {
3✔
1953
                cid = 0
3✔
1954
        })
3✔
1955
        if err != nil && err != ErrGraphNoEdgesFound {
3✔
1956
                return 0, err
×
1957
        }
×
1958

1959
        return cid, nil
3✔
1960
}
1961

1962
// ChannelEdge represents the complete set of information for a channel edge in
1963
// the known channel graph. This struct couples the core information of the
1964
// edge as well as each of the known advertised edge policies.
1965
type ChannelEdge struct {
1966
        // Info contains all the static information describing the channel.
1967
        Info *models.ChannelEdgeInfo
1968

1969
        // Policy1 points to the "first" edge policy of the channel containing
1970
        // the dynamic information required to properly route through the edge.
1971
        Policy1 *models.ChannelEdgePolicy
1972

1973
        // Policy2 points to the "second" edge policy of the channel containing
1974
        // the dynamic information required to properly route through the edge.
1975
        Policy2 *models.ChannelEdgePolicy
1976

1977
        // Node1 is "node 1" in the channel. This is the node that would have
1978
        // produced Policy1 if it exists.
1979
        Node1 *models.LightningNode
1980

1981
        // Node2 is "node 2" in the channel. This is the node that would have
1982
        // produced Policy2 if it exists.
1983
        Node2 *models.LightningNode
1984
}
1985

1986
// ChanUpdatesInHorizon returns all the known channel edges which have at least
1987
// one edge that has an update timestamp within the specified horizon.
1988
func (c *ChannelGraph) ChanUpdatesInHorizon(startTime,
1989
        endTime time.Time) ([]ChannelEdge, error) {
3✔
1990

3✔
1991
        // To ensure we don't return duplicate ChannelEdges, we'll use an
3✔
1992
        // additional map to keep track of the edges already seen to prevent
3✔
1993
        // re-adding it.
3✔
1994
        var edgesSeen map[uint64]struct{}
3✔
1995
        var edgesToCache map[uint64]ChannelEdge
3✔
1996
        var edgesInHorizon []ChannelEdge
3✔
1997

3✔
1998
        c.cacheMu.Lock()
3✔
1999
        defer c.cacheMu.Unlock()
3✔
2000

3✔
2001
        var hits int
3✔
2002
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2003
                edges := tx.ReadBucket(edgeBucket)
3✔
2004
                if edges == nil {
3✔
2005
                        return ErrGraphNoEdgesFound
×
2006
                }
×
2007
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2008
                if edgeIndex == nil {
3✔
2009
                        return ErrGraphNoEdgesFound
×
2010
                }
×
2011
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
3✔
2012
                if edgeUpdateIndex == nil {
3✔
2013
                        return ErrGraphNoEdgesFound
×
2014
                }
×
2015

2016
                nodes := tx.ReadBucket(nodeBucket)
3✔
2017
                if nodes == nil {
3✔
2018
                        return ErrGraphNodesNotFound
×
2019
                }
×
2020

2021
                // We'll now obtain a cursor to perform a range query within
2022
                // the index to find all channels within the horizon.
2023
                updateCursor := edgeUpdateIndex.ReadCursor()
3✔
2024

3✔
2025
                var startTimeBytes, endTimeBytes [8 + 8]byte
3✔
2026
                byteOrder.PutUint64(
3✔
2027
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2028
                )
3✔
2029
                byteOrder.PutUint64(
3✔
2030
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2031
                )
3✔
2032

3✔
2033
                // With our start and end times constructed, we'll step through
3✔
2034
                // the index collecting the info and policy of each update of
3✔
2035
                // each channel that has a last update within the time range.
3✔
2036
                //
3✔
2037
                //nolint:ll
3✔
2038
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2039
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2040

3✔
2041
                        // We have a new eligible entry, so we'll slice of the
3✔
2042
                        // chan ID so we can query it in the DB.
3✔
2043
                        chanID := indexKey[8:]
3✔
2044

3✔
2045
                        // If we've already retrieved the info and policies for
3✔
2046
                        // this edge, then we can skip it as we don't need to do
3✔
2047
                        // so again.
3✔
2048
                        chanIDInt := byteOrder.Uint64(chanID)
3✔
2049
                        if _, ok := edgesSeen[chanIDInt]; ok {
3✔
2050
                                continue
×
2051
                        }
2052

2053
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
6✔
2054
                                hits++
3✔
2055
                                edgesSeen[chanIDInt] = struct{}{}
3✔
2056
                                edgesInHorizon = append(edgesInHorizon, channel)
3✔
2057
                                continue
3✔
2058
                        }
2059

2060
                        // First, we'll fetch the static edge information.
2061
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2062
                        if err != nil {
3✔
2063
                                chanID := byteOrder.Uint64(chanID)
×
2064
                                return fmt.Errorf("unable to fetch info for "+
×
2065
                                        "edge with chan_id=%v: %v", chanID, err)
×
2066
                        }
×
2067

2068
                        // With the static information obtained, we'll now
2069
                        // fetch the dynamic policy info.
2070
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2071
                                edgeIndex, edges, chanID,
3✔
2072
                        )
3✔
2073
                        if err != nil {
3✔
2074
                                chanID := byteOrder.Uint64(chanID)
×
2075
                                return fmt.Errorf("unable to fetch policies "+
×
2076
                                        "for edge with chan_id=%v: %v", chanID,
×
2077
                                        err)
×
2078
                        }
×
2079

2080
                        node1, err := fetchLightningNode(
3✔
2081
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2082
                        )
3✔
2083
                        if err != nil {
3✔
2084
                                return err
×
2085
                        }
×
2086

2087
                        node2, err := fetchLightningNode(
3✔
2088
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2089
                        )
3✔
2090
                        if err != nil {
3✔
2091
                                return err
×
2092
                        }
×
2093

2094
                        // Finally, we'll collate this edge with the rest of
2095
                        // edges to be returned.
2096
                        edgesSeen[chanIDInt] = struct{}{}
3✔
2097
                        channel := ChannelEdge{
3✔
2098
                                Info:    &edgeInfo,
3✔
2099
                                Policy1: edge1,
3✔
2100
                                Policy2: edge2,
3✔
2101
                                Node1:   &node1,
3✔
2102
                                Node2:   &node2,
3✔
2103
                        }
3✔
2104
                        edgesInHorizon = append(edgesInHorizon, channel)
3✔
2105
                        edgesToCache[chanIDInt] = channel
3✔
2106
                }
2107

2108
                return nil
3✔
2109
        }, func() {
3✔
2110
                edgesSeen = make(map[uint64]struct{})
3✔
2111
                edgesToCache = make(map[uint64]ChannelEdge)
3✔
2112
                edgesInHorizon = nil
3✔
2113
        })
3✔
2114
        switch {
3✔
2115
        case err == ErrGraphNoEdgesFound:
×
2116
                fallthrough
×
2117
        case err == ErrGraphNodesNotFound:
×
2118
                break
×
2119

2120
        case err != nil:
×
2121
                return nil, err
×
2122
        }
2123

2124
        // Insert any edges loaded from disk into the cache.
2125
        for chanid, channel := range edgesToCache {
6✔
2126
                c.chanCache.insert(chanid, channel)
3✔
2127
        }
3✔
2128

2129
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
3✔
2130
                float64(hits)/float64(len(edgesInHorizon)), hits,
3✔
2131
                len(edgesInHorizon))
3✔
2132

3✔
2133
        return edgesInHorizon, nil
3✔
2134
}
2135

2136
// NodeUpdatesInHorizon returns all the known lightning node which have an
2137
// update timestamp within the passed range. This method can be used by two
2138
// nodes to quickly determine if they have the same set of up to date node
2139
// announcements.
2140
func (c *ChannelGraph) NodeUpdatesInHorizon(startTime,
2141
        endTime time.Time) ([]models.LightningNode, error) {
3✔
2142

3✔
2143
        var nodesInHorizon []models.LightningNode
3✔
2144

3✔
2145
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2146
                nodes := tx.ReadBucket(nodeBucket)
3✔
2147
                if nodes == nil {
3✔
2148
                        return ErrGraphNodesNotFound
×
2149
                }
×
2150

2151
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
3✔
2152
                if nodeUpdateIndex == nil {
3✔
2153
                        return ErrGraphNodesNotFound
×
2154
                }
×
2155

2156
                // We'll now obtain a cursor to perform a range query within
2157
                // the index to find all node announcements within the horizon.
2158
                updateCursor := nodeUpdateIndex.ReadCursor()
3✔
2159

3✔
2160
                var startTimeBytes, endTimeBytes [8 + 33]byte
3✔
2161
                byteOrder.PutUint64(
3✔
2162
                        startTimeBytes[:8], uint64(startTime.Unix()),
3✔
2163
                )
3✔
2164
                byteOrder.PutUint64(
3✔
2165
                        endTimeBytes[:8], uint64(endTime.Unix()),
3✔
2166
                )
3✔
2167

3✔
2168
                // With our start and end times constructed, we'll step through
3✔
2169
                // the index collecting info for each node within the time
3✔
2170
                // range.
3✔
2171
                //
3✔
2172
                //nolint:ll
3✔
2173
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
3✔
2174
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
6✔
2175

3✔
2176
                        nodePub := indexKey[8:]
3✔
2177
                        node, err := fetchLightningNode(nodes, nodePub)
3✔
2178
                        if err != nil {
3✔
2179
                                return err
×
2180
                        }
×
2181

2182
                        nodesInHorizon = append(nodesInHorizon, node)
3✔
2183
                }
2184

2185
                return nil
3✔
2186
        }, func() {
3✔
2187
                nodesInHorizon = nil
3✔
2188
        })
3✔
2189
        switch {
3✔
2190
        case err == ErrGraphNoEdgesFound:
×
2191
                fallthrough
×
2192
        case err == ErrGraphNodesNotFound:
×
2193
                break
×
2194

2195
        case err != nil:
×
2196
                return nil, err
×
2197
        }
2198

2199
        return nodesInHorizon, nil
3✔
2200
}
2201

2202
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2203
// ID's that we don't know and are not known zombies of the passed set. In other
2204
// words, we perform a set difference of our set of chan ID's and the ones
2205
// passed in. This method can be used by callers to determine the set of
2206
// channels another peer knows of that we don't.
2207
func (c *ChannelGraph) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo,
2208
        isZombieChan func(time.Time, time.Time) bool) ([]uint64, error) {
3✔
2209

3✔
2210
        var newChanIDs []uint64
3✔
2211

3✔
2212
        c.cacheMu.Lock()
3✔
2213
        defer c.cacheMu.Unlock()
3✔
2214

3✔
2215
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
2216
                edges := tx.ReadBucket(edgeBucket)
3✔
2217
                if edges == nil {
3✔
2218
                        return ErrGraphNoEdgesFound
×
2219
                }
×
2220
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2221
                if edgeIndex == nil {
3✔
2222
                        return ErrGraphNoEdgesFound
×
2223
                }
×
2224

2225
                // Fetch the zombie index, it may not exist if no edges have
2226
                // ever been marked as zombies. If the index has been
2227
                // initialized, we will use it later to skip known zombie edges.
2228
                zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
2229

3✔
2230
                // We'll run through the set of chanIDs and collate only the
3✔
2231
                // set of channel that are unable to be found within our db.
3✔
2232
                var cidBytes [8]byte
3✔
2233
                for _, info := range chansInfo {
6✔
2234
                        scid := info.ShortChannelID.ToUint64()
3✔
2235
                        byteOrder.PutUint64(cidBytes[:], scid)
3✔
2236

3✔
2237
                        // If the edge is already known, skip it.
3✔
2238
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
6✔
2239
                                continue
3✔
2240
                        }
2241

2242
                        // If the edge is a known zombie, skip it.
2243
                        if zombieIndex != nil {
6✔
2244
                                isZombie, _, _ := isZombieEdge(
3✔
2245
                                        zombieIndex, scid,
3✔
2246
                                )
3✔
2247

3✔
2248
                                // TODO(ziggie): Make sure that for the strict
3✔
2249
                                // pruning case we compare the pubkeys and
3✔
2250
                                // whether the right timestamp is not older than
3✔
2251
                                // the `ChannelPruneExpiry`.
3✔
2252
                                //
3✔
2253
                                // NOTE: The timestamp data has no verification
3✔
2254
                                // attached to it in the `ReplyChannelRange` msg
3✔
2255
                                // so we are trusting this data at this point.
3✔
2256
                                // However it is not critical because we are
3✔
2257
                                // just removing the channel from the db when
3✔
2258
                                // the timestamps are more recent. During the
3✔
2259
                                // querying of the gossip msg verification
3✔
2260
                                // happens as usual.
3✔
2261
                                // However we should start punishing peers when
3✔
2262
                                // they don't provide us honest data ?
3✔
2263
                                isStillZombie := isZombieChan(
3✔
2264
                                        info.Node1UpdateTimestamp,
3✔
2265
                                        info.Node2UpdateTimestamp,
3✔
2266
                                )
3✔
2267

3✔
2268
                                switch {
3✔
2269
                                // If the edge is a known zombie and if we
2270
                                // would still consider it a zombie given the
2271
                                // latest update timestamps, then we skip this
2272
                                // channel.
2273
                                case isZombie && isStillZombie:
×
2274
                                        continue
×
2275

2276
                                // Otherwise, if we have marked it as a zombie
2277
                                // but the latest update timestamps could bring
2278
                                // it back from the dead, then we mark it alive,
2279
                                // and we let it be added to the set of IDs to
2280
                                // query our peer for.
2281
                                case isZombie && !isStillZombie:
×
2282
                                        err := c.markEdgeLiveUnsafe(tx, scid)
×
2283
                                        if err != nil {
×
2284
                                                return err
×
2285
                                        }
×
2286
                                }
2287
                        }
2288

2289
                        newChanIDs = append(newChanIDs, scid)
3✔
2290
                }
2291

2292
                return nil
3✔
2293
        }, func() {
3✔
2294
                newChanIDs = nil
3✔
2295
        })
3✔
2296
        switch {
3✔
2297
        // If we don't know of any edges yet, then we'll return the entire set
2298
        // of chan IDs specified.
2299
        case err == ErrGraphNoEdgesFound:
×
2300
                ogChanIDs := make([]uint64, len(chansInfo))
×
2301
                for i, info := range chansInfo {
×
2302
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2303
                }
×
2304

2305
                return ogChanIDs, nil
×
2306

2307
        case err != nil:
×
2308
                return nil, err
×
2309
        }
2310

2311
        return newChanIDs, nil
3✔
2312
}
2313

2314
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2315
// latest received channel updates for the channel.
2316
type ChannelUpdateInfo struct {
2317
        // ShortChannelID is the SCID identifier of the channel.
2318
        ShortChannelID lnwire.ShortChannelID
2319

2320
        // Node1UpdateTimestamp is the timestamp of the latest received update
2321
        // from the node 1 channel peer. This will be set to zero time if no
2322
        // update has yet been received from this node.
2323
        Node1UpdateTimestamp time.Time
2324

2325
        // Node2UpdateTimestamp is the timestamp of the latest received update
2326
        // from the node 2 channel peer. This will be set to zero time if no
2327
        // update has yet been received from this node.
2328
        Node2UpdateTimestamp time.Time
2329
}
2330

2331
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2332
// timestamps with zero seconds unix timestamp which equals
2333
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2334
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2335
        node2Timestamp time.Time) ChannelUpdateInfo {
3✔
2336

3✔
2337
        chanInfo := ChannelUpdateInfo{
3✔
2338
                ShortChannelID:       scid,
3✔
2339
                Node1UpdateTimestamp: node1Timestamp,
3✔
2340
                Node2UpdateTimestamp: node2Timestamp,
3✔
2341
        }
3✔
2342

3✔
2343
        if node1Timestamp.IsZero() {
6✔
2344
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
3✔
2345
        }
3✔
2346

2347
        if node2Timestamp.IsZero() {
6✔
2348
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
3✔
2349
        }
3✔
2350

2351
        return chanInfo
3✔
2352
}
2353

2354
// BlockChannelRange represents a range of channels for a given block height.
2355
type BlockChannelRange struct {
2356
        // Height is the height of the block all of the channels below were
2357
        // included in.
2358
        Height uint32
2359

2360
        // Channels is the list of channels identified by their short ID
2361
        // representation known to us that were included in the block height
2362
        // above. The list may include channel update timestamp information if
2363
        // requested.
2364
        Channels []ChannelUpdateInfo
2365
}
2366

2367
// FilterChannelRange returns the channel ID's of all known channels which were
2368
// mined in a block height within the passed range. The channel IDs are grouped
2369
// by their common block height. This method can be used to quickly share with a
2370
// peer the set of channels we know of within a particular range to catch them
2371
// up after a period of time offline. If withTimestamps is true then the
2372
// timestamp info of the latest received channel update messages of the channel
2373
// will be included in the response.
2374
func (c *ChannelGraph) FilterChannelRange(startHeight,
2375
        endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error) {
3✔
2376

3✔
2377
        startChanID := &lnwire.ShortChannelID{
3✔
2378
                BlockHeight: startHeight,
3✔
2379
        }
3✔
2380

3✔
2381
        endChanID := lnwire.ShortChannelID{
3✔
2382
                BlockHeight: endHeight,
3✔
2383
                TxIndex:     math.MaxUint32 & 0x00ffffff,
3✔
2384
                TxPosition:  math.MaxUint16,
3✔
2385
        }
3✔
2386

3✔
2387
        // As we need to perform a range scan, we'll convert the starting and
3✔
2388
        // ending height to their corresponding values when encoded using short
3✔
2389
        // channel ID's.
3✔
2390
        var chanIDStart, chanIDEnd [8]byte
3✔
2391
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
3✔
2392
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
3✔
2393

3✔
2394
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
3✔
2395
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
2396
                edges := tx.ReadBucket(edgeBucket)
3✔
2397
                if edges == nil {
3✔
2398
                        return ErrGraphNoEdgesFound
×
2399
                }
×
2400
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2401
                if edgeIndex == nil {
3✔
2402
                        return ErrGraphNoEdgesFound
×
2403
                }
×
2404

2405
                cursor := edgeIndex.ReadCursor()
3✔
2406

3✔
2407
                // We'll now iterate through the database, and find each
3✔
2408
                // channel ID that resides within the specified range.
3✔
2409
                //
3✔
2410
                //nolint:ll
3✔
2411
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
3✔
2412
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
6✔
2413
                        // Don't send alias SCIDs during gossip sync.
3✔
2414
                        edgeReader := bytes.NewReader(v)
3✔
2415
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
3✔
2416
                        if err != nil {
3✔
2417
                                return err
×
2418
                        }
×
2419

2420
                        if edgeInfo.AuthProof == nil {
6✔
2421
                                continue
3✔
2422
                        }
2423

2424
                        // This channel ID rests within the target range, so
2425
                        // we'll add it to our returned set.
2426
                        rawCid := byteOrder.Uint64(k)
3✔
2427
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
3✔
2428

3✔
2429
                        chanInfo := NewChannelUpdateInfo(
3✔
2430
                                cid, time.Time{}, time.Time{},
3✔
2431
                        )
3✔
2432

3✔
2433
                        if !withTimestamps {
3✔
2434
                                channelsPerBlock[cid.BlockHeight] = append(
×
2435
                                        channelsPerBlock[cid.BlockHeight],
×
2436
                                        chanInfo,
×
2437
                                )
×
2438

×
2439
                                continue
×
2440
                        }
2441

2442
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
3✔
2443

3✔
2444
                        rawPolicy := edges.Get(node1Key)
3✔
2445
                        if len(rawPolicy) != 0 {
6✔
2446
                                r := bytes.NewReader(rawPolicy)
3✔
2447

3✔
2448
                                edge, err := deserializeChanEdgePolicyRaw(r)
3✔
2449
                                if err != nil && !errors.Is(
3✔
2450
                                        err, ErrEdgePolicyOptionalFieldNotFound,
3✔
2451
                                ) {
3✔
2452

×
2453
                                        return err
×
2454
                                }
×
2455

2456
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
3✔
2457
                        }
2458

2459
                        rawPolicy = edges.Get(node2Key)
3✔
2460
                        if len(rawPolicy) != 0 {
6✔
2461
                                r := bytes.NewReader(rawPolicy)
3✔
2462

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

×
2468
                                        return err
×
2469
                                }
×
2470

2471
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
3✔
2472
                        }
2473

2474
                        channelsPerBlock[cid.BlockHeight] = append(
3✔
2475
                                channelsPerBlock[cid.BlockHeight], chanInfo,
3✔
2476
                        )
3✔
2477
                }
2478

2479
                return nil
3✔
2480
        }, func() {
3✔
2481
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
3✔
2482
        })
3✔
2483

2484
        switch {
3✔
2485
        // If we don't know of any channels yet, then there's nothing to
2486
        // filter, so we'll return an empty slice.
2487
        case err == ErrGraphNoEdgesFound || len(channelsPerBlock) == 0:
3✔
2488
                return nil, nil
3✔
2489

2490
        case err != nil:
×
2491
                return nil, err
×
2492
        }
2493

2494
        // Return the channel ranges in ascending block height order.
2495
        blocks := make([]uint32, 0, len(channelsPerBlock))
3✔
2496
        for block := range channelsPerBlock {
6✔
2497
                blocks = append(blocks, block)
3✔
2498
        }
3✔
2499
        sort.Slice(blocks, func(i, j int) bool {
6✔
2500
                return blocks[i] < blocks[j]
3✔
2501
        })
3✔
2502

2503
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
3✔
2504
        for _, block := range blocks {
6✔
2505
                channelRanges = append(channelRanges, BlockChannelRange{
3✔
2506
                        Height:   block,
3✔
2507
                        Channels: channelsPerBlock[block],
3✔
2508
                })
3✔
2509
        }
3✔
2510

2511
        return channelRanges, nil
3✔
2512
}
2513

2514
// FetchChanInfos returns the set of channel edges that correspond to the passed
2515
// channel ID's. If an edge is the query is unknown to the database, it will
2516
// skipped and the result will contain only those edges that exist at the time
2517
// of the query. This can be used to respond to peer queries that are seeking to
2518
// fill in gaps in their view of the channel graph.
2519
func (c *ChannelGraph) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
3✔
2520
        return c.fetchChanInfos(nil, chanIDs)
3✔
2521
}
3✔
2522

2523
// fetchChanInfos returns the set of channel edges that correspond to the passed
2524
// channel ID's. If an edge is the query is unknown to the database, it will
2525
// skipped and the result will contain only those edges that exist at the time
2526
// of the query. This can be used to respond to peer queries that are seeking to
2527
// fill in gaps in their view of the channel graph.
2528
//
2529
// NOTE: An optional transaction may be provided. If none is provided, then a
2530
// new one will be created.
2531
func (c *ChannelGraph) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2532
        []ChannelEdge, error) {
3✔
2533
        // TODO(roasbeef): sort cids?
3✔
2534

3✔
2535
        var (
3✔
2536
                chanEdges []ChannelEdge
3✔
2537
                cidBytes  [8]byte
3✔
2538
        )
3✔
2539

3✔
2540
        fetchChanInfos := func(tx kvdb.RTx) error {
6✔
2541
                edges := tx.ReadBucket(edgeBucket)
3✔
2542
                if edges == nil {
3✔
2543
                        return ErrGraphNoEdgesFound
×
2544
                }
×
2545
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2546
                if edgeIndex == nil {
3✔
2547
                        return ErrGraphNoEdgesFound
×
2548
                }
×
2549
                nodes := tx.ReadBucket(nodeBucket)
3✔
2550
                if nodes == nil {
3✔
2551
                        return ErrGraphNotFound
×
2552
                }
×
2553

2554
                for _, cid := range chanIDs {
6✔
2555
                        byteOrder.PutUint64(cidBytes[:], cid)
3✔
2556

3✔
2557
                        // First, we'll fetch the static edge information. If
3✔
2558
                        // the edge is unknown, we will skip the edge and
3✔
2559
                        // continue gathering all known edges.
3✔
2560
                        edgeInfo, err := fetchChanEdgeInfo(
3✔
2561
                                edgeIndex, cidBytes[:],
3✔
2562
                        )
3✔
2563
                        switch {
3✔
2564
                        case errors.Is(err, ErrEdgeNotFound):
×
2565
                                continue
×
2566
                        case err != nil:
×
2567
                                return err
×
2568
                        }
2569

2570
                        // With the static information obtained, we'll now
2571
                        // fetch the dynamic policy info.
2572
                        edge1, edge2, err := fetchChanEdgePolicies(
3✔
2573
                                edgeIndex, edges, cidBytes[:],
3✔
2574
                        )
3✔
2575
                        if err != nil {
3✔
2576
                                return err
×
2577
                        }
×
2578

2579
                        node1, err := fetchLightningNode(
3✔
2580
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
2581
                        )
3✔
2582
                        if err != nil {
3✔
2583
                                return err
×
2584
                        }
×
2585

2586
                        node2, err := fetchLightningNode(
3✔
2587
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
2588
                        )
3✔
2589
                        if err != nil {
3✔
2590
                                return err
×
2591
                        }
×
2592

2593
                        chanEdges = append(chanEdges, ChannelEdge{
3✔
2594
                                Info:    &edgeInfo,
3✔
2595
                                Policy1: edge1,
3✔
2596
                                Policy2: edge2,
3✔
2597
                                Node1:   &node1,
3✔
2598
                                Node2:   &node2,
3✔
2599
                        })
3✔
2600
                }
2601
                return nil
3✔
2602
        }
2603

2604
        if tx == nil {
6✔
2605
                err := kvdb.View(c.db, fetchChanInfos, func() {
6✔
2606
                        chanEdges = nil
3✔
2607
                })
3✔
2608
                if err != nil {
3✔
2609
                        return nil, err
×
2610
                }
×
2611

2612
                return chanEdges, nil
3✔
2613
        }
2614

2615
        err := fetchChanInfos(tx)
×
2616
        if err != nil {
×
2617
                return nil, err
×
2618
        }
×
2619

2620
        return chanEdges, nil
×
2621
}
2622

2623
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2624
        edge1, edge2 *models.ChannelEdgePolicy) error {
3✔
2625

3✔
2626
        // First, we'll fetch the edge update index bucket which currently
3✔
2627
        // stores an entry for the channel we're about to delete.
3✔
2628
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
3✔
2629
        if updateIndex == nil {
3✔
2630
                // No edges in bucket, return early.
×
2631
                return nil
×
2632
        }
×
2633

2634
        // Now that we have the bucket, we'll attempt to construct a template
2635
        // for the index key: updateTime || chanid.
2636
        var indexKey [8 + 8]byte
3✔
2637
        byteOrder.PutUint64(indexKey[8:], chanID)
3✔
2638

3✔
2639
        // With the template constructed, we'll attempt to delete an entry that
3✔
2640
        // would have been created by both edges: we'll alternate the update
3✔
2641
        // times, as one may had overridden the other.
3✔
2642
        if edge1 != nil {
6✔
2643
                byteOrder.PutUint64(
3✔
2644
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
3✔
2645
                )
3✔
2646
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2647
                        return err
×
2648
                }
×
2649
        }
2650

2651
        // We'll also attempt to delete the entry that may have been created by
2652
        // the second edge.
2653
        if edge2 != nil {
6✔
2654
                byteOrder.PutUint64(
3✔
2655
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
3✔
2656
                )
3✔
2657
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2658
                        return err
×
2659
                }
×
2660
        }
2661

2662
        return nil
3✔
2663
}
2664

2665
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2666
// cache. It then goes on to delete any policy info and edge info for this
2667
// channel from the DB and finally, if isZombie is true, it will add an entry
2668
// for this channel in the zombie index.
2669
//
2670
// NOTE: this method MUST only be called if the cacheMu has already been
2671
// acquired.
2672
func (c *ChannelGraph) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2673
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2674
        strictZombie bool) error {
3✔
2675

3✔
2676
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
2677
        if err != nil {
3✔
2678
                return err
×
2679
        }
×
2680

2681
        if c.graphCache != nil {
6✔
2682
                c.graphCache.RemoveChannel(
3✔
2683
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
3✔
2684
                        edgeInfo.ChannelID,
3✔
2685
                )
3✔
2686
        }
3✔
2687

2688
        // We'll also remove the entry in the edge update index bucket before
2689
        // we delete the edges themselves so we can access their last update
2690
        // times.
2691
        cid := byteOrder.Uint64(chanID)
3✔
2692
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
2693
        if err != nil {
3✔
2694
                return err
×
2695
        }
×
2696
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
3✔
2697
        if err != nil {
3✔
2698
                return err
×
2699
        }
×
2700

2701
        // The edge key is of the format pubKey || chanID. First we construct
2702
        // the latter half, populating the channel ID.
2703
        var edgeKey [33 + 8]byte
3✔
2704
        copy(edgeKey[33:], chanID)
3✔
2705

3✔
2706
        // With the latter half constructed, copy over the first public key to
3✔
2707
        // delete the edge in this direction, then the second to delete the
3✔
2708
        // edge in the opposite direction.
3✔
2709
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
3✔
2710
        if edges.Get(edgeKey[:]) != nil {
6✔
2711
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2712
                        return err
×
2713
                }
×
2714
        }
2715
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
3✔
2716
        if edges.Get(edgeKey[:]) != nil {
6✔
2717
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2718
                        return err
×
2719
                }
×
2720
        }
2721

2722
        // As part of deleting the edge we also remove all disabled entries
2723
        // from the edgePolicyDisabledIndex bucket. We do that for both
2724
        // directions.
2725
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
3✔
2726
        if err != nil {
3✔
2727
                return err
×
2728
        }
×
2729
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
3✔
2730
        if err != nil {
3✔
2731
                return err
×
2732
        }
×
2733

2734
        // With the edge data deleted, we can purge the information from the two
2735
        // edge indexes.
2736
        if err := edgeIndex.Delete(chanID); err != nil {
3✔
2737
                return err
×
2738
        }
×
2739
        var b bytes.Buffer
3✔
2740
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
2741
                return err
×
2742
        }
×
2743
        if err := chanIndex.Delete(b.Bytes()); err != nil {
3✔
2744
                return err
×
2745
        }
×
2746

2747
        // Finally, we'll mark the edge as a zombie within our index if it's
2748
        // being removed due to the channel becoming a zombie. We do this to
2749
        // ensure we don't store unnecessary data for spent channels.
2750
        if !isZombie {
6✔
2751
                return nil
3✔
2752
        }
3✔
2753

2754
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
3✔
2755
        if strictZombie {
3✔
2756
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
×
2757
        }
×
2758

2759
        return markEdgeZombie(
3✔
2760
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
3✔
2761
        )
3✔
2762
}
2763

2764
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2765
// particular pair of channel policies. The return values are one of:
2766
//  1. (pubkey1, pubkey2)
2767
//  2. (pubkey1, blank)
2768
//  3. (blank, pubkey2)
2769
//
2770
// A blank pubkey means that corresponding node will be unable to resurrect a
2771
// channel on its own. For example, node1 may continue to publish recent
2772
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2773
// we don't want another fresh update from node1 to resurrect, as the edge can
2774
// only become live once node2 finally sends something recent.
2775
//
2776
// In the case where we have neither update, we allow either party to resurrect
2777
// the channel. If the channel were to be marked zombie again, it would be
2778
// marked with the correct lagging channel since we received an update from only
2779
// one side.
2780
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
2781
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
×
2782

×
2783
        switch {
×
2784
        // If we don't have either edge policy, we'll return both pubkeys so
2785
        // that the channel can be resurrected by either party.
2786
        case e1 == nil && e2 == nil:
×
2787
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2788

2789
        // If we're missing edge1, or if both edges are present but edge1 is
2790
        // older, we'll return edge1's pubkey and a blank pubkey for edge2. This
2791
        // means that only an update from edge1 will be able to resurrect the
2792
        // channel.
2793
        case e1 == nil || (e2 != nil && e1.LastUpdate.Before(e2.LastUpdate)):
×
2794
                return info.NodeKey1Bytes, [33]byte{}
×
2795

2796
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2797
        // return a blank pubkey for edge1. In this case, only an update from
2798
        // edge2 can resurect the channel.
2799
        default:
×
2800
                return [33]byte{}, info.NodeKey2Bytes
×
2801
        }
2802
}
2803

2804
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2805
// within the database for the referenced channel. The `flags` attribute within
2806
// the ChannelEdgePolicy determines which of the directed edges are being
2807
// updated. If the flag is 1, then the first node's information is being
2808
// updated, otherwise it's the second node's information. The node ordering is
2809
// determined by the lexicographical ordering of the identity public keys of the
2810
// nodes on either side of the channel.
2811
func (c *ChannelGraph) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2812
        op ...batch.SchedulerOption) error {
3✔
2813

3✔
2814
        var (
3✔
2815
                isUpdate1    bool
3✔
2816
                edgeNotFound bool
3✔
2817
        )
3✔
2818

3✔
2819
        r := &batch.Request{
3✔
2820
                Reset: func() {
6✔
2821
                        isUpdate1 = false
3✔
2822
                        edgeNotFound = false
3✔
2823
                },
3✔
2824
                Update: func(tx kvdb.RwTx) error {
3✔
2825
                        var err error
3✔
2826
                        isUpdate1, err = updateEdgePolicy(
3✔
2827
                                tx, edge, c.graphCache,
3✔
2828
                        )
3✔
2829

3✔
2830
                        if err != nil {
3✔
2831
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
×
2832
                        }
×
2833

2834
                        // Silence ErrEdgeNotFound so that the batch can
2835
                        // succeed, but propagate the error via local state.
2836
                        if errors.Is(err, ErrEdgeNotFound) {
3✔
2837
                                edgeNotFound = true
×
2838
                                return nil
×
2839
                        }
×
2840

2841
                        return err
3✔
2842
                },
2843
                OnCommit: func(err error) error {
3✔
2844
                        switch {
3✔
2845
                        case err != nil:
×
2846
                                return err
×
2847
                        case edgeNotFound:
×
2848
                                return ErrEdgeNotFound
×
2849
                        default:
3✔
2850
                                c.updateEdgeCache(edge, isUpdate1)
3✔
2851
                                return nil
3✔
2852
                        }
2853
                },
2854
        }
2855

2856
        for _, f := range op {
6✔
2857
                f(r)
3✔
2858
        }
3✔
2859

2860
        return c.chanScheduler.Execute(r)
3✔
2861
}
2862

2863
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2864
        isUpdate1 bool) {
3✔
2865

3✔
2866
        // If an entry for this channel is found in reject cache, we'll modify
3✔
2867
        // the entry with the updated timestamp for the direction that was just
3✔
2868
        // written. If the edge doesn't exist, we'll load the cache entry lazily
3✔
2869
        // during the next query for this edge.
3✔
2870
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
6✔
2871
                if isUpdate1 {
6✔
2872
                        entry.upd1Time = e.LastUpdate.Unix()
3✔
2873
                } else {
6✔
2874
                        entry.upd2Time = e.LastUpdate.Unix()
3✔
2875
                }
3✔
2876
                c.rejectCache.insert(e.ChannelID, entry)
3✔
2877
        }
2878

2879
        // If an entry for this channel is found in channel cache, we'll modify
2880
        // the entry with the updated policy for the direction that was just
2881
        // written. If the edge doesn't exist, we'll defer loading the info and
2882
        // policies and lazily read from disk during the next query.
2883
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
6✔
2884
                if isUpdate1 {
6✔
2885
                        channel.Policy1 = e
3✔
2886
                } else {
6✔
2887
                        channel.Policy2 = e
3✔
2888
                }
3✔
2889
                c.chanCache.insert(e.ChannelID, channel)
3✔
2890
        }
2891
}
2892

2893
// updateEdgePolicy attempts to update an edge's policy within the relevant
2894
// buckets using an existing database transaction. The returned boolean will be
2895
// true if the updated policy belongs to node1, and false if the policy belonged
2896
// to node2.
2897
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy,
2898
        graphCache *GraphCache) (bool, error) {
3✔
2899

3✔
2900
        edges := tx.ReadWriteBucket(edgeBucket)
3✔
2901
        if edges == nil {
3✔
2902
                return false, ErrEdgeNotFound
×
2903
        }
×
2904
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
2905
        if edgeIndex == nil {
3✔
2906
                return false, ErrEdgeNotFound
×
2907
        }
×
2908

2909
        // Create the channelID key be converting the channel ID
2910
        // integer into a byte slice.
2911
        var chanID [8]byte
3✔
2912
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
3✔
2913

3✔
2914
        // With the channel ID, we then fetch the value storing the two
3✔
2915
        // nodes which connect this channel edge.
3✔
2916
        nodeInfo := edgeIndex.Get(chanID[:])
3✔
2917
        if nodeInfo == nil {
3✔
2918
                return false, ErrEdgeNotFound
×
2919
        }
×
2920

2921
        // Depending on the flags value passed above, either the first
2922
        // or second edge policy is being updated.
2923
        var fromNode, toNode []byte
3✔
2924
        var isUpdate1 bool
3✔
2925
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
6✔
2926
                fromNode = nodeInfo[:33]
3✔
2927
                toNode = nodeInfo[33:66]
3✔
2928
                isUpdate1 = true
3✔
2929
        } else {
6✔
2930
                fromNode = nodeInfo[33:66]
3✔
2931
                toNode = nodeInfo[:33]
3✔
2932
                isUpdate1 = false
3✔
2933
        }
3✔
2934

2935
        // Finally, with the direction of the edge being updated
2936
        // identified, we update the on-disk edge representation.
2937
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
3✔
2938
        if err != nil {
3✔
2939
                return false, err
×
2940
        }
×
2941

2942
        var (
3✔
2943
                fromNodePubKey route.Vertex
3✔
2944
                toNodePubKey   route.Vertex
3✔
2945
        )
3✔
2946
        copy(fromNodePubKey[:], fromNode)
3✔
2947
        copy(toNodePubKey[:], toNode)
3✔
2948

3✔
2949
        if graphCache != nil {
6✔
2950
                graphCache.UpdatePolicy(
3✔
2951
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
3✔
2952
                )
3✔
2953
        }
3✔
2954

2955
        return isUpdate1, nil
3✔
2956
}
2957

2958
// isPublic determines whether the node is seen as public within the graph from
2959
// the source node's point of view. An existing database transaction can also be
2960
// specified.
2961
func (c *ChannelGraph) isPublic(tx kvdb.RTx, nodePub route.Vertex,
2962
        sourcePubKey []byte) (bool, error) {
3✔
2963

3✔
2964
        // In order to determine whether this node is publicly advertised within
3✔
2965
        // the graph, we'll need to look at all of its edges and check whether
3✔
2966
        // they extend to any other node than the source node. errDone will be
3✔
2967
        // used to terminate the check early.
3✔
2968
        nodeIsPublic := false
3✔
2969
        errDone := errors.New("done")
3✔
2970
        err := c.ForEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
3✔
2971
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
3✔
2972
                _ *models.ChannelEdgePolicy) error {
6✔
2973

3✔
2974
                // If this edge doesn't extend to the source node, we'll
3✔
2975
                // terminate our search as we can now conclude that the node is
3✔
2976
                // publicly advertised within the graph due to the local node
3✔
2977
                // knowing of the current edge.
3✔
2978
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
3✔
2979
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
6✔
2980

3✔
2981
                        nodeIsPublic = true
3✔
2982
                        return errDone
3✔
2983
                }
3✔
2984

2985
                // Since the edge _does_ extend to the source node, we'll also
2986
                // need to ensure that this is a public edge.
2987
                if info.AuthProof != nil {
6✔
2988
                        nodeIsPublic = true
3✔
2989
                        return errDone
3✔
2990
                }
3✔
2991

2992
                // Otherwise, we'll continue our search.
2993
                return nil
3✔
2994
        })
2995
        if err != nil && err != errDone {
3✔
2996
                return false, err
×
2997
        }
×
2998

2999
        return nodeIsPublic, nil
3✔
3000
}
3001

3002
// FetchLightningNodeTx attempts to look up a target node by its identity
3003
// public key. If the node isn't found in the database, then
3004
// ErrGraphNodeNotFound is returned. An optional transaction may be provided.
3005
// If none is provided, then a new one will be created.
3006
func (c *ChannelGraph) FetchLightningNodeTx(tx kvdb.RTx, nodePub route.Vertex) (
3007
        *models.LightningNode, error) {
3✔
3008

3✔
3009
        return c.fetchLightningNode(tx, nodePub)
3✔
3010
}
3✔
3011

3012
// FetchLightningNode attempts to look up a target node by its identity public
3013
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3014
// returned.
3015
func (c *ChannelGraph) FetchLightningNode(nodePub route.Vertex) (
3016
        *models.LightningNode, error) {
3✔
3017

3✔
3018
        return c.fetchLightningNode(nil, nodePub)
3✔
3019
}
3✔
3020

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

3✔
3028
        var node *models.LightningNode
3✔
3029
        fetch := func(tx kvdb.RTx) error {
6✔
3030
                // First grab the nodes bucket which stores the mapping from
3✔
3031
                // pubKey to node information.
3✔
3032
                nodes := tx.ReadBucket(nodeBucket)
3✔
3033
                if nodes == nil {
3✔
3034
                        return ErrGraphNotFound
×
3035
                }
×
3036

3037
                // If a key for this serialized public key isn't found, then
3038
                // the target node doesn't exist within the database.
3039
                nodeBytes := nodes.Get(nodePub[:])
3✔
3040
                if nodeBytes == nil {
6✔
3041
                        return ErrGraphNodeNotFound
3✔
3042
                }
3✔
3043

3044
                // If the node is found, then we can de deserialize the node
3045
                // information to return to the user.
3046
                nodeReader := bytes.NewReader(nodeBytes)
3✔
3047
                n, err := deserializeLightningNode(nodeReader)
3✔
3048
                if err != nil {
3✔
3049
                        return err
×
3050
                }
×
3051

3052
                node = &n
3✔
3053

3✔
3054
                return nil
3✔
3055
        }
3056

3057
        if tx == nil {
6✔
3058
                err := kvdb.View(
3✔
3059
                        c.db, fetch, func() {
6✔
3060
                                node = nil
3✔
3061
                        },
3✔
3062
                )
3063
                if err != nil {
6✔
3064
                        return nil, err
3✔
3065
                }
3✔
3066

3067
                return node, nil
3✔
3068
        }
3069

3070
        err := fetch(tx)
×
3071
        if err != nil {
×
3072
                return nil, err
×
3073
        }
×
3074

3075
        return node, nil
×
3076
}
3077

3078
// HasLightningNode determines if the graph has a vertex identified by the
3079
// target node identity public key. If the node exists in the database, a
3080
// timestamp of when the data for the node was lasted updated is returned along
3081
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3082
// boolean.
3083
func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool,
3084
        error) {
3✔
3085

3✔
3086
        var (
3✔
3087
                updateTime time.Time
3✔
3088
                exists     bool
3✔
3089
        )
3✔
3090

3✔
3091
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3092
                // First grab the nodes bucket which stores the mapping from
3✔
3093
                // pubKey to node information.
3✔
3094
                nodes := tx.ReadBucket(nodeBucket)
3✔
3095
                if nodes == nil {
3✔
3096
                        return ErrGraphNotFound
×
3097
                }
×
3098

3099
                // If a key for this serialized public key isn't found, we can
3100
                // exit early.
3101
                nodeBytes := nodes.Get(nodePub[:])
3✔
3102
                if nodeBytes == nil {
6✔
3103
                        exists = false
3✔
3104
                        return nil
3✔
3105
                }
3✔
3106

3107
                // Otherwise we continue on to obtain the time stamp
3108
                // representing the last time the data for this node was
3109
                // updated.
3110
                nodeReader := bytes.NewReader(nodeBytes)
3✔
3111
                node, err := deserializeLightningNode(nodeReader)
3✔
3112
                if err != nil {
3✔
3113
                        return err
×
3114
                }
×
3115

3116
                exists = true
3✔
3117
                updateTime = node.LastUpdate
3✔
3118
                return nil
3✔
3119
        }, func() {
3✔
3120
                updateTime = time.Time{}
3✔
3121
                exists = false
3✔
3122
        })
3✔
3123
        if err != nil {
3✔
3124
                return time.Time{}, exists, err
×
3125
        }
×
3126

3127
        return updateTime, exists, nil
3✔
3128
}
3129

3130
// nodeTraversal is used to traverse all channels of a node given by its
3131
// public key and passes channel information into the specified callback.
3132
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3133
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3134
                *models.ChannelEdgePolicy) error) error {
3✔
3135

3✔
3136
        traversal := func(tx kvdb.RTx) error {
6✔
3137
                edges := tx.ReadBucket(edgeBucket)
3✔
3138
                if edges == nil {
3✔
3139
                        return ErrGraphNotFound
×
3140
                }
×
3141
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3142
                if edgeIndex == nil {
3✔
3143
                        return ErrGraphNoEdgesFound
×
3144
                }
×
3145

3146
                // In order to reach all the edges for this node, we take
3147
                // advantage of the construction of the key-space within the
3148
                // edge bucket. The keys are stored in the form: pubKey ||
3149
                // chanID. Therefore, starting from a chanID of zero, we can
3150
                // scan forward in the bucket, grabbing all the edges for the
3151
                // node. Once the prefix no longer matches, then we know we're
3152
                // done.
3153
                var nodeStart [33 + 8]byte
3✔
3154
                copy(nodeStart[:], nodePub)
3✔
3155
                copy(nodeStart[33:], chanStart[:])
3✔
3156

3✔
3157
                // Starting from the key pubKey || 0, we seek forward in the
3✔
3158
                // bucket until the retrieved key no longer has the public key
3✔
3159
                // as its prefix. This indicates that we've stepped over into
3✔
3160
                // another node's edges, so we can terminate our scan.
3✔
3161
                edgeCursor := edges.ReadCursor()
3✔
3162
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
6✔
3163
                        // If the prefix still matches, the channel id is
3✔
3164
                        // returned in nodeEdge. Channel id is used to lookup
3✔
3165
                        // the node at the other end of the channel and both
3✔
3166
                        // edge policies.
3✔
3167
                        chanID := nodeEdge[33:]
3✔
3168
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3169
                        if err != nil {
3✔
3170
                                return err
×
3171
                        }
×
3172

3173
                        outgoingPolicy, err := fetchChanEdgePolicy(
3✔
3174
                                edges, chanID, nodePub,
3✔
3175
                        )
3✔
3176
                        if err != nil {
3✔
3177
                                return err
×
3178
                        }
×
3179

3180
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3✔
3181
                        if err != nil {
3✔
3182
                                return err
×
3183
                        }
×
3184

3185
                        incomingPolicy, err := fetchChanEdgePolicy(
3✔
3186
                                edges, chanID, otherNode[:],
3✔
3187
                        )
3✔
3188
                        if err != nil {
3✔
3189
                                return err
×
3190
                        }
×
3191

3192
                        // Finally, we execute the callback.
3193
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3✔
3194
                        if err != nil {
6✔
3195
                                return err
3✔
3196
                        }
3✔
3197
                }
3198

3199
                return nil
3✔
3200
        }
3201

3202
        // If no transaction was provided, then we'll create a new transaction
3203
        // to execute the transaction within.
3204
        if tx == nil {
6✔
3205
                return kvdb.View(db, traversal, func() {})
6✔
3206
        }
3207

3208
        // Otherwise, we re-use the existing transaction to execute the graph
3209
        // traversal.
3210
        return traversal(tx)
3✔
3211
}
3212

3213
// ForEachNodeChannel iterates through all channels of the given node,
3214
// executing the passed callback with an edge info structure and the policies
3215
// of each end of the channel. The first edge policy is the outgoing edge *to*
3216
// the connecting node, while the second is the incoming edge *from* the
3217
// connecting node. If the callback returns an error, then the iteration is
3218
// halted with the error propagated back up to the caller.
3219
//
3220
// Unknown policies are passed into the callback as nil values.
3221
func (c *ChannelGraph) ForEachNodeChannel(nodePub route.Vertex,
3222
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3223
                *models.ChannelEdgePolicy) error) error {
3✔
3224

3✔
3225
        return nodeTraversal(nil, nodePub[:], c.db, cb)
3✔
3226
}
3✔
3227

3228
// ForEachNodeChannelTx iterates through all channels of the given node,
3229
// executing the passed callback with an edge info structure and the policies
3230
// of each end of the channel. The first edge policy is the outgoing edge *to*
3231
// the connecting node, while the second is the incoming edge *from* the
3232
// connecting node. If the callback returns an error, then the iteration is
3233
// halted with the error propagated back up to the caller.
3234
//
3235
// Unknown policies are passed into the callback as nil values.
3236
//
3237
// If the caller wishes to re-use an existing boltdb transaction, then it
3238
// should be passed as the first argument.  Otherwise, the first argument should
3239
// be nil and a fresh transaction will be created to execute the graph
3240
// traversal.
3241
func (c *ChannelGraph) ForEachNodeChannelTx(tx kvdb.RTx,
3242
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3243
                *models.ChannelEdgePolicy,
3244
                *models.ChannelEdgePolicy) error) error {
3✔
3245

3✔
3246
        return nodeTraversal(tx, nodePub[:], c.db, cb)
3✔
3247
}
3✔
3248

3249
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3250
// the target node in the channel. This is useful when one knows the pubkey of
3251
// one of the nodes, and wishes to obtain the full LightningNode for the other
3252
// end of the channel.
3253
func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx,
3254
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3255
        *models.LightningNode, error) {
3✔
3256

3✔
3257
        // Ensure that the node passed in is actually a member of the channel.
3✔
3258
        var targetNodeBytes [33]byte
3✔
3259
        switch {
3✔
3260
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3✔
3261
                targetNodeBytes = channel.NodeKey2Bytes
3✔
3262
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3263
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3264
        default:
×
3265
                return nil, fmt.Errorf("node not participating in this channel")
×
3266
        }
3267

3268
        var targetNode *models.LightningNode
3✔
3269
        fetchNodeFunc := func(tx kvdb.RTx) error {
6✔
3270
                // First grab the nodes bucket which stores the mapping from
3✔
3271
                // pubKey to node information.
3✔
3272
                nodes := tx.ReadBucket(nodeBucket)
3✔
3273
                if nodes == nil {
3✔
3274
                        return ErrGraphNotFound
×
3275
                }
×
3276

3277
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3278
                if err != nil {
3✔
3279
                        return err
×
3280
                }
×
3281

3282
                targetNode = &node
3✔
3283

3✔
3284
                return nil
3✔
3285
        }
3286

3287
        // If the transaction is nil, then we'll need to create a new one,
3288
        // otherwise we can use the existing db transaction.
3289
        var err error
3✔
3290
        if tx == nil {
3✔
3291
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3292
                        targetNode = nil
×
3293
                })
×
3294
        } else {
3✔
3295
                err = fetchNodeFunc(tx)
3✔
3296
        }
3✔
3297

3298
        return targetNode, err
3✔
3299
}
3300

3301
// computeEdgePolicyKeys is a helper function that can be used to compute the
3302
// keys used to index the channel edge policy info for the two nodes of the
3303
// edge. The keys for node 1 and node 2 are returned respectively.
3304
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
3✔
3305
        var (
3✔
3306
                node1Key [33 + 8]byte
3✔
3307
                node2Key [33 + 8]byte
3✔
3308
        )
3✔
3309

3✔
3310
        copy(node1Key[:], info.NodeKey1Bytes[:])
3✔
3311
        copy(node2Key[:], info.NodeKey2Bytes[:])
3✔
3312

3✔
3313
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
3✔
3314
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
3✔
3315

3✔
3316
        return node1Key[:], node2Key[:]
3✔
3317
}
3✔
3318

3319
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3320
// the channel identified by the funding outpoint. If the channel can't be
3321
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3322
// information for the channel itself is returned as well as two structs that
3323
// contain the routing policies for the channel in either direction.
3324
func (c *ChannelGraph) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3325
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3326
        *models.ChannelEdgePolicy, error) {
3✔
3327

3✔
3328
        var (
3✔
3329
                edgeInfo *models.ChannelEdgeInfo
3✔
3330
                policy1  *models.ChannelEdgePolicy
3✔
3331
                policy2  *models.ChannelEdgePolicy
3✔
3332
        )
3✔
3333

3✔
3334
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3335
                // First, grab the node bucket. This will be used to populate
3✔
3336
                // the Node pointers in each edge read from disk.
3✔
3337
                nodes := tx.ReadBucket(nodeBucket)
3✔
3338
                if nodes == nil {
3✔
3339
                        return ErrGraphNotFound
×
3340
                }
×
3341

3342
                // Next, grab the edge bucket which stores the edges, and also
3343
                // the index itself so we can group the directed edges together
3344
                // logically.
3345
                edges := tx.ReadBucket(edgeBucket)
3✔
3346
                if edges == nil {
3✔
3347
                        return ErrGraphNoEdgesFound
×
3348
                }
×
3349
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3350
                if edgeIndex == nil {
3✔
3351
                        return ErrGraphNoEdgesFound
×
3352
                }
×
3353

3354
                // If the channel's outpoint doesn't exist within the outpoint
3355
                // index, then the edge does not exist.
3356
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3357
                if chanIndex == nil {
3✔
3358
                        return ErrGraphNoEdgesFound
×
3359
                }
×
3360
                var b bytes.Buffer
3✔
3361
                if err := WriteOutpoint(&b, op); err != nil {
3✔
3362
                        return err
×
3363
                }
×
3364
                chanID := chanIndex.Get(b.Bytes())
3✔
3365
                if chanID == nil {
6✔
3366
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
3✔
3367
                }
3✔
3368

3369
                // If the channel is found to exists, then we'll first retrieve
3370
                // the general information for the channel.
3371
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3372
                if err != nil {
3✔
3373
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3374
                }
×
3375
                edgeInfo = &edge
3✔
3376

3✔
3377
                // Once we have the information about the channels' parameters,
3✔
3378
                // we'll fetch the routing policies for each for the directed
3✔
3379
                // edges.
3✔
3380
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
3381
                if err != nil {
3✔
3382
                        return fmt.Errorf("failed to find policy: %w", err)
×
3383
                }
×
3384

3385
                policy1 = e1
3✔
3386
                policy2 = e2
3✔
3387
                return nil
3✔
3388
        }, func() {
3✔
3389
                edgeInfo = nil
3✔
3390
                policy1 = nil
3✔
3391
                policy2 = nil
3✔
3392
        })
3✔
3393
        if err != nil {
6✔
3394
                return nil, nil, nil, err
3✔
3395
        }
3✔
3396

3397
        return edgeInfo, policy1, policy2, nil
3✔
3398
}
3399

3400
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3401
// channel identified by the channel ID. If the channel can't be found, then
3402
// ErrEdgeNotFound is returned. A struct which houses the general information
3403
// for the channel itself is returned as well as two structs that contain the
3404
// routing policies for the channel in either direction.
3405
//
3406
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3407
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3408
// the ChannelEdgeInfo will only include the public keys of each node.
3409
func (c *ChannelGraph) FetchChannelEdgesByID(chanID uint64) (
3410
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3411
        *models.ChannelEdgePolicy, error) {
3✔
3412

3✔
3413
        var (
3✔
3414
                edgeInfo  *models.ChannelEdgeInfo
3✔
3415
                policy1   *models.ChannelEdgePolicy
3✔
3416
                policy2   *models.ChannelEdgePolicy
3✔
3417
                channelID [8]byte
3✔
3418
        )
3✔
3419

3✔
3420
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3421
                // First, grab the node bucket. This will be used to populate
3✔
3422
                // the Node pointers in each edge read from disk.
3✔
3423
                nodes := tx.ReadBucket(nodeBucket)
3✔
3424
                if nodes == nil {
3✔
3425
                        return ErrGraphNotFound
×
3426
                }
×
3427

3428
                // Next, grab the edge bucket which stores the edges, and also
3429
                // the index itself so we can group the directed edges together
3430
                // logically.
3431
                edges := tx.ReadBucket(edgeBucket)
3✔
3432
                if edges == nil {
3✔
3433
                        return ErrGraphNoEdgesFound
×
3434
                }
×
3435
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3436
                if edgeIndex == nil {
3✔
3437
                        return ErrGraphNoEdgesFound
×
3438
                }
×
3439

3440
                byteOrder.PutUint64(channelID[:], chanID)
3✔
3441

3✔
3442
                // Now, attempt to fetch edge.
3✔
3443
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
3✔
3444

3✔
3445
                // If it doesn't exist, we'll quickly check our zombie index to
3✔
3446
                // see if we've previously marked it as so.
3✔
3447
                if errors.Is(err, ErrEdgeNotFound) {
6✔
3448
                        // If the zombie index doesn't exist, or the edge is not
3✔
3449
                        // marked as a zombie within it, then we'll return the
3✔
3450
                        // original ErrEdgeNotFound error.
3✔
3451
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
3452
                        if zombieIndex == nil {
3✔
3453
                                return ErrEdgeNotFound
×
3454
                        }
×
3455

3456
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3457
                                zombieIndex, chanID,
3✔
3458
                        )
3✔
3459
                        if !isZombie {
6✔
3460
                                return ErrEdgeNotFound
3✔
3461
                        }
3✔
3462

3463
                        // Otherwise, the edge is marked as a zombie, so we'll
3464
                        // populate the edge info with the public keys of each
3465
                        // party as this is the only information we have about
3466
                        // it and return an error signaling so.
3467
                        edgeInfo = &models.ChannelEdgeInfo{
3✔
3468
                                NodeKey1Bytes: pubKey1,
3✔
3469
                                NodeKey2Bytes: pubKey2,
3✔
3470
                        }
3✔
3471
                        return ErrZombieEdge
3✔
3472
                }
3473

3474
                // Otherwise, we'll just return the error if any.
3475
                if err != nil {
3✔
3476
                        return err
×
3477
                }
×
3478

3479
                edgeInfo = &edge
3✔
3480

3✔
3481
                // Then we'll attempt to fetch the accompanying policies of this
3✔
3482
                // edge.
3✔
3483
                e1, e2, err := fetchChanEdgePolicies(
3✔
3484
                        edgeIndex, edges, channelID[:],
3✔
3485
                )
3✔
3486
                if err != nil {
3✔
3487
                        return err
×
3488
                }
×
3489

3490
                policy1 = e1
3✔
3491
                policy2 = e2
3✔
3492
                return nil
3✔
3493
        }, func() {
3✔
3494
                edgeInfo = nil
3✔
3495
                policy1 = nil
3✔
3496
                policy2 = nil
3✔
3497
        })
3✔
3498
        if err == ErrZombieEdge {
6✔
3499
                return edgeInfo, nil, nil, err
3✔
3500
        }
3✔
3501
        if err != nil {
6✔
3502
                return nil, nil, nil, err
3✔
3503
        }
3✔
3504

3505
        return edgeInfo, policy1, policy2, nil
3✔
3506
}
3507

3508
// IsPublicNode is a helper method that determines whether the node with the
3509
// given public key is seen as a public node in the graph from the graph's
3510
// source node's point of view.
3511
func (c *ChannelGraph) IsPublicNode(pubKey [33]byte) (bool, error) {
3✔
3512
        var nodeIsPublic bool
3✔
3513
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3514
                nodes := tx.ReadBucket(nodeBucket)
3✔
3515
                if nodes == nil {
3✔
3516
                        return ErrGraphNodesNotFound
×
3517
                }
×
3518
                ourPubKey := nodes.Get(sourceKey)
3✔
3519
                if ourPubKey == nil {
3✔
3520
                        return ErrSourceNodeNotSet
×
3521
                }
×
3522
                node, err := fetchLightningNode(nodes, pubKey[:])
3✔
3523
                if err != nil {
3✔
3524
                        return err
×
3525
                }
×
3526

3527
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
3✔
3528
                return err
3✔
3529
        }, func() {
3✔
3530
                nodeIsPublic = false
3✔
3531
        })
3✔
3532
        if err != nil {
3✔
3533
                return false, err
×
3534
        }
×
3535

3536
        return nodeIsPublic, nil
3✔
3537
}
3538

3539
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3540
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
3✔
3541
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
3✔
3542
        if err != nil {
3✔
3543
                return nil, err
×
3544
        }
×
3545

3546
        // With the witness script generated, we'll now turn it into a p2wsh
3547
        // script:
3548
        //  * OP_0 <sha256(script)>
3549
        bldr := txscript.NewScriptBuilder(
3✔
3550
                txscript.WithScriptAllocSize(input.P2WSHSize),
3✔
3551
        )
3✔
3552
        bldr.AddOp(txscript.OP_0)
3✔
3553
        scriptHash := sha256.Sum256(witnessScript)
3✔
3554
        bldr.AddData(scriptHash[:])
3✔
3555

3✔
3556
        return bldr.Script()
3✔
3557
}
3558

3559
// EdgePoint couples the outpoint of a channel with the funding script that it
3560
// creates. The FilteredChainView will use this to watch for spends of this
3561
// edge point on chain. We require both of these values as depending on the
3562
// concrete implementation, either the pkScript, or the out point will be used.
3563
type EdgePoint struct {
3564
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3565
        FundingPkScript []byte
3566

3567
        // OutPoint is the outpoint of the target channel.
3568
        OutPoint wire.OutPoint
3569
}
3570

3571
// String returns a human readable version of the target EdgePoint. We return
3572
// the outpoint directly as it is enough to uniquely identify the edge point.
3573
func (e *EdgePoint) String() string {
×
3574
        return e.OutPoint.String()
×
3575
}
×
3576

3577
// ChannelView returns the verifiable edge information for each active channel
3578
// within the known channel graph. The set of UTXO's (along with their scripts)
3579
// returned are the ones that need to be watched on chain to detect channel
3580
// closes on the resident blockchain.
3581
func (c *ChannelGraph) ChannelView() ([]EdgePoint, error) {
3✔
3582
        var edgePoints []EdgePoint
3✔
3583
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3584
                // We're going to iterate over the entire channel index, so
3✔
3585
                // we'll need to fetch the edgeBucket to get to the index as
3✔
3586
                // it's a sub-bucket.
3✔
3587
                edges := tx.ReadBucket(edgeBucket)
3✔
3588
                if edges == nil {
3✔
3589
                        return ErrGraphNoEdgesFound
×
3590
                }
×
3591
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3592
                if chanIndex == nil {
3✔
3593
                        return ErrGraphNoEdgesFound
×
3594
                }
×
3595
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3596
                if edgeIndex == nil {
3✔
3597
                        return ErrGraphNoEdgesFound
×
3598
                }
×
3599

3600
                // Once we have the proper bucket, we'll range over each key
3601
                // (which is the channel point for the channel) and decode it,
3602
                // accumulating each entry.
3603
                return chanIndex.ForEach(
3✔
3604
                        func(chanPointBytes, chanID []byte) error {
6✔
3605
                                chanPointReader := bytes.NewReader(
3✔
3606
                                        chanPointBytes,
3✔
3607
                                )
3✔
3608

3✔
3609
                                var chanPoint wire.OutPoint
3✔
3610
                                err := ReadOutpoint(chanPointReader, &chanPoint)
3✔
3611
                                if err != nil {
3✔
3612
                                        return err
×
3613
                                }
×
3614

3615
                                edgeInfo, err := fetchChanEdgeInfo(
3✔
3616
                                        edgeIndex, chanID,
3✔
3617
                                )
3✔
3618
                                if err != nil {
3✔
3619
                                        return err
×
3620
                                }
×
3621

3622
                                pkScript, err := genMultiSigP2WSH(
3✔
3623
                                        edgeInfo.BitcoinKey1Bytes[:],
3✔
3624
                                        edgeInfo.BitcoinKey2Bytes[:],
3✔
3625
                                )
3✔
3626
                                if err != nil {
3✔
3627
                                        return err
×
3628
                                }
×
3629

3630
                                edgePoints = append(edgePoints, EdgePoint{
3✔
3631
                                        FundingPkScript: pkScript,
3✔
3632
                                        OutPoint:        chanPoint,
3✔
3633
                                })
3✔
3634

3✔
3635
                                return nil
3✔
3636
                        },
3637
                )
3638
        }, func() {
3✔
3639
                edgePoints = nil
3✔
3640
        }); err != nil {
3✔
3641
                return nil, err
×
3642
        }
×
3643

3644
        return edgePoints, nil
3✔
3645
}
3646

3647
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3648
// zombie. This method is used on an ad-hoc basis, when channels need to be
3649
// marked as zombies outside the normal pruning cycle.
3650
func (c *ChannelGraph) MarkEdgeZombie(chanID uint64,
3651
        pubKey1, pubKey2 [33]byte) error {
×
3652

×
3653
        c.cacheMu.Lock()
×
3654
        defer c.cacheMu.Unlock()
×
3655

×
3656
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
×
3657
                edges := tx.ReadWriteBucket(edgeBucket)
×
3658
                if edges == nil {
×
3659
                        return ErrGraphNoEdgesFound
×
3660
                }
×
3661
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
×
3662
                if err != nil {
×
3663
                        return fmt.Errorf("unable to create zombie "+
×
3664
                                "bucket: %w", err)
×
3665
                }
×
3666

3667
                if c.graphCache != nil {
×
3668
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
×
3669
                }
×
3670

3671
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
×
3672
        })
3673
        if err != nil {
×
3674
                return err
×
3675
        }
×
3676

3677
        c.rejectCache.remove(chanID)
×
3678
        c.chanCache.remove(chanID)
×
3679

×
3680
        return nil
×
3681
}
3682

3683
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3684
// keys should represent the node public keys of the two parties involved in the
3685
// edge.
3686
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3687
        pubKey2 [33]byte) error {
3✔
3688

3✔
3689
        var k [8]byte
3✔
3690
        byteOrder.PutUint64(k[:], chanID)
3✔
3691

3✔
3692
        var v [66]byte
3✔
3693
        copy(v[:33], pubKey1[:])
3✔
3694
        copy(v[33:], pubKey2[:])
3✔
3695

3✔
3696
        return zombieIndex.Put(k[:], v[:])
3✔
3697
}
3✔
3698

3699
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3700
func (c *ChannelGraph) MarkEdgeLive(chanID uint64) error {
×
3701
        c.cacheMu.Lock()
×
3702
        defer c.cacheMu.Unlock()
×
3703

×
3704
        return c.markEdgeLiveUnsafe(nil, chanID)
×
3705
}
×
3706

3707
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3708
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3709
// case a new transaction will be created.
3710
//
3711
// NOTE: this method MUST only be called if the cacheMu has already been
3712
// acquired.
3713
func (c *ChannelGraph) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
×
3714
        dbFn := func(tx kvdb.RwTx) error {
×
3715
                edges := tx.ReadWriteBucket(edgeBucket)
×
3716
                if edges == nil {
×
3717
                        return ErrGraphNoEdgesFound
×
3718
                }
×
3719
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
×
3720
                if zombieIndex == nil {
×
3721
                        return nil
×
3722
                }
×
3723

3724
                var k [8]byte
×
3725
                byteOrder.PutUint64(k[:], chanID)
×
3726

×
3727
                if len(zombieIndex.Get(k[:])) == 0 {
×
3728
                        return ErrZombieEdgeNotFound
×
3729
                }
×
3730

3731
                return zombieIndex.Delete(k[:])
×
3732
        }
3733

3734
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3735
        // the existing transaction
3736
        var err error
×
3737
        if tx == nil {
×
3738
                err = kvdb.Update(c.db, dbFn, func() {})
×
3739
        } else {
×
3740
                err = dbFn(tx)
×
3741
        }
×
3742
        if err != nil {
×
3743
                return err
×
3744
        }
×
3745

3746
        c.rejectCache.remove(chanID)
×
3747
        c.chanCache.remove(chanID)
×
3748

×
3749
        // We need to add the channel back into our graph cache, otherwise we
×
3750
        // won't use it for path finding.
×
3751
        if c.graphCache != nil {
×
3752
                edgeInfos, err := c.fetchChanInfos(tx, []uint64{chanID})
×
3753
                if err != nil {
×
3754
                        return err
×
3755
                }
×
3756

3757
                for _, edgeInfo := range edgeInfos {
×
3758
                        c.graphCache.AddChannel(
×
3759
                                edgeInfo.Info, edgeInfo.Policy1,
×
3760
                                edgeInfo.Policy2,
×
3761
                        )
×
3762
                }
×
3763
        }
3764

3765
        return nil
×
3766
}
3767

3768
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3769
// zombie, then the two node public keys corresponding to this edge are also
3770
// returned.
3771
func (c *ChannelGraph) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
×
3772
        var (
×
3773
                isZombie         bool
×
3774
                pubKey1, pubKey2 [33]byte
×
3775
        )
×
3776

×
3777
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
3778
                edges := tx.ReadBucket(edgeBucket)
×
3779
                if edges == nil {
×
3780
                        return ErrGraphNoEdgesFound
×
3781
                }
×
3782
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
3783
                if zombieIndex == nil {
×
3784
                        return nil
×
3785
                }
×
3786

3787
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
×
3788
                return nil
×
3789
        }, func() {
×
3790
                isZombie = false
×
3791
                pubKey1 = [33]byte{}
×
3792
                pubKey2 = [33]byte{}
×
3793
        })
×
3794
        if err != nil {
×
3795
                return false, [33]byte{}, [33]byte{}
×
3796
        }
×
3797

3798
        return isZombie, pubKey1, pubKey2
×
3799
}
3800

3801
// isZombieEdge returns whether an entry exists for the given channel in the
3802
// zombie index. If an entry exists, then the two node public keys corresponding
3803
// to this edge are also returned.
3804
func isZombieEdge(zombieIndex kvdb.RBucket,
3805
        chanID uint64) (bool, [33]byte, [33]byte) {
3✔
3806

3✔
3807
        var k [8]byte
3✔
3808
        byteOrder.PutUint64(k[:], chanID)
3✔
3809

3✔
3810
        v := zombieIndex.Get(k[:])
3✔
3811
        if v == nil {
6✔
3812
                return false, [33]byte{}, [33]byte{}
3✔
3813
        }
3✔
3814

3815
        var pubKey1, pubKey2 [33]byte
3✔
3816
        copy(pubKey1[:], v[:33])
3✔
3817
        copy(pubKey2[:], v[33:])
3✔
3818

3✔
3819
        return true, pubKey1, pubKey2
3✔
3820
}
3821

3822
// NumZombies returns the current number of zombie channels in the graph.
3823
func (c *ChannelGraph) NumZombies() (uint64, error) {
×
3824
        var numZombies uint64
×
3825
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
×
3826
                edges := tx.ReadBucket(edgeBucket)
×
3827
                if edges == nil {
×
3828
                        return nil
×
3829
                }
×
3830
                zombieIndex := edges.NestedReadBucket(zombieBucket)
×
3831
                if zombieIndex == nil {
×
3832
                        return nil
×
3833
                }
×
3834

3835
                return zombieIndex.ForEach(func(_, _ []byte) error {
×
3836
                        numZombies++
×
3837
                        return nil
×
3838
                })
×
3839
        }, func() {
×
3840
                numZombies = 0
×
3841
        })
×
3842
        if err != nil {
×
3843
                return 0, err
×
3844
        }
×
3845

3846
        return numZombies, nil
×
3847
}
3848

3849
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3850
// that we can ignore channel announcements that we know to be closed without
3851
// having to validate them and fetch a block.
3852
func (c *ChannelGraph) PutClosedScid(scid lnwire.ShortChannelID) error {
×
3853
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
3854
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
×
3855
                if err != nil {
×
3856
                        return err
×
3857
                }
×
3858

3859
                var k [8]byte
×
3860
                byteOrder.PutUint64(k[:], scid.ToUint64())
×
3861

×
3862
                return closedScids.Put(k[:], []byte{})
×
3863
        }, func() {})
×
3864
}
3865

3866
// IsClosedScid checks whether a channel identified by the passed in scid is
3867
// closed. This helps avoid having to perform expensive validation checks.
3868
// TODO: Add an LRU cache to cut down on disc reads.
3869
func (c *ChannelGraph) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
3✔
3870
        var isClosed bool
3✔
3871
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3872
                closedScids := tx.ReadBucket(closedScidBucket)
3✔
3873
                if closedScids == nil {
3✔
3874
                        return ErrClosedScidsNotFound
×
3875
                }
×
3876

3877
                var k [8]byte
3✔
3878
                byteOrder.PutUint64(k[:], scid.ToUint64())
3✔
3879

3✔
3880
                if closedScids.Get(k[:]) != nil {
3✔
3881
                        isClosed = true
×
3882
                        return nil
×
3883
                }
×
3884

3885
                return nil
3✔
3886
        }, func() {
3✔
3887
                isClosed = false
3✔
3888
        })
3✔
3889
        if err != nil {
3✔
3890
                return false, err
×
3891
        }
×
3892

3893
        return isClosed, nil
3✔
3894
}
3895

3896
// GraphSession will provide the call-back with access to a graphdb.CachedGraph
3897
// instance which can be used to perform queries against the channel graph.
3898
// If the graph cache is not enabled, then the call-back will be provided with
3899
// access to the graph via a consistent read-only transaction.
3900
func (c *ChannelGraph) GraphSession(cb func(graph CachedGraph) error) error {
3✔
3901
        var (
3✔
3902
                tx     kvdb.RTx
3✔
3903
                err    error
3✔
3904
                commit = func() {}
6✔
3905
        )
3906
        if c.graphCache == nil {
3✔
NEW
3907
                tx, err = c.db.BeginReadTx()
×
NEW
3908
                if err != nil {
×
NEW
3909
                        return err
×
NEW
3910
                }
×
3911

NEW
3912
                commit = func() {
×
NEW
3913
                        if err := tx.Rollback(); err != nil {
×
NEW
3914
                                log.Errorf("Unable to rollback tx: %v", err)
×
NEW
3915
                        }
×
3916
                }
3917
        }
3918
        defer commit()
3✔
3919

3✔
3920
        return cb(&cachedGraphSession{
3✔
3921
                db: c,
3✔
3922
                tx: tx,
3✔
3923
        })
3✔
3924
}
3925

3926
// cachedGraphSession implements the CachedGraph interface but with a backing
3927
// read only transaction for a consistent view of the graph in the case where
3928
// the graph Cache has not been enabled.
3929
type cachedGraphSession struct {
3930
        tx kvdb.RTx
3931
        db *ChannelGraph
3932
}
3933

3934
// ForEachNodeDirectedChannel calls the callback for every channel of the given
3935
// node.
3936
//
3937
// NOTE: Part of the CachedGraph interface.
3938
func (c *cachedGraphSession) ForEachNodeDirectedChannel(nodePub route.Vertex,
3939
        cb func(channel *DirectedChannel) error) error {
3✔
3940

3✔
3941
        return c.db.forEachNodeDirectedChannel(c.tx, nodePub, cb)
3✔
3942
}
3✔
3943

3944
// FetchNodeFeatures returns the features of the given node. If the node is
3945
// unknown, assume no additional features are supported.
3946
//
3947
// NOTE: Part of the CachedGraph interface.
3948
func (c *cachedGraphSession) FetchNodeFeatures(nodePub route.Vertex) (
3949
        *lnwire.FeatureVector, error) {
3✔
3950

3✔
3951
        return c.db.fetchNodeFeatures(c.tx, nodePub)
3✔
3952
}
3✔
3953

3954
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3955
        updateIndex kvdb.RwBucket, node *models.LightningNode) error {
3✔
3956

3✔
3957
        var (
3✔
3958
                scratch [16]byte
3✔
3959
                b       bytes.Buffer
3✔
3960
        )
3✔
3961

3✔
3962
        pub, err := node.PubKey()
3✔
3963
        if err != nil {
3✔
3964
                return err
×
3965
        }
×
3966
        nodePub := pub.SerializeCompressed()
3✔
3967

3✔
3968
        // If the node has the update time set, write it, else write 0.
3✔
3969
        updateUnix := uint64(0)
3✔
3970
        if node.LastUpdate.Unix() > 0 {
6✔
3971
                updateUnix = uint64(node.LastUpdate.Unix())
3✔
3972
        }
3✔
3973

3974
        byteOrder.PutUint64(scratch[:8], updateUnix)
3✔
3975
        if _, err := b.Write(scratch[:8]); err != nil {
3✔
3976
                return err
×
3977
        }
×
3978

3979
        if _, err := b.Write(nodePub); err != nil {
3✔
3980
                return err
×
3981
        }
×
3982

3983
        // If we got a node announcement for this node, we will have the rest
3984
        // of the data available. If not we don't have more data to write.
3985
        if !node.HaveNodeAnnouncement {
6✔
3986
                // Write HaveNodeAnnouncement=0.
3✔
3987
                byteOrder.PutUint16(scratch[:2], 0)
3✔
3988
                if _, err := b.Write(scratch[:2]); err != nil {
3✔
3989
                        return err
×
3990
                }
×
3991

3992
                return nodeBucket.Put(nodePub, b.Bytes())
3✔
3993
        }
3994

3995
        // Write HaveNodeAnnouncement=1.
3996
        byteOrder.PutUint16(scratch[:2], 1)
3✔
3997
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
3998
                return err
×
3999
        }
×
4000

4001
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
3✔
4002
                return err
×
4003
        }
×
4004
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
3✔
4005
                return err
×
4006
        }
×
4007
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
3✔
4008
                return err
×
4009
        }
×
4010

4011
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
3✔
4012
                return err
×
4013
        }
×
4014

4015
        if err := node.Features.Encode(&b); err != nil {
3✔
4016
                return err
×
4017
        }
×
4018

4019
        numAddresses := uint16(len(node.Addresses))
3✔
4020
        byteOrder.PutUint16(scratch[:2], numAddresses)
3✔
4021
        if _, err := b.Write(scratch[:2]); err != nil {
3✔
4022
                return err
×
4023
        }
×
4024

4025
        for _, address := range node.Addresses {
6✔
4026
                if err := SerializeAddr(&b, address); err != nil {
3✔
4027
                        return err
×
4028
                }
×
4029
        }
4030

4031
        sigLen := len(node.AuthSigBytes)
3✔
4032
        if sigLen > 80 {
3✔
4033
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4034
                        sigLen)
×
4035
        }
×
4036

4037
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
3✔
4038
        if err != nil {
3✔
4039
                return err
×
4040
        }
×
4041

4042
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4043
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4044
        }
×
4045
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
3✔
4046
        if err != nil {
3✔
4047
                return err
×
4048
        }
×
4049

4050
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
3✔
4051
                return err
×
4052
        }
×
4053

4054
        // With the alias bucket updated, we'll now update the index that
4055
        // tracks the time series of node updates.
4056
        var indexKey [8 + 33]byte
3✔
4057
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4058
        copy(indexKey[8:], nodePub)
3✔
4059

3✔
4060
        // If there was already an old index entry for this node, then we'll
3✔
4061
        // delete the old one before we write the new entry.
3✔
4062
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
6✔
4063
                // Extract out the old update time to we can reconstruct the
3✔
4064
                // prior index key to delete it from the index.
3✔
4065
                oldUpdateTime := nodeBytes[:8]
3✔
4066

3✔
4067
                var oldIndexKey [8 + 33]byte
3✔
4068
                copy(oldIndexKey[:8], oldUpdateTime)
3✔
4069
                copy(oldIndexKey[8:], nodePub)
3✔
4070

3✔
4071
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4072
                        return err
×
4073
                }
×
4074
        }
4075

4076
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4077
                return err
×
4078
        }
×
4079

4080
        return nodeBucket.Put(nodePub, b.Bytes())
3✔
4081
}
4082

4083
func fetchLightningNode(nodeBucket kvdb.RBucket,
4084
        nodePub []byte) (models.LightningNode, error) {
3✔
4085

3✔
4086
        nodeBytes := nodeBucket.Get(nodePub)
3✔
4087
        if nodeBytes == nil {
6✔
4088
                return models.LightningNode{}, ErrGraphNodeNotFound
3✔
4089
        }
3✔
4090

4091
        nodeReader := bytes.NewReader(nodeBytes)
3✔
4092
        return deserializeLightningNode(nodeReader)
3✔
4093
}
4094

4095
func deserializeLightningNodeCacheable(r io.Reader) (route.Vertex,
4096
        *lnwire.FeatureVector, error) {
3✔
4097

3✔
4098
        var (
3✔
4099
                pubKey      route.Vertex
3✔
4100
                features    = lnwire.EmptyFeatureVector()
3✔
4101
                nodeScratch [8]byte
3✔
4102
        )
3✔
4103

3✔
4104
        // Skip ahead:
3✔
4105
        // - LastUpdate (8 bytes)
3✔
4106
        if _, err := r.Read(nodeScratch[:]); err != nil {
3✔
4107
                return pubKey, nil, err
×
4108
        }
×
4109

4110
        if _, err := io.ReadFull(r, pubKey[:]); err != nil {
3✔
4111
                return pubKey, nil, err
×
4112
        }
×
4113

4114
        // Read the node announcement flag.
4115
        if _, err := r.Read(nodeScratch[:2]); err != nil {
3✔
4116
                return pubKey, nil, err
×
4117
        }
×
4118
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
3✔
4119

3✔
4120
        // The rest of the data is optional, and will only be there if we got a
3✔
4121
        // node announcement for this node.
3✔
4122
        if hasNodeAnn == 0 {
6✔
4123
                return pubKey, features, nil
3✔
4124
        }
3✔
4125

4126
        // We did get a node announcement for this node, so we'll have the rest
4127
        // of the data available.
4128
        var rgb uint8
3✔
4129
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4130
                return pubKey, nil, err
×
4131
        }
×
4132
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4133
                return pubKey, nil, err
×
4134
        }
×
4135
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
4136
                return pubKey, nil, err
×
4137
        }
×
4138

4139
        if _, err := wire.ReadVarString(r, 0); err != nil {
3✔
4140
                return pubKey, nil, err
×
4141
        }
×
4142

4143
        if err := features.Decode(r); err != nil {
3✔
4144
                return pubKey, nil, err
×
4145
        }
×
4146

4147
        return pubKey, features, nil
3✔
4148
}
4149

4150
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
3✔
4151
        var (
3✔
4152
                node    models.LightningNode
3✔
4153
                scratch [8]byte
3✔
4154
                err     error
3✔
4155
        )
3✔
4156

3✔
4157
        // Always populate a feature vector, even if we don't have a node
3✔
4158
        // announcement and short circuit below.
3✔
4159
        node.Features = lnwire.EmptyFeatureVector()
3✔
4160

3✔
4161
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4162
                return models.LightningNode{}, err
×
4163
        }
×
4164

4165
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4166
        node.LastUpdate = time.Unix(unix, 0)
3✔
4167

3✔
4168
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
3✔
4169
                return models.LightningNode{}, err
×
4170
        }
×
4171

4172
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4173
                return models.LightningNode{}, err
×
4174
        }
×
4175

4176
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
3✔
4177
        if hasNodeAnn == 1 {
6✔
4178
                node.HaveNodeAnnouncement = true
3✔
4179
        } else {
6✔
4180
                node.HaveNodeAnnouncement = false
3✔
4181
        }
3✔
4182

4183
        // The rest of the data is optional, and will only be there if we got a
4184
        // node announcement for this node.
4185
        if !node.HaveNodeAnnouncement {
6✔
4186
                return node, nil
3✔
4187
        }
3✔
4188

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

4201
        node.Alias, err = wire.ReadVarString(r, 0)
3✔
4202
        if err != nil {
3✔
4203
                return models.LightningNode{}, err
×
4204
        }
×
4205

4206
        err = node.Features.Decode(r)
3✔
4207
        if err != nil {
3✔
4208
                return models.LightningNode{}, err
×
4209
        }
×
4210

4211
        if _, err := r.Read(scratch[:2]); err != nil {
3✔
4212
                return models.LightningNode{}, err
×
4213
        }
×
4214
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
3✔
4215

3✔
4216
        var addresses []net.Addr
3✔
4217
        for i := 0; i < numAddresses; i++ {
6✔
4218
                address, err := DeserializeAddr(r)
3✔
4219
                if err != nil {
3✔
4220
                        return models.LightningNode{}, err
×
4221
                }
×
4222
                addresses = append(addresses, address)
3✔
4223
        }
4224
        node.Addresses = addresses
3✔
4225

3✔
4226
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4227
        if err != nil {
3✔
4228
                return models.LightningNode{}, err
×
4229
        }
×
4230

4231
        // We'll try and see if there are any opaque bytes left, if not, then
4232
        // we'll ignore the EOF error and return the node as is.
4233
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4234
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4235
        )
3✔
4236
        switch {
3✔
4237
        case err == io.ErrUnexpectedEOF:
×
4238
        case err == io.EOF:
×
4239
        case err != nil:
×
4240
                return models.LightningNode{}, err
×
4241
        }
4242

4243
        return node, nil
3✔
4244
}
4245

4246
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4247
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
3✔
4248

3✔
4249
        var b bytes.Buffer
3✔
4250

3✔
4251
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4252
                return err
×
4253
        }
×
4254
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4255
                return err
×
4256
        }
×
4257
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4258
                return err
×
4259
        }
×
4260
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4261
                return err
×
4262
        }
×
4263

4264
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
3✔
4265
                return err
×
4266
        }
×
4267

4268
        authProof := edgeInfo.AuthProof
3✔
4269
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
3✔
4270
        if authProof != nil {
6✔
4271
                nodeSig1 = authProof.NodeSig1Bytes
3✔
4272
                nodeSig2 = authProof.NodeSig2Bytes
3✔
4273
                bitcoinSig1 = authProof.BitcoinSig1Bytes
3✔
4274
                bitcoinSig2 = authProof.BitcoinSig2Bytes
3✔
4275
        }
3✔
4276

4277
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
3✔
4278
                return err
×
4279
        }
×
4280
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
3✔
4281
                return err
×
4282
        }
×
4283
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
3✔
4284
                return err
×
4285
        }
×
4286
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
3✔
4287
                return err
×
4288
        }
×
4289

4290
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
4291
                return err
×
4292
        }
×
4293
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
3✔
4294
        if err != nil {
3✔
4295
                return err
×
4296
        }
×
4297
        if _, err := b.Write(chanID[:]); err != nil {
3✔
4298
                return err
×
4299
        }
×
4300
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
3✔
4301
                return err
×
4302
        }
×
4303

4304
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4305
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4306
        }
×
4307
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
3✔
4308
        if err != nil {
3✔
4309
                return err
×
4310
        }
×
4311

4312
        return edgeIndex.Put(chanID[:], b.Bytes())
3✔
4313
}
4314

4315
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4316
        chanID []byte) (models.ChannelEdgeInfo, error) {
3✔
4317

3✔
4318
        edgeInfoBytes := edgeIndex.Get(chanID)
3✔
4319
        if edgeInfoBytes == nil {
6✔
4320
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
3✔
4321
        }
3✔
4322

4323
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
3✔
4324
        return deserializeChanEdgeInfo(edgeInfoReader)
3✔
4325
}
4326

4327
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
3✔
4328
        var (
3✔
4329
                err      error
3✔
4330
                edgeInfo models.ChannelEdgeInfo
3✔
4331
        )
3✔
4332

3✔
4333
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
3✔
4334
                return models.ChannelEdgeInfo{}, err
×
4335
        }
×
4336
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
3✔
4337
                return models.ChannelEdgeInfo{}, err
×
4338
        }
×
4339
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
3✔
4340
                return models.ChannelEdgeInfo{}, err
×
4341
        }
×
4342
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
3✔
4343
                return models.ChannelEdgeInfo{}, err
×
4344
        }
×
4345

4346
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
3✔
4347
        if err != nil {
3✔
4348
                return models.ChannelEdgeInfo{}, err
×
4349
        }
×
4350

4351
        proof := &models.ChannelAuthProof{}
3✔
4352

3✔
4353
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4354
        if err != nil {
3✔
4355
                return models.ChannelEdgeInfo{}, err
×
4356
        }
×
4357
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4358
        if err != nil {
3✔
4359
                return models.ChannelEdgeInfo{}, err
×
4360
        }
×
4361
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4362
        if err != nil {
3✔
4363
                return models.ChannelEdgeInfo{}, err
×
4364
        }
×
4365
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
3✔
4366
        if err != nil {
3✔
4367
                return models.ChannelEdgeInfo{}, err
×
4368
        }
×
4369

4370
        if !proof.IsEmpty() {
6✔
4371
                edgeInfo.AuthProof = proof
3✔
4372
        }
3✔
4373

4374
        edgeInfo.ChannelPoint = wire.OutPoint{}
3✔
4375
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
3✔
4376
                return models.ChannelEdgeInfo{}, err
×
4377
        }
×
4378
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
3✔
4379
                return models.ChannelEdgeInfo{}, err
×
4380
        }
×
4381
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
3✔
4382
                return models.ChannelEdgeInfo{}, err
×
4383
        }
×
4384

4385
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
3✔
4386
                return models.ChannelEdgeInfo{}, err
×
4387
        }
×
4388

4389
        // We'll try and see if there are any opaque bytes left, if not, then
4390
        // we'll ignore the EOF error and return the edge as is.
4391
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4392
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4393
        )
3✔
4394
        switch {
3✔
4395
        case err == io.ErrUnexpectedEOF:
×
4396
        case err == io.EOF:
×
4397
        case err != nil:
×
4398
                return models.ChannelEdgeInfo{}, err
×
4399
        }
4400

4401
        return edgeInfo, nil
3✔
4402
}
4403

4404
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4405
        from, to []byte) error {
3✔
4406

3✔
4407
        var edgeKey [33 + 8]byte
3✔
4408
        copy(edgeKey[:], from)
3✔
4409
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
3✔
4410

3✔
4411
        var b bytes.Buffer
3✔
4412
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
3✔
4413
                return err
×
4414
        }
×
4415

4416
        // Before we write out the new edge, we'll create a new entry in the
4417
        // update index in order to keep it fresh.
4418
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4419
        var indexKey [8 + 8]byte
3✔
4420
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4421
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
3✔
4422

3✔
4423
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
4424
        if err != nil {
3✔
4425
                return err
×
4426
        }
×
4427

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

3✔
4435
                // In order to delete the old entry, we'll need to obtain the
3✔
4436
                // *prior* update time in order to delete it. To do this, we'll
3✔
4437
                // need to deserialize the existing policy within the database
3✔
4438
                // (now outdated by the new one), and delete its corresponding
3✔
4439
                // entry within the update index. We'll ignore any
3✔
4440
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
3✔
4441
                // the channel ID and update time to delete the entry.
3✔
4442
                // TODO(halseth): get rid of these invalid policies in a
3✔
4443
                // migration.
3✔
4444
                oldEdgePolicy, err := deserializeChanEdgePolicy(
3✔
4445
                        bytes.NewReader(edgeBytes),
3✔
4446
                )
3✔
4447
                if err != nil && err != ErrEdgePolicyOptionalFieldNotFound {
3✔
4448
                        return err
×
4449
                }
×
4450

4451
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
3✔
4452

3✔
4453
                var oldIndexKey [8 + 8]byte
3✔
4454
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
3✔
4455
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
3✔
4456

3✔
4457
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
3✔
4458
                        return err
×
4459
                }
×
4460
        }
4461

4462
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
3✔
4463
                return err
×
4464
        }
×
4465

4466
        err = updateEdgePolicyDisabledIndex(
3✔
4467
                edges, edge.ChannelID,
3✔
4468
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
3✔
4469
                edge.IsDisabled(),
3✔
4470
        )
3✔
4471
        if err != nil {
3✔
4472
                return err
×
4473
        }
×
4474

4475
        return edges.Put(edgeKey[:], b.Bytes()[:])
3✔
4476
}
4477

4478
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4479
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4480
// one.
4481
// The direction represents the direction of the edge and disabled is used for
4482
// deciding whether to remove or add an entry to the bucket.
4483
// In general a channel is disabled if two entries for the same chanID exist
4484
// in this bucket.
4485
// Maintaining the bucket this way allows a fast retrieval of disabled
4486
// channels, for example when prune is needed.
4487
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4488
        direction bool, disabled bool) error {
3✔
4489

3✔
4490
        var disabledEdgeKey [8 + 1]byte
3✔
4491
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
3✔
4492
        if direction {
6✔
4493
                disabledEdgeKey[8] = 1
3✔
4494
        }
3✔
4495

4496
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
3✔
4497
                disabledEdgePolicyBucket,
3✔
4498
        )
3✔
4499
        if err != nil {
3✔
4500
                return err
×
4501
        }
×
4502

4503
        if disabled {
6✔
4504
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
3✔
4505
        }
3✔
4506

4507
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
3✔
4508
}
4509

4510
// putChanEdgePolicyUnknown marks the edge policy as unknown
4511
// in the edges bucket.
4512
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4513
        from []byte) error {
3✔
4514

3✔
4515
        var edgeKey [33 + 8]byte
3✔
4516
        copy(edgeKey[:], from)
3✔
4517
        byteOrder.PutUint64(edgeKey[33:], channelID)
3✔
4518

3✔
4519
        if edges.Get(edgeKey[:]) != nil {
3✔
4520
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4521
                        " when there is already a policy present", channelID)
×
4522
        }
×
4523

4524
        return edges.Put(edgeKey[:], unknownPolicy)
3✔
4525
}
4526

4527
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4528
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
3✔
4529

3✔
4530
        var edgeKey [33 + 8]byte
3✔
4531
        copy(edgeKey[:], nodePub)
3✔
4532
        copy(edgeKey[33:], chanID[:])
3✔
4533

3✔
4534
        edgeBytes := edges.Get(edgeKey[:])
3✔
4535
        if edgeBytes == nil {
3✔
4536
                return nil, ErrEdgeNotFound
×
4537
        }
×
4538

4539
        // No need to deserialize unknown policy.
4540
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
6✔
4541
                return nil, nil
3✔
4542
        }
3✔
4543

4544
        edgeReader := bytes.NewReader(edgeBytes)
3✔
4545

3✔
4546
        ep, err := deserializeChanEdgePolicy(edgeReader)
3✔
4547
        switch {
3✔
4548
        // If the db policy was missing an expected optional field, we return
4549
        // nil as if the policy was unknown.
4550
        case err == ErrEdgePolicyOptionalFieldNotFound:
×
4551
                return nil, nil
×
4552

4553
        case err != nil:
×
4554
                return nil, err
×
4555
        }
4556

4557
        return ep, nil
3✔
4558
}
4559

4560
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4561
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4562
        error) {
3✔
4563

3✔
4564
        edgeInfo := edgeIndex.Get(chanID)
3✔
4565
        if edgeInfo == nil {
3✔
4566
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4567
                        chanID)
×
4568
        }
×
4569

4570
        // The first node is contained within the first half of the edge
4571
        // information. We only propagate the error here and below if it's
4572
        // something other than edge non-existence.
4573
        node1Pub := edgeInfo[:33]
3✔
4574
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
3✔
4575
        if err != nil {
3✔
4576
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4577
                        node1Pub)
×
4578
        }
×
4579

4580
        // Similarly, the second node is contained within the latter
4581
        // half of the edge information.
4582
        node2Pub := edgeInfo[33:66]
3✔
4583
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
3✔
4584
        if err != nil {
3✔
4585
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4586
                        node2Pub)
×
4587
        }
×
4588

4589
        return edge1, edge2, nil
3✔
4590
}
4591

4592
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4593
        to []byte) error {
3✔
4594

3✔
4595
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
3✔
4596
        if err != nil {
3✔
4597
                return err
×
4598
        }
×
4599

4600
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
3✔
4601
                return err
×
4602
        }
×
4603

4604
        var scratch [8]byte
3✔
4605
        updateUnix := uint64(edge.LastUpdate.Unix())
3✔
4606
        byteOrder.PutUint64(scratch[:], updateUnix)
3✔
4607
        if _, err := w.Write(scratch[:]); err != nil {
3✔
4608
                return err
×
4609
        }
×
4610

4611
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
3✔
4612
                return err
×
4613
        }
×
4614
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
3✔
4615
                return err
×
4616
        }
×
4617
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
3✔
4618
                return err
×
4619
        }
×
4620
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
3✔
4621
                return err
×
4622
        }
×
4623
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
3✔
4624
        if err != nil {
3✔
4625
                return err
×
4626
        }
×
4627
        err = binary.Write(
3✔
4628
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
3✔
4629
        )
3✔
4630
        if err != nil {
3✔
4631
                return err
×
4632
        }
×
4633

4634
        if _, err := w.Write(to); err != nil {
3✔
4635
                return err
×
4636
        }
×
4637

4638
        // If the max_htlc field is present, we write it. To be compatible with
4639
        // older versions that wasn't aware of this field, we write it as part
4640
        // of the opaque data.
4641
        // TODO(halseth): clean up when moving to TLV.
4642
        var opaqueBuf bytes.Buffer
3✔
4643
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4644
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
3✔
4645
                if err != nil {
3✔
4646
                        return err
×
4647
                }
×
4648
        }
4649

4650
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
3✔
4651
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4652
        }
×
4653
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
3✔
4654
                return err
×
4655
        }
×
4656

4657
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
3✔
4658
                return err
×
4659
        }
×
4660
        return nil
3✔
4661
}
4662

4663
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
3✔
4664
        // Deserialize the policy. Note that in case an optional field is not
3✔
4665
        // found, both an error and a populated policy object are returned.
3✔
4666
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
3✔
4667
        if deserializeErr != nil &&
3✔
4668
                deserializeErr != ErrEdgePolicyOptionalFieldNotFound {
3✔
4669

×
4670
                return nil, deserializeErr
×
4671
        }
×
4672

4673
        return edge, deserializeErr
3✔
4674
}
4675

4676
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4677
        error) {
3✔
4678

3✔
4679
        edge := &models.ChannelEdgePolicy{}
3✔
4680

3✔
4681
        var err error
3✔
4682
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4683
        if err != nil {
3✔
4684
                return nil, err
×
4685
        }
×
4686

4687
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
3✔
4688
                return nil, err
×
4689
        }
×
4690

4691
        var scratch [8]byte
3✔
4692
        if _, err := r.Read(scratch[:]); err != nil {
3✔
4693
                return nil, err
×
4694
        }
×
4695
        unix := int64(byteOrder.Uint64(scratch[:]))
3✔
4696
        edge.LastUpdate = time.Unix(unix, 0)
3✔
4697

3✔
4698
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
3✔
4699
                return nil, err
×
4700
        }
×
4701
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
3✔
4702
                return nil, err
×
4703
        }
×
4704
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
3✔
4705
                return nil, err
×
4706
        }
×
4707

4708
        var n uint64
3✔
4709
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4710
                return nil, err
×
4711
        }
×
4712
        edge.MinHTLC = lnwire.MilliSatoshi(n)
3✔
4713

3✔
4714
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4715
                return nil, err
×
4716
        }
×
4717
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
3✔
4718

3✔
4719
        if err := binary.Read(r, byteOrder, &n); err != nil {
3✔
4720
                return nil, err
×
4721
        }
×
4722
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
3✔
4723

3✔
4724
        if _, err := r.Read(edge.ToNode[:]); err != nil {
3✔
4725
                return nil, err
×
4726
        }
×
4727

4728
        // We'll try and see if there are any opaque bytes left, if not, then
4729
        // we'll ignore the EOF error and return the edge as is.
4730
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
3✔
4731
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4732
        )
3✔
4733
        switch {
3✔
4734
        case err == io.ErrUnexpectedEOF:
×
4735
        case err == io.EOF:
×
4736
        case err != nil:
×
4737
                return nil, err
×
4738
        }
4739

4740
        // See if optional fields are present.
4741
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4742
                // The max_htlc field should be at the beginning of the opaque
3✔
4743
                // bytes.
3✔
4744
                opq := edge.ExtraOpaqueData
3✔
4745

3✔
4746
                // If the max_htlc field is not present, it might be old data
3✔
4747
                // stored before this field was validated. We'll return the
3✔
4748
                // edge along with an error.
3✔
4749
                if len(opq) < 8 {
3✔
4750
                        return edge, ErrEdgePolicyOptionalFieldNotFound
×
4751
                }
×
4752

4753
                maxHtlc := byteOrder.Uint64(opq[:8])
3✔
4754
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
3✔
4755

3✔
4756
                // Exclude the parsed field from the rest of the opaque data.
3✔
4757
                edge.ExtraOpaqueData = opq[8:]
3✔
4758
        }
4759

4760
        return edge, nil
3✔
4761
}
4762

4763
// chanGraphNodeTx is an implementation of the NodeRTx interface backed by the
4764
// ChannelGraph and a kvdb.RTx.
4765
type chanGraphNodeTx struct {
4766
        tx   kvdb.RTx
4767
        db   *ChannelGraph
4768
        node *models.LightningNode
4769
}
4770

4771
// A compile-time constraint to ensure chanGraphNodeTx implements the NodeRTx
4772
// interface.
4773
var _ NodeRTx = (*chanGraphNodeTx)(nil)
4774

4775
func newChanGraphNodeTx(tx kvdb.RTx, db *ChannelGraph,
4776
        node *models.LightningNode) *chanGraphNodeTx {
3✔
4777

3✔
4778
        return &chanGraphNodeTx{
3✔
4779
                tx:   tx,
3✔
4780
                db:   db,
3✔
4781
                node: node,
3✔
4782
        }
3✔
4783
}
3✔
4784

4785
// Node returns the raw information of the node.
4786
//
4787
// NOTE: This is a part of the NodeRTx interface.
4788
func (c *chanGraphNodeTx) Node() *models.LightningNode {
3✔
4789
        return c.node
3✔
4790
}
3✔
4791

4792
// FetchNode fetches the node with the given pub key under the same transaction
4793
// used to fetch the current node. The returned node is also a NodeRTx and any
4794
// operations on that NodeRTx will also be done under the same transaction.
4795
//
4796
// NOTE: This is a part of the NodeRTx interface.
4797
func (c *chanGraphNodeTx) FetchNode(nodePub route.Vertex) (NodeRTx, error) {
×
4798
        node, err := c.db.FetchLightningNodeTx(c.tx, nodePub)
×
4799
        if err != nil {
×
4800
                return nil, err
×
4801
        }
×
4802

4803
        return newChanGraphNodeTx(c.tx, c.db, node), nil
×
4804
}
4805

4806
// ForEachChannel can be used to iterate over the node's channels under
4807
// the same transaction used to fetch the node.
4808
//
4809
// NOTE: This is a part of the NodeRTx interface.
4810
func (c *chanGraphNodeTx) ForEachChannel(f func(*models.ChannelEdgeInfo,
4811
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
×
4812

×
4813
        return c.db.ForEachNodeChannelTx(c.tx, c.node.PubKeyBytes,
×
4814
                func(_ kvdb.RTx, info *models.ChannelEdgeInfo, policy1,
×
4815
                        policy2 *models.ChannelEdgePolicy) error {
×
4816

×
4817
                        return f(info, policy1, policy2)
×
4818
                },
×
4819
        )
4820
}
4821

4822
// MakeTestGraph creates a new instance of the ChannelGraph for testing
4823
// purposes.
4824
func MakeTestGraph(t testing.TB, modifiers ...OptionModifier) (*ChannelGraph,
4825
        error) {
×
4826

×
4827
        opts := DefaultOptions()
×
4828
        for _, modifier := range modifiers {
×
4829
                modifier(opts)
×
4830
        }
×
4831

4832
        // Next, create channelgraph for the first time.
4833
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
×
4834
        if err != nil {
×
4835
                backendCleanup()
×
4836
                return nil, err
×
4837
        }
×
4838

4839
        graph, err := NewChannelGraph(backend)
×
4840
        if err != nil {
×
4841
                backendCleanup()
×
4842
                return nil, err
×
4843
        }
×
4844

4845
        t.Cleanup(func() {
×
4846
                _ = backend.Close()
×
4847
                backendCleanup()
×
4848
        })
×
4849

4850
        return graph, nil
×
4851
}
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