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

lightningnetwork / lnd / 12430728843

20 Dec 2024 11:36AM UTC coverage: 61.336% (+2.6%) from 58.716%
12430728843

Pull #8777

github

ziggie1984
channeldb: fix typo.
Pull Request #8777: multi: make reassignment of alias channel edge atomic

161 of 213 new or added lines in 7 files covered. (75.59%)

70 existing lines in 17 files now uncovered.

23369 of 38100 relevant lines covered (61.34%)

115813.77 hits per line

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

77.16
/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) {
178✔
202

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

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

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

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

145✔
234
                err := g.ForEachNodeCacheable(
145✔
235
                        func(tx kvdb.RTx, node GraphCacheNode) error {
249✔
236
                                g.graphCache.AddNodeFeatures(node)
104✔
237

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

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

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

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

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

260
        return g, nil
178✔
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) {
149✔
273

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

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

589✔
285
                        return nil
589✔
286
                }
589✔
287

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

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

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

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

994✔
307
                switch {
994✔
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
994✔
318

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

325
        return channelMap, nil
149✔
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 {
178✔
360
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
356✔
361
                for _, tlb := range graphTopLevelBuckets {
878✔
362
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
700✔
363
                                return err
×
364
                        }
×
365
                }
366

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

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

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

403
        return nil
178✔
404
}
405

406
// NewPathFindTx returns a new read transaction that can be used for a single
407
// path finding session. Will return nil if the graph cache is enabled.
408
func (c *ChannelGraph) NewPathFindTx() (kvdb.RTx, error) {
137✔
409
        if c.graphCache != nil {
220✔
410
                return nil, nil
83✔
411
        }
83✔
412

413
        return c.db.BeginReadTx()
54✔
414
}
415

416
// AddrsForNode returns all known addresses for the target node public key that
417
// the graph DB is aware of. The returned boolean indicates if the given node is
418
// unknown to the graph DB or not.
419
//
420
// NOTE: this is part of the channeldb.AddrSource interface.
421
func (c *ChannelGraph) AddrsForNode(nodePub *btcec.PublicKey) (bool, []net.Addr,
422
        error) {
5✔
423

5✔
424
        pubKey, err := route.NewVertexFromBytes(nodePub.SerializeCompressed())
5✔
425
        if err != nil {
5✔
426
                return false, nil, err
×
427
        }
×
428

429
        node, err := c.FetchLightningNode(pubKey)
5✔
430
        // We don't consider it an error if the graph is unaware of the node.
5✔
431
        switch {
5✔
432
        case err != nil && !errors.Is(err, ErrGraphNodeNotFound):
×
433
                return false, nil, err
×
434

435
        case errors.Is(err, ErrGraphNodeNotFound):
4✔
436
                return false, nil, nil
4✔
437
        }
438

439
        return true, node.Addresses, nil
5✔
440
}
441

442
// ForEachChannel iterates through all the channel edges stored within the
443
// graph and invokes the passed callback for each edge. The callback takes two
444
// edges as since this is a directed graph, both the in/out edges are visited.
445
// If the callback returns an error, then the transaction is aborted and the
446
// iteration stops early.
447
//
448
// NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer
449
// for that particular channel edge routing policy will be passed into the
450
// callback.
451
func (c *ChannelGraph) ForEachChannel(cb func(*models.ChannelEdgeInfo,
452
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
149✔
453

149✔
454
        return c.db.View(func(tx kvdb.RTx) error {
298✔
455
                edges := tx.ReadBucket(edgeBucket)
149✔
456
                if edges == nil {
149✔
457
                        return ErrGraphNoEdgesFound
×
458
                }
×
459

460
                // First, load all edges in memory indexed by node and channel
461
                // id.
462
                channelMap, err := c.getChannelMap(edges)
149✔
463
                if err != nil {
149✔
464
                        return err
×
465
                }
×
466

467
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
149✔
468
                if edgeIndex == nil {
149✔
469
                        return ErrGraphNoEdgesFound
×
470
                }
×
471

472
                // Load edge index, recombine each channel with the policies
473
                // loaded above and invoke the callback.
474
                return kvdb.ForAll(
149✔
475
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
648✔
476
                                var chanID [8]byte
499✔
477
                                copy(chanID[:], k)
499✔
478

499✔
479
                                edgeInfoReader := bytes.NewReader(edgeInfoBytes)
499✔
480
                                info, err := deserializeChanEdgeInfo(
499✔
481
                                        edgeInfoReader,
499✔
482
                                )
499✔
483
                                if err != nil {
499✔
484
                                        return err
×
485
                                }
×
486

487
                                policy1 := channelMap[channelMapKey{
499✔
488
                                        nodeKey: info.NodeKey1Bytes,
499✔
489
                                        chanID:  chanID,
499✔
490
                                }]
499✔
491

499✔
492
                                policy2 := channelMap[channelMapKey{
499✔
493
                                        nodeKey: info.NodeKey2Bytes,
499✔
494
                                        chanID:  chanID,
499✔
495
                                }]
499✔
496

499✔
497
                                return cb(&info, policy1, policy2)
499✔
498
                        },
499
                )
500
        }, func() {})
149✔
501
}
502

503
// ForEachNodeDirectedChannel iterates through all channels of a given node,
504
// executing the passed callback on the directed edge representing the channel
505
// and its incoming policy. If the callback returns an error, then the iteration
506
// is halted with the error propagated back up to the caller.
507
//
508
// Unknown policies are passed into the callback as nil values.
509
func (c *ChannelGraph) ForEachNodeDirectedChannel(tx kvdb.RTx,
510
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
708✔
511

708✔
512
        if c.graphCache != nil {
1,174✔
513
                return c.graphCache.ForEachChannel(node, cb)
466✔
514
        }
466✔
515

516
        // Fallback that uses the database.
517
        toNodeCallback := func() route.Vertex {
382✔
518
                return node
136✔
519
        }
136✔
520
        toNodeFeatures, err := c.FetchNodeFeatures(node)
246✔
521
        if err != nil {
246✔
522
                return err
×
523
        }
×
524

525
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
246✔
526
                p2 *models.ChannelEdgePolicy) error {
746✔
527

500✔
528
                var cachedInPolicy *models.CachedEdgePolicy
500✔
529
                if p2 != nil {
997✔
530
                        cachedInPolicy = models.NewCachedPolicy(p2)
497✔
531
                        cachedInPolicy.ToNodePubKey = toNodeCallback
497✔
532
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
497✔
533
                }
497✔
534

535
                var inboundFee lnwire.Fee
500✔
536
                if p1 != nil {
999✔
537
                        // Extract inbound fee. If there is a decoding error,
499✔
538
                        // skip this edge.
499✔
539
                        _, err := p1.ExtraOpaqueData.ExtractRecords(&inboundFee)
499✔
540
                        if err != nil {
500✔
541
                                return nil
1✔
542
                        }
1✔
543
                }
544

545
                directedChannel := &DirectedChannel{
499✔
546
                        ChannelID:    e.ChannelID,
499✔
547
                        IsNode1:      node == e.NodeKey1Bytes,
499✔
548
                        OtherNode:    e.NodeKey2Bytes,
499✔
549
                        Capacity:     e.Capacity,
499✔
550
                        OutPolicySet: p1 != nil,
499✔
551
                        InPolicy:     cachedInPolicy,
499✔
552
                        InboundFee:   inboundFee,
499✔
553
                }
499✔
554

499✔
555
                if node == e.NodeKey2Bytes {
751✔
556
                        directedChannel.OtherNode = e.NodeKey1Bytes
252✔
557
                }
252✔
558

559
                return cb(directedChannel)
499✔
560
        }
561
        return nodeTraversal(tx, node[:], c.db, dbCallback)
246✔
562
}
563

564
// FetchNodeFeatures returns the features of a given node. If no features are
565
// known for the node, an empty feature vector is returned.
566
func (c *ChannelGraph) FetchNodeFeatures(
567
        node route.Vertex) (*lnwire.FeatureVector, error) {
1,143✔
568

1,143✔
569
        if c.graphCache != nil {
1,600✔
570
                return c.graphCache.GetFeatures(node), nil
457✔
571
        }
457✔
572

573
        // Fallback that uses the database.
574
        targetNode, err := c.FetchLightningNode(node)
690✔
575
        switch err {
690✔
576
        // If the node exists and has features, return them directly.
577
        case nil:
679✔
578
                return targetNode.Features, nil
679✔
579

580
        // If we couldn't find a node announcement, populate a blank feature
581
        // vector.
582
        case ErrGraphNodeNotFound:
11✔
583
                return lnwire.EmptyFeatureVector(), nil
11✔
584

585
        // Otherwise, bubble the error up.
586
        default:
×
587
                return nil, err
×
588
        }
589
}
590

591
// ForEachNodeCached is similar to ForEachNode, but it utilizes the channel
592
// graph cache instead. Note that this doesn't return all the information the
593
// regular ForEachNode method does.
594
//
595
// NOTE: The callback contents MUST not be modified.
596
func (c *ChannelGraph) ForEachNodeCached(cb func(node route.Vertex,
597
        chans map[uint64]*DirectedChannel) error) error {
1✔
598

1✔
599
        if c.graphCache != nil {
1✔
600
                return c.graphCache.ForEachNode(cb)
×
601
        }
×
602

603
        // Otherwise call back to a version that uses the database directly.
604
        // We'll iterate over each node, then the set of channels for each
605
        // node, and construct a similar callback functiopn signature as the
606
        // main funcotin expects.
607
        return c.ForEachNode(func(tx kvdb.RTx,
1✔
608
                node *models.LightningNode) error {
21✔
609

20✔
610
                channels := make(map[uint64]*DirectedChannel)
20✔
611

20✔
612
                err := c.ForEachNodeChannelTx(tx, node.PubKeyBytes,
20✔
613
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
20✔
614
                                p1 *models.ChannelEdgePolicy,
20✔
615
                                p2 *models.ChannelEdgePolicy) error {
210✔
616

190✔
617
                                toNodeCallback := func() route.Vertex {
190✔
618
                                        return node.PubKeyBytes
×
619
                                }
×
620
                                toNodeFeatures, err := c.FetchNodeFeatures(
190✔
621
                                        node.PubKeyBytes,
190✔
622
                                )
190✔
623
                                if err != nil {
190✔
624
                                        return err
×
625
                                }
×
626

627
                                var cachedInPolicy *models.CachedEdgePolicy
190✔
628
                                if p2 != nil {
380✔
629
                                        cachedInPolicy =
190✔
630
                                                models.NewCachedPolicy(p2)
190✔
631
                                        cachedInPolicy.ToNodePubKey =
190✔
632
                                                toNodeCallback
190✔
633
                                        cachedInPolicy.ToNodeFeatures =
190✔
634
                                                toNodeFeatures
190✔
635
                                }
190✔
636

637
                                directedChannel := &DirectedChannel{
190✔
638
                                        ChannelID: e.ChannelID,
190✔
639
                                        IsNode1: node.PubKeyBytes ==
190✔
640
                                                e.NodeKey1Bytes,
190✔
641
                                        OtherNode:    e.NodeKey2Bytes,
190✔
642
                                        Capacity:     e.Capacity,
190✔
643
                                        OutPolicySet: p1 != nil,
190✔
644
                                        InPolicy:     cachedInPolicy,
190✔
645
                                }
190✔
646

190✔
647
                                if node.PubKeyBytes == e.NodeKey2Bytes {
285✔
648
                                        directedChannel.OtherNode =
95✔
649
                                                e.NodeKey1Bytes
95✔
650
                                }
95✔
651

652
                                channels[e.ChannelID] = directedChannel
190✔
653

190✔
654
                                return nil
190✔
655
                        })
656
                if err != nil {
20✔
657
                        return err
×
658
                }
×
659

660
                return cb(node.PubKeyBytes, channels)
20✔
661
        })
662
}
663

664
// DisabledChannelIDs returns the channel ids of disabled channels.
665
// A channel is disabled when two of the associated ChanelEdgePolicies
666
// have their disabled bit on.
667
func (c *ChannelGraph) DisabledChannelIDs() ([]uint64, error) {
6✔
668
        var disabledChanIDs []uint64
6✔
669
        var chanEdgeFound map[uint64]struct{}
6✔
670

6✔
671
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
672
                edges := tx.ReadBucket(edgeBucket)
6✔
673
                if edges == nil {
6✔
674
                        return ErrGraphNoEdgesFound
×
675
                }
×
676

677
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
678
                        disabledEdgePolicyBucket,
6✔
679
                )
6✔
680
                if disabledEdgePolicyIndex == nil {
7✔
681
                        return nil
1✔
682
                }
1✔
683

684
                // We iterate over all disabled policies and we add each channel
685
                // that has more than one disabled policy to disabledChanIDs
686
                // array.
687
                return disabledEdgePolicyIndex.ForEach(
5✔
688
                        func(k, v []byte) error {
16✔
689
                                chanID := byteOrder.Uint64(k[:8])
11✔
690
                                _, edgeFound := chanEdgeFound[chanID]
11✔
691
                                if edgeFound {
15✔
692
                                        delete(chanEdgeFound, chanID)
4✔
693
                                        disabledChanIDs = append(
4✔
694
                                                disabledChanIDs, chanID,
4✔
695
                                        )
4✔
696

4✔
697
                                        return nil
4✔
698
                                }
4✔
699

700
                                chanEdgeFound[chanID] = struct{}{}
7✔
701

7✔
702
                                return nil
7✔
703
                        },
704
                )
705
        }, func() {
6✔
706
                disabledChanIDs = nil
6✔
707
                chanEdgeFound = make(map[uint64]struct{})
6✔
708
        })
6✔
709
        if err != nil {
6✔
710
                return nil, err
×
711
        }
×
712

713
        return disabledChanIDs, nil
6✔
714
}
715

716
// ForEachNode iterates through all the stored vertices/nodes in the graph,
717
// executing the passed callback with each node encountered. If the callback
718
// returns an error, then the transaction is aborted and the iteration stops
719
// early.
720
//
721
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
722
// traversal when graph gets mega
723
func (c *ChannelGraph) ForEachNode(
724
        cb func(kvdb.RTx, *models.LightningNode) error) error {
133✔
725

133✔
726
        traversal := func(tx kvdb.RTx) error {
266✔
727
                // First grab the nodes bucket which stores the mapping from
133✔
728
                // pubKey to node information.
133✔
729
                nodes := tx.ReadBucket(nodeBucket)
133✔
730
                if nodes == nil {
133✔
731
                        return ErrGraphNotFound
×
732
                }
×
733

734
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,576✔
735
                        // If this is the source key, then we skip this
1,443✔
736
                        // iteration as the value for this key is a pubKey
1,443✔
737
                        // rather than raw node information.
1,443✔
738
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
1,708✔
739
                                return nil
265✔
740
                        }
265✔
741

742
                        nodeReader := bytes.NewReader(nodeBytes)
1,182✔
743
                        node, err := deserializeLightningNode(nodeReader)
1,182✔
744
                        if err != nil {
1,182✔
745
                                return err
×
746
                        }
×
747

748
                        // Execute the callback, the transaction will abort if
749
                        // this returns an error.
750
                        return cb(tx, &node)
1,182✔
751
                })
752
        }
753

754
        return kvdb.View(c.db, traversal, func() {})
266✔
755
}
756

757
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
758
// graph, executing the passed callback with each node encountered. If the
759
// callback returns an error, then the transaction is aborted and the iteration
760
// stops early.
761
func (c *ChannelGraph) ForEachNodeCacheable(cb func(kvdb.RTx,
762
        GraphCacheNode) error) error {
146✔
763

146✔
764
        traversal := func(tx kvdb.RTx) error {
292✔
765
                // First grab the nodes bucket which stores the mapping from
146✔
766
                // pubKey to node information.
146✔
767
                nodes := tx.ReadBucket(nodeBucket)
146✔
768
                if nodes == nil {
146✔
769
                        return ErrGraphNotFound
×
770
                }
×
771

772
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
554✔
773
                        // If this is the source key, then we skip this
408✔
774
                        // iteration as the value for this key is a pubKey
408✔
775
                        // rather than raw node information.
408✔
776
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
696✔
777
                                return nil
288✔
778
                        }
288✔
779

780
                        nodeReader := bytes.NewReader(nodeBytes)
124✔
781
                        cacheableNode, err := deserializeLightningNodeCacheable(
124✔
782
                                nodeReader,
124✔
783
                        )
124✔
784
                        if err != nil {
124✔
785
                                return err
×
786
                        }
×
787

788
                        // Execute the callback, the transaction will abort if
789
                        // this returns an error.
790
                        return cb(tx, cacheableNode)
124✔
791
                })
792
        }
793

794
        return kvdb.View(c.db, traversal, func() {})
292✔
795
}
796

797
// SourceNode returns the source node of the graph. The source node is treated
798
// as the center node within a star-graph. This method may be used to kick off
799
// a path finding algorithm in order to explore the reachability of another
800
// node based off the source node.
801
func (c *ChannelGraph) SourceNode() (*models.LightningNode, error) {
236✔
802
        var source *models.LightningNode
236✔
803
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
472✔
804
                // First grab the nodes bucket which stores the mapping from
236✔
805
                // pubKey to node information.
236✔
806
                nodes := tx.ReadBucket(nodeBucket)
236✔
807
                if nodes == nil {
236✔
808
                        return ErrGraphNotFound
×
809
                }
×
810

811
                node, err := c.sourceNode(nodes)
236✔
812
                if err != nil {
237✔
813
                        return err
1✔
814
                }
1✔
815
                source = node
235✔
816

235✔
817
                return nil
235✔
818
        }, func() {
236✔
819
                source = nil
236✔
820
        })
236✔
821
        if err != nil {
237✔
822
                return nil, err
1✔
823
        }
1✔
824

825
        return source, nil
235✔
826
}
827

828
// sourceNode uses an existing database transaction and returns the source node
829
// of the graph. The source node is treated as the center node within a
830
// star-graph. This method may be used to kick off a path finding algorithm in
831
// order to explore the reachability of another node based off the source node.
832
func (c *ChannelGraph) sourceNode(nodes kvdb.RBucket) (*models.LightningNode,
833
        error) {
503✔
834

503✔
835
        selfPub := nodes.Get(sourceKey)
503✔
836
        if selfPub == nil {
504✔
837
                return nil, ErrSourceNodeNotSet
1✔
838
        }
1✔
839

840
        // With the pubKey of the source node retrieved, we're able to
841
        // fetch the full node information.
842
        node, err := fetchLightningNode(nodes, selfPub)
502✔
843
        if err != nil {
502✔
844
                return nil, err
×
845
        }
×
846

847
        return &node, nil
502✔
848
}
849

850
// SetSourceNode sets the source node within the graph database. The source
851
// node is to be used as the center of a star-graph within path finding
852
// algorithms.
853
func (c *ChannelGraph) SetSourceNode(node *models.LightningNode) error {
122✔
854
        nodePubBytes := node.PubKeyBytes[:]
122✔
855

122✔
856
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
244✔
857
                // First grab the nodes bucket which stores the mapping from
122✔
858
                // pubKey to node information.
122✔
859
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
122✔
860
                if err != nil {
122✔
861
                        return err
×
862
                }
×
863

864
                // Next we create the mapping from source to the targeted
865
                // public key.
866
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
122✔
867
                        return err
×
868
                }
×
869

870
                // Finally, we commit the information of the lightning node
871
                // itself.
872
                return addLightningNode(tx, node)
122✔
873
        }, func() {})
122✔
874
}
875

876
// AddLightningNode adds a vertex/node to the graph database. If the node is not
877
// in the database from before, this will add a new, unconnected one to the
878
// graph. If it is present from before, this will update that node's
879
// information. Note that this method is expected to only be called to update an
880
// already present node from a node announcement, or to insert a node found in a
881
// channel update.
882
//
883
// TODO(roasbeef): also need sig of announcement
884
func (c *ChannelGraph) AddLightningNode(node *models.LightningNode,
885
        op ...batch.SchedulerOption) error {
805✔
886

805✔
887
        r := &batch.Request{
805✔
888
                Update: func(tx kvdb.RwTx) error {
1,610✔
889
                        if c.graphCache != nil {
1,423✔
890
                                cNode := newGraphCacheNode(
618✔
891
                                        node.PubKeyBytes, node.Features,
618✔
892
                                )
618✔
893
                                err := c.graphCache.AddNode(tx, cNode)
618✔
894
                                if err != nil {
618✔
895
                                        return err
×
896
                                }
×
897
                        }
898

899
                        return addLightningNode(tx, node)
805✔
900
                },
901
        }
902

903
        for _, f := range op {
809✔
904
                f(r)
4✔
905
        }
4✔
906

907
        return c.nodeScheduler.Execute(r)
805✔
908
}
909

910
func addLightningNode(tx kvdb.RwTx, node *models.LightningNode) error {
1,002✔
911
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,002✔
912
        if err != nil {
1,002✔
913
                return err
×
914
        }
×
915

916
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
1,002✔
917
        if err != nil {
1,002✔
918
                return err
×
919
        }
×
920

921
        updateIndex, err := nodes.CreateBucketIfNotExists(
1,002✔
922
                nodeUpdateIndexBucket,
1,002✔
923
        )
1,002✔
924
        if err != nil {
1,002✔
925
                return err
×
926
        }
×
927

928
        return putLightningNode(nodes, aliases, updateIndex, node)
1,002✔
929
}
930

931
// LookupAlias attempts to return the alias as advertised by the target node.
932
// TODO(roasbeef): currently assumes that aliases are unique...
933
func (c *ChannelGraph) LookupAlias(pub *btcec.PublicKey) (string, error) {
6✔
934
        var alias string
6✔
935

6✔
936
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
937
                nodes := tx.ReadBucket(nodeBucket)
6✔
938
                if nodes == nil {
6✔
939
                        return ErrGraphNodesNotFound
×
940
                }
×
941

942
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
6✔
943
                if aliases == nil {
6✔
944
                        return ErrGraphNodesNotFound
×
945
                }
×
946

947
                nodePub := pub.SerializeCompressed()
6✔
948
                a := aliases.Get(nodePub)
6✔
949
                if a == nil {
7✔
950
                        return ErrNodeAliasNotFound
1✔
951
                }
1✔
952

953
                // TODO(roasbeef): should actually be using the utf-8
954
                // package...
955
                alias = string(a)
5✔
956
                return nil
5✔
957
        }, func() {
6✔
958
                alias = ""
6✔
959
        })
6✔
960
        if err != nil {
7✔
961
                return "", err
1✔
962
        }
1✔
963

964
        return alias, nil
5✔
965
}
966

967
// DeleteLightningNode starts a new database transaction to remove a vertex/node
968
// from the database according to the node's public key.
969
func (c *ChannelGraph) DeleteLightningNode(nodePub route.Vertex) error {
3✔
970
        // TODO(roasbeef): ensure dangling edges are removed...
3✔
971
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
972
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
973
                if nodes == nil {
3✔
974
                        return ErrGraphNodeNotFound
×
975
                }
×
976

977
                if c.graphCache != nil {
6✔
978
                        c.graphCache.RemoveNode(nodePub)
3✔
979
                }
3✔
980

981
                return c.deleteLightningNode(nodes, nodePub[:])
3✔
982
        }, func() {})
3✔
983
}
984

985
// deleteLightningNode uses an existing database transaction to remove a
986
// vertex/node from the database according to the node's public key.
987
func (c *ChannelGraph) deleteLightningNode(nodes kvdb.RwBucket,
988
        compressedPubKey []byte) error {
76✔
989

76✔
990
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
76✔
991
        if aliases == nil {
76✔
992
                return ErrGraphNodesNotFound
×
993
        }
×
994

995
        if err := aliases.Delete(compressedPubKey); err != nil {
76✔
996
                return err
×
997
        }
×
998

999
        // Before we delete the node, we'll fetch its current state so we can
1000
        // determine when its last update was to clear out the node update
1001
        // index.
1002
        node, err := fetchLightningNode(nodes, compressedPubKey)
76✔
1003
        if err != nil {
76✔
1004
                return err
×
1005
        }
×
1006

1007
        if err := nodes.Delete(compressedPubKey); err != nil {
76✔
1008
                return err
×
1009
        }
×
1010

1011
        // Finally, we'll delete the index entry for the node within the
1012
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
1013
        // need to track its last update.
1014
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
76✔
1015
        if nodeUpdateIndex == nil {
76✔
1016
                return ErrGraphNodesNotFound
×
1017
        }
×
1018

1019
        // In order to delete the entry, we'll need to reconstruct the key for
1020
        // its last update.
1021
        updateUnix := uint64(node.LastUpdate.Unix())
76✔
1022
        var indexKey [8 + 33]byte
76✔
1023
        byteOrder.PutUint64(indexKey[:8], updateUnix)
76✔
1024
        copy(indexKey[8:], compressedPubKey)
76✔
1025

76✔
1026
        return nodeUpdateIndex.Delete(indexKey[:])
76✔
1027
}
1028

1029
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
1030
// undirected edge from the two target nodes are created. The information stored
1031
// denotes the static attributes of the channel, such as the channelID, the keys
1032
// involved in creation of the channel, and the set of features that the channel
1033
// supports. The chanPoint and chanID are used to uniquely identify the edge
1034
// globally within the database.
1035
func (c *ChannelGraph) AddChannelEdge(edge *models.ChannelEdgeInfo,
1036
        op ...batch.SchedulerOption) error {
1,723✔
1037

1,723✔
1038
        var alreadyExists bool
1,723✔
1039
        r := &batch.Request{
1,723✔
1040
                Reset: func() {
3,446✔
1041
                        alreadyExists = false
1,723✔
1042
                },
1,723✔
1043
                Update: func(tx kvdb.RwTx) error {
1,723✔
1044
                        err := c.addChannelEdge(tx, edge)
1,723✔
1045

1,723✔
1046
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,723✔
1047
                        // succeed, but propagate the error via local state.
1,723✔
1048
                        if err == ErrEdgeAlreadyExist {
1,957✔
1049
                                alreadyExists = true
234✔
1050
                                return nil
234✔
1051
                        }
234✔
1052

1053
                        return err
1,489✔
1054
                },
1055
                OnCommit: func(err error) error {
1,723✔
1056
                        switch {
1,723✔
1057
                        case err != nil:
×
1058
                                return err
×
1059
                        case alreadyExists:
234✔
1060
                                return ErrEdgeAlreadyExist
234✔
1061
                        default:
1,489✔
1062
                                c.rejectCache.remove(edge.ChannelID)
1,489✔
1063
                                c.chanCache.remove(edge.ChannelID)
1,489✔
1064
                                return nil
1,489✔
1065
                        }
1066
                },
1067
        }
1068

1069
        for _, f := range op {
1,727✔
1070
                if f == nil {
4✔
1071
                        return fmt.Errorf("nil scheduler option was used")
×
1072
                }
×
1073

1074
                f(r)
4✔
1075
        }
1076

1077
        return c.chanScheduler.Execute(r)
1,723✔
1078
}
1079

1080
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1081
// utilize an existing db transaction.
1082
func (c *ChannelGraph) addChannelEdge(tx kvdb.RwTx,
1083
        edge *models.ChannelEdgeInfo) error {
1,724✔
1084

1,724✔
1085
        // Construct the channel's primary key which is the 8-byte channel ID.
1,724✔
1086
        var chanKey [8]byte
1,724✔
1087
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,724✔
1088

1,724✔
1089
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,724✔
1090
        if err != nil {
1,724✔
1091
                return err
×
1092
        }
×
1093
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,724✔
1094
        if err != nil {
1,724✔
1095
                return err
×
1096
        }
×
1097
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,724✔
1098
        if err != nil {
1,724✔
1099
                return err
×
1100
        }
×
1101
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,724✔
1102
        if err != nil {
1,724✔
1103
                return err
×
1104
        }
×
1105

1106
        // First, attempt to check if this edge has already been created. If
1107
        // so, then we can exit early as this method is meant to be idempotent.
1108
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
1,958✔
1109
                return ErrEdgeAlreadyExist
234✔
1110
        }
234✔
1111

1112
        if c.graphCache != nil {
2,790✔
1113
                c.graphCache.AddChannel(edge, nil, nil)
1,300✔
1114
        }
1,300✔
1115

1116
        // Before we insert the channel into the database, we'll ensure that
1117
        // both nodes already exist in the channel graph. If either node
1118
        // doesn't, then we'll insert a "shell" node that just includes its
1119
        // public key, so subsequent validation and queries can work properly.
1120
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
1,490✔
1121
        switch {
1,490✔
1122
        case node1Err == ErrGraphNodeNotFound:
22✔
1123
                node1Shell := models.LightningNode{
22✔
1124
                        PubKeyBytes:          edge.NodeKey1Bytes,
22✔
1125
                        HaveNodeAnnouncement: false,
22✔
1126
                }
22✔
1127
                err := addLightningNode(tx, &node1Shell)
22✔
1128
                if err != nil {
22✔
1129
                        return fmt.Errorf("unable to create shell node "+
×
1130
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1131
                }
×
1132
        case node1Err != nil:
×
1133
                return node1Err
×
1134
        }
1135

1136
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
1,490✔
1137
        switch {
1,490✔
1138
        case node2Err == ErrGraphNodeNotFound:
65✔
1139
                node2Shell := models.LightningNode{
65✔
1140
                        PubKeyBytes:          edge.NodeKey2Bytes,
65✔
1141
                        HaveNodeAnnouncement: false,
65✔
1142
                }
65✔
1143
                err := addLightningNode(tx, &node2Shell)
65✔
1144
                if err != nil {
65✔
1145
                        return fmt.Errorf("unable to create shell node "+
×
1146
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
1147
                }
×
1148
        case node2Err != nil:
×
1149
                return node2Err
×
1150
        }
1151

1152
        // If the edge hasn't been created yet, then we'll first add it to the
1153
        // edge index in order to associate the edge between two nodes and also
1154
        // store the static components of the channel.
1155
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
1,490✔
1156
                return err
×
1157
        }
×
1158

1159
        // Mark edge policies for both sides as unknown. This is to enable
1160
        // efficient incoming channel lookup for a node.
1161
        keys := []*[33]byte{
1,490✔
1162
                &edge.NodeKey1Bytes,
1,490✔
1163
                &edge.NodeKey2Bytes,
1,490✔
1164
        }
1,490✔
1165
        for _, key := range keys {
4,466✔
1166
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,976✔
1167
                if err != nil {
2,976✔
1168
                        return err
×
1169
                }
×
1170
        }
1171

1172
        // Finally we add it to the channel index which maps channel points
1173
        // (outpoints) to the shorter channel ID's.
1174
        var b bytes.Buffer
1,490✔
1175
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
1,490✔
1176
                return err
×
1177
        }
×
1178
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,490✔
1179
}
1180

1181
// ReAddChannelEdge removes the edge with the given channel ID from the
1182
// database and adds the new edge to guarantee atomicity.
1183
// This is important for option-scid-alias channels which may change its SCID
1184
// over the course of its lifetime (e.g., public zero-conf channels).
1185
func (c *ChannelGraph) ReAddChannelEdge(
1186
        chanID uint64, newEdge *models.ChannelEdgeInfo,
1187
        ourPolicy *models.ChannelEdgePolicy) error {
5✔
1188

5✔
1189
        c.cacheMu.Lock()
5✔
1190
        defer c.cacheMu.Unlock()
5✔
1191

5✔
1192
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
10✔
1193
                edges := tx.ReadWriteBucket(edgeBucket)
5✔
1194
                if edges == nil {
5✔
NEW
1195
                        return ErrEdgeNotFound
×
NEW
1196
                }
×
1197
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
5✔
1198
                if edgeIndex == nil {
5✔
NEW
1199
                        return ErrEdgeNotFound
×
NEW
1200
                }
×
1201
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
5✔
1202
                if chanIndex == nil {
5✔
NEW
1203
                        return ErrEdgeNotFound
×
NEW
1204
                }
×
1205
                nodes := tx.ReadWriteBucket(nodeBucket)
5✔
1206
                if nodes == nil {
5✔
NEW
1207
                        return ErrGraphNodeNotFound
×
NEW
1208
                }
×
1209

1210
                var rawChanID [8]byte
5✔
1211
                byteOrder.PutUint64(rawChanID[:], chanID)
5✔
1212

5✔
1213
                // We don't mark this channel as zombie, because we are readding
5✔
1214
                // it immediately after deleting it below. This method also
5✔
1215
                // deletes the channel from the graph cache, however there is
5✔
1216
                // no entry in the cache because we only add it if we have
5✔
1217
                // received the proof(signatures).
5✔
1218
                err := c.delChannelEdgeUnsafe(
5✔
1219
                        edges, edgeIndex, chanIndex, nil,
5✔
1220
                        rawChanID[:], false, false,
5✔
1221
                )
5✔
1222
                if err != nil {
5✔
NEW
1223
                        return err
×
NEW
1224
                }
×
1225

1226
                // Now we add the channel with the new edge info.
1227
                err = c.addChannelEdge(tx, newEdge)
5✔
1228
                if err != nil {
5✔
NEW
1229
                        return err
×
NEW
1230
                }
×
1231

1232
                // Also add the new channel update from our side.
1233
                _, err = updateEdgePolicy(tx, ourPolicy, c.graphCache)
5✔
1234

5✔
1235
                return err
5✔
1236
        }, func() {})
5✔
1237
        if err != nil {
5✔
NEW
1238
                return err
×
NEW
1239
        }
×
1240

1241
        // Remove the Cache entries.
1242
        c.rejectCache.remove(chanID)
5✔
1243
        c.chanCache.remove(chanID)
5✔
1244

5✔
1245
        // We also make sure we clear the reject cache because we might have
5✔
1246
        // received a channel update msg with the new SCID from our peer which
5✔
1247
        // would have been put in the reject cache because the channel was not
5✔
1248
        // part of the graph.
5✔
1249
        c.rejectCache.remove(newEdge.ChannelID)
5✔
1250
        c.chanCache.remove(newEdge.ChannelID)
5✔
1251

5✔
1252
        return nil
5✔
1253
}
1254

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

220✔
1264
        var (
220✔
1265
                upd1Time time.Time
220✔
1266
                upd2Time time.Time
220✔
1267
                exists   bool
220✔
1268
                isZombie bool
220✔
1269
        )
220✔
1270

220✔
1271
        // We'll query the cache with the shared lock held to allow multiple
220✔
1272
        // readers to access values in the cache concurrently if they exist.
220✔
1273
        c.cacheMu.RLock()
220✔
1274
        if entry, ok := c.rejectCache.get(chanID); ok {
293✔
1275
                c.cacheMu.RUnlock()
73✔
1276
                upd1Time = time.Unix(entry.upd1Time, 0)
73✔
1277
                upd2Time = time.Unix(entry.upd2Time, 0)
73✔
1278
                exists, isZombie = entry.flags.unpack()
73✔
1279
                return upd1Time, upd2Time, exists, isZombie, nil
73✔
1280
        }
73✔
1281
        c.cacheMu.RUnlock()
151✔
1282

151✔
1283
        c.cacheMu.Lock()
151✔
1284
        defer c.cacheMu.Unlock()
151✔
1285

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

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

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

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

1320
                        return nil
99✔
1321
                }
1322

1323
                exists = true
53✔
1324
                isZombie = false
53✔
1325

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

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

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

1350
                return nil
53✔
1351
        }, func() {}); err != nil {
148✔
1352
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1353
        }
×
1354

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

148✔
1361
        return upd1Time, upd2Time, exists, isZombie, nil
148✔
1362
}
1363

1364
// UpdateChannelEdge retrieves and update edge of the graph database. Method
1365
// only reserved for updating an edge info after its already been created.
1366
// In order to maintain this constraints, we return an error in the scenario
1367
// that an edge info hasn't yet been created yet, but someone attempts to update
1368
// it.
1369
func (c *ChannelGraph) UpdateChannelEdge(edge *models.ChannelEdgeInfo) error {
5✔
1370
        // Construct the channel's primary key which is the 8-byte channel ID.
5✔
1371
        var chanKey [8]byte
5✔
1372
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
5✔
1373

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

1380
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
5✔
1381
                if edgeIndex == nil {
5✔
1382
                        return ErrEdgeNotFound
×
1383
                }
×
1384

1385
                if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo == nil {
5✔
1386
                        return ErrEdgeNotFound
×
1387
                }
×
1388

1389
                if c.graphCache != nil {
10✔
1390
                        c.graphCache.UpdateChannel(edge)
5✔
1391
                }
5✔
1392

1393
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
5✔
1394
        }, func() {})
5✔
1395
}
1396

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

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

247✔
1417
        c.cacheMu.Lock()
247✔
1418
        defer c.cacheMu.Unlock()
247✔
1419

247✔
1420
        var chansClosed []*models.ChannelEdgeInfo
247✔
1421

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

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

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

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

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

1471
                        // However, if it does, then we'll read out the full
1472
                        // version so we can add it to the set of deleted
1473
                        // channels.
1474
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
27✔
1475
                        if err != nil {
27✔
1476
                                return err
×
1477
                        }
×
1478

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

1491
                        chansClosed = append(chansClosed, &edgeInfo)
27✔
1492
                }
1493

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

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

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

247✔
1512
                var newTip [pruneTipBytes]byte
247✔
1513
                copy(newTip[:], blockHash[:])
247✔
1514

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

1520
                // Now that the graph has been pruned, we'll also attempt to
1521
                // prune any nodes that have had a channel closed within the
1522
                // latest block.
1523
                return c.pruneGraphNodes(nodes, edgeIndex)
247✔
1524
        }, func() {
247✔
1525
                chansClosed = nil
247✔
1526
        })
247✔
1527
        if err != nil {
247✔
1528
                return nil, err
×
1529
        }
×
1530

1531
        for _, channel := range chansClosed {
274✔
1532
                c.rejectCache.remove(channel.ChannelID)
27✔
1533
                c.chanCache.remove(channel.ChannelID)
27✔
1534
        }
27✔
1535

1536
        if c.graphCache != nil {
494✔
1537
                log.Debugf("Pruned graph, cache now has %s",
247✔
1538
                        c.graphCache.Stats())
247✔
1539
        }
247✔
1540

1541
        return chansClosed, nil
247✔
1542
}
1543

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

1563
                return c.pruneGraphNodes(nodes, edgeIndex)
28✔
1564
        }, func() {})
28✔
1565
}
1566

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

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

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

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

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

513✔
1598
                return nil
513✔
1599
        })
1600
        if err != nil {
271✔
1601
                return err
×
1602
        }
×
1603

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

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

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

195✔
1624
                return nil
195✔
1625
        })
195✔
1626
        if err != nil {
271✔
1627
                return err
×
1628
        }
×
1629

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

1641
                if c.graphCache != nil {
146✔
1642
                        c.graphCache.RemoveNode(nodePubKey)
73✔
1643
                }
73✔
1644

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

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

1657
                        return err
×
1658
                }
1659

1660
                log.Infof("Pruned unconnected node %x from channel graph",
73✔
1661
                        nodePubKey[:])
73✔
1662

73✔
1663
                numNodesPruned++
73✔
1664
        }
1665

1666
        if numNodesPruned > 0 {
328✔
1667
                log.Infof("Pruned %v unconnected nodes from the channel graph",
57✔
1668
                        numNodesPruned)
57✔
1669
        }
57✔
1670

1671
        return nil
271✔
1672
}
1673

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

166✔
1684
        // Every channel having a ShortChannelID starting at 'height'
166✔
1685
        // will no longer be confirmed.
166✔
1686
        startShortChanID := lnwire.ShortChannelID{
166✔
1687
                BlockHeight: height,
166✔
1688
        }
166✔
1689

166✔
1690
        // Delete everything after this height from the db up until the
166✔
1691
        // SCID alias range.
166✔
1692
        endShortChanID := aliasmgr.StartingAlias
166✔
1693

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

166✔
1700
        c.cacheMu.Lock()
166✔
1701
        defer c.cacheMu.Unlock()
166✔
1702

166✔
1703
        // Keep track of the channels that are removed from the graph.
166✔
1704
        var removedChans []*models.ChannelEdgeInfo
166✔
1705

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

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

166✔
1735
                //nolint:ll
166✔
1736
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
166✔
1737
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
264✔
1738
                        edgeInfoReader := bytes.NewReader(v)
98✔
1739
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
98✔
1740
                        if err != nil {
98✔
1741
                                return err
×
1742
                        }
×
1743

1744
                        keys = append(keys, k)
98✔
1745
                        removedChans = append(removedChans, &edgeInfo)
98✔
1746
                }
1747

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

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

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

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

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

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

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

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

1801
        for _, channel := range removedChans {
264✔
1802
                c.rejectCache.remove(channel.ChannelID)
98✔
1803
                c.chanCache.remove(channel.ChannelID)
98✔
1804
        }
98✔
1805

1806
        return removedChans, nil
166✔
1807
}
1808

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

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

1829
                pruneCursor := pruneBucket.ReadCursor()
59✔
1830

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

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

40✔
1843
                return nil
40✔
1844
        }, func() {})
59✔
1845
        if err != nil {
82✔
1846
                return nil, 0, err
23✔
1847
        }
23✔
1848

1849
        return &tipHash, tipHeight, nil
40✔
1850
}
1851

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

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

141✔
1867
        c.cacheMu.Lock()
141✔
1868
        defer c.cacheMu.Unlock()
141✔
1869

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

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

1904
                return nil
82✔
1905
        }, func() {})
141✔
1906
        if err != nil {
200✔
1907
                return err
59✔
1908
        }
59✔
1909

1910
        for _, chanID := range chanIDs {
111✔
1911
                c.rejectCache.remove(chanID)
29✔
1912
                c.chanCache.remove(chanID)
29✔
1913
        }
29✔
1914

1915
        return nil
82✔
1916
}
1917

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

1933
        return chanID, nil
5✔
1934
}
1935

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

1943
        edges := tx.ReadBucket(edgeBucket)
5✔
1944
        if edges == nil {
5✔
1945
                return 0, ErrGraphNoEdgesFound
×
1946
        }
×
1947
        chanIndex := edges.NestedReadBucket(channelPointBucket)
5✔
1948
        if chanIndex == nil {
5✔
1949
                return 0, ErrGraphNoEdgesFound
×
1950
        }
×
1951

1952
        chanIDBytes := chanIndex.Get(b.Bytes())
5✔
1953
        if chanIDBytes == nil {
9✔
1954
                return 0, ErrEdgeNotFound
4✔
1955
        }
4✔
1956

1957
        chanID := byteOrder.Uint64(chanIDBytes)
5✔
1958

5✔
1959
        return chanID, nil
5✔
1960
}
1961

1962
// TODO(roasbeef): allow updates to use Batch?
1963

1964
// HighestChanID returns the "highest" known channel ID in the channel graph.
1965
// This represents the "newest" channel from the PoV of the chain. This method
1966
// can be used by peers to quickly determine if they're graphs are in sync.
1967
func (c *ChannelGraph) HighestChanID() (uint64, error) {
7✔
1968
        var cid uint64
7✔
1969

7✔
1970
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
14✔
1971
                edges := tx.ReadBucket(edgeBucket)
7✔
1972
                if edges == nil {
7✔
1973
                        return ErrGraphNoEdgesFound
×
1974
                }
×
1975
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
7✔
1976
                if edgeIndex == nil {
7✔
1977
                        return ErrGraphNoEdgesFound
×
1978
                }
×
1979

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

7✔
1984
                lastChanID, _ := cidCursor.Last()
7✔
1985

7✔
1986
                // If there's no key, then this means that we don't actually
7✔
1987
                // know of any channels, so we'll return a predicable error.
7✔
1988
                if lastChanID == nil {
12✔
1989
                        return ErrGraphNoEdgesFound
5✔
1990
                }
5✔
1991

1992
                // Otherwise, we'll de serialize the channel ID and return it
1993
                // to the caller.
1994
                cid = byteOrder.Uint64(lastChanID)
6✔
1995
                return nil
6✔
1996
        }, func() {
7✔
1997
                cid = 0
7✔
1998
        })
7✔
1999
        if err != nil && err != ErrGraphNoEdgesFound {
7✔
2000
                return 0, err
×
2001
        }
×
2002

2003
        return cid, nil
7✔
2004
}
2005

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

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

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

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

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

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

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

142✔
2042
        c.cacheMu.Lock()
142✔
2043
        defer c.cacheMu.Unlock()
142✔
2044

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

2060
                nodes := tx.ReadBucket(nodeBucket)
142✔
2061
                if nodes == nil {
142✔
2062
                        return ErrGraphNodesNotFound
×
2063
                }
×
2064

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

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

142✔
2077
                // With our start and end times constructed, we'll step through
142✔
2078
                // the index collecting the info and policy of each update of
142✔
2079
                // each channel that has a last update within the time range.
142✔
2080
                //
142✔
2081
                //nolint:ll
142✔
2082
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
142✔
2083
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
192✔
2084

50✔
2085
                        // We have a new eligible entry, so we'll slice of the
50✔
2086
                        // chan ID so we can query it in the DB.
50✔
2087
                        chanID := indexKey[8:]
50✔
2088

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

2097
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
43✔
2098
                                hits++
12✔
2099
                                edgesSeen[chanIDInt] = struct{}{}
12✔
2100
                                edgesInHorizon = append(edgesInHorizon, channel)
12✔
2101
                                continue
12✔
2102
                        }
2103

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

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

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

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

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

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

2164
        case err != nil:
×
2165
                return nil, err
×
2166
        }
2167

2168
        // Insert any edges loaded from disk into the cache.
2169
        for chanid, channel := range edgesToCache {
164✔
2170
                c.chanCache.insert(chanid, channel)
22✔
2171
        }
22✔
2172

2173
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
142✔
2174
                float64(hits)/float64(len(edgesInHorizon)), hits,
142✔
2175
                len(edgesInHorizon))
142✔
2176

142✔
2177
        return edgesInHorizon, nil
142✔
2178
}
2179

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

12✔
2187
        var nodesInHorizon []models.LightningNode
12✔
2188

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

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

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

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

12✔
2212
                // With our start and end times constructed, we'll step through
12✔
2213
                // the index collecting info for each node within the time
12✔
2214
                // range.
12✔
2215
                //
12✔
2216
                //nolint:ll
12✔
2217
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
12✔
2218
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
45✔
2219

33✔
2220
                        nodePub := indexKey[8:]
33✔
2221
                        node, err := fetchLightningNode(nodes, nodePub)
33✔
2222
                        if err != nil {
33✔
2223
                                return err
×
2224
                        }
×
2225

2226
                        nodesInHorizon = append(nodesInHorizon, node)
33✔
2227
                }
2228

2229
                return nil
12✔
2230
        }, func() {
12✔
2231
                nodesInHorizon = nil
12✔
2232
        })
12✔
2233
        switch {
12✔
2234
        case err == ErrGraphNoEdgesFound:
×
2235
                fallthrough
×
2236
        case err == ErrGraphNodesNotFound:
×
2237
                break
×
2238

2239
        case err != nil:
×
2240
                return nil, err
×
2241
        }
2242

2243
        return nodesInHorizon, nil
12✔
2244
}
2245

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

125✔
2254
        var newChanIDs []uint64
125✔
2255

125✔
2256
        c.cacheMu.Lock()
125✔
2257
        defer c.cacheMu.Unlock()
125✔
2258

125✔
2259
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
250✔
2260
                edges := tx.ReadBucket(edgeBucket)
125✔
2261
                if edges == nil {
125✔
2262
                        return ErrGraphNoEdgesFound
×
2263
                }
×
2264
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
125✔
2265
                if edgeIndex == nil {
125✔
2266
                        return ErrGraphNoEdgesFound
×
2267
                }
×
2268

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

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

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

2286
                        // If the edge is a known zombie, skip it.
2287
                        if zombieIndex != nil {
228✔
2288
                                isZombie, _, _ := isZombieEdge(
114✔
2289
                                        zombieIndex, scid,
114✔
2290
                                )
114✔
2291

114✔
2292
                                // TODO(ziggie): Make sure that for the strict
114✔
2293
                                // pruning case we compare the pubkeys and
114✔
2294
                                // whether the right timestamp is not older than
114✔
2295
                                // the `ChannelPruneExpiry`.
114✔
2296
                                //
114✔
2297
                                // NOTE: The timestamp data has no verification
114✔
2298
                                // attached to it in the `ReplyChannelRange` msg
114✔
2299
                                // so we are trusting this data at this point.
114✔
2300
                                // However it is not critical because we are
114✔
2301
                                // just removing the channel from the db when
114✔
2302
                                // the timestamps are more recent. During the
114✔
2303
                                // querying of the gossip msg verification
114✔
2304
                                // happens as usual.
114✔
2305
                                // However we should start punishing peers when
114✔
2306
                                // they don't provide us honest data ?
114✔
2307
                                isStillZombie := isZombieChan(
114✔
2308
                                        info.Node1UpdateTimestamp,
114✔
2309
                                        info.Node2UpdateTimestamp,
114✔
2310
                                )
114✔
2311

114✔
2312
                                switch {
114✔
2313
                                // If the edge is a known zombie and if we
2314
                                // would still consider it a zombie given the
2315
                                // latest update timestamps, then we skip this
2316
                                // channel.
2317
                                case isZombie && isStillZombie:
27✔
2318
                                        continue
27✔
2319

2320
                                // Otherwise, if we have marked it as a zombie
2321
                                // but the latest update timestamps could bring
2322
                                // it back from the dead, then we mark it alive,
2323
                                // and we let it be added to the set of IDs to
2324
                                // query our peer for.
2325
                                case isZombie && !isStillZombie:
24✔
2326
                                        err := c.markEdgeLiveUnsafe(tx, scid)
24✔
2327
                                        if err != nil {
24✔
2328
                                                return err
×
2329
                                        }
×
2330
                                }
2331
                        }
2332

2333
                        newChanIDs = append(newChanIDs, scid)
87✔
2334
                }
2335

2336
                return nil
125✔
2337
        }, func() {
125✔
2338
                newChanIDs = nil
125✔
2339
        })
125✔
2340
        switch {
125✔
2341
        // If we don't know of any edges yet, then we'll return the entire set
2342
        // of chan IDs specified.
2343
        case err == ErrGraphNoEdgesFound:
×
2344
                ogChanIDs := make([]uint64, len(chansInfo))
×
2345
                for i, info := range chansInfo {
×
2346
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2347
                }
×
2348

2349
                return ogChanIDs, nil
×
2350

2351
        case err != nil:
×
2352
                return nil, err
×
2353
        }
2354

2355
        return newChanIDs, nil
125✔
2356
}
2357

2358
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2359
// latest received channel updates for the channel.
2360
type ChannelUpdateInfo struct {
2361
        // ShortChannelID is the SCID identifier of the channel.
2362
        ShortChannelID lnwire.ShortChannelID
2363

2364
        // Node1UpdateTimestamp is the timestamp of the latest received update
2365
        // from the node 1 channel peer. This will be set to zero time if no
2366
        // update has yet been received from this node.
2367
        Node1UpdateTimestamp time.Time
2368

2369
        // Node2UpdateTimestamp is the timestamp of the latest received update
2370
        // from the node 2 channel peer. This will be set to zero time if no
2371
        // update has yet been received from this node.
2372
        Node2UpdateTimestamp time.Time
2373
}
2374

2375
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2376
// timestamps with zero seconds unix timestamp which equals
2377
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2378
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2379
        node2Timestamp time.Time) ChannelUpdateInfo {
222✔
2380

222✔
2381
        chanInfo := ChannelUpdateInfo{
222✔
2382
                ShortChannelID:       scid,
222✔
2383
                Node1UpdateTimestamp: node1Timestamp,
222✔
2384
                Node2UpdateTimestamp: node2Timestamp,
222✔
2385
        }
222✔
2386

222✔
2387
        if node1Timestamp.IsZero() {
434✔
2388
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
212✔
2389
        }
212✔
2390

2391
        if node2Timestamp.IsZero() {
434✔
2392
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
212✔
2393
        }
212✔
2394

2395
        return chanInfo
222✔
2396
}
2397

2398
// BlockChannelRange represents a range of channels for a given block height.
2399
type BlockChannelRange struct {
2400
        // Height is the height of the block all of the channels below were
2401
        // included in.
2402
        Height uint32
2403

2404
        // Channels is the list of channels identified by their short ID
2405
        // representation known to us that were included in the block height
2406
        // above. The list may include channel update timestamp information if
2407
        // requested.
2408
        Channels []ChannelUpdateInfo
2409
}
2410

2411
// FilterChannelRange returns the channel ID's of all known channels which were
2412
// mined in a block height within the passed range. The channel IDs are grouped
2413
// by their common block height. This method can be used to quickly share with a
2414
// peer the set of channels we know of within a particular range to catch them
2415
// up after a period of time offline. If withTimestamps is true then the
2416
// timestamp info of the latest received channel update messages of the channel
2417
// will be included in the response.
2418
func (c *ChannelGraph) FilterChannelRange(startHeight,
2419
        endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error) {
15✔
2420

15✔
2421
        startChanID := &lnwire.ShortChannelID{
15✔
2422
                BlockHeight: startHeight,
15✔
2423
        }
15✔
2424

15✔
2425
        endChanID := lnwire.ShortChannelID{
15✔
2426
                BlockHeight: endHeight,
15✔
2427
                TxIndex:     math.MaxUint32 & 0x00ffffff,
15✔
2428
                TxPosition:  math.MaxUint16,
15✔
2429
        }
15✔
2430

15✔
2431
        // As we need to perform a range scan, we'll convert the starting and
15✔
2432
        // ending height to their corresponding values when encoded using short
15✔
2433
        // channel ID's.
15✔
2434
        var chanIDStart, chanIDEnd [8]byte
15✔
2435
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
15✔
2436
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
15✔
2437

15✔
2438
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
15✔
2439
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
30✔
2440
                edges := tx.ReadBucket(edgeBucket)
15✔
2441
                if edges == nil {
15✔
2442
                        return ErrGraphNoEdgesFound
×
2443
                }
×
2444
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
15✔
2445
                if edgeIndex == nil {
15✔
2446
                        return ErrGraphNoEdgesFound
×
2447
                }
×
2448

2449
                cursor := edgeIndex.ReadCursor()
15✔
2450

15✔
2451
                // We'll now iterate through the database, and find each
15✔
2452
                // channel ID that resides within the specified range.
15✔
2453
                //
15✔
2454
                //nolint:ll
15✔
2455
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
15✔
2456
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
63✔
2457
                        // Don't send alias SCIDs during gossip sync.
48✔
2458
                        edgeReader := bytes.NewReader(v)
48✔
2459
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
48✔
2460
                        if err != nil {
48✔
2461
                                return err
×
2462
                        }
×
2463

2464
                        if edgeInfo.AuthProof == nil {
52✔
2465
                                continue
4✔
2466
                        }
2467

2468
                        // This channel ID rests within the target range, so
2469
                        // we'll add it to our returned set.
2470
                        rawCid := byteOrder.Uint64(k)
48✔
2471
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
48✔
2472

48✔
2473
                        chanInfo := NewChannelUpdateInfo(
48✔
2474
                                cid, time.Time{}, time.Time{},
48✔
2475
                        )
48✔
2476

48✔
2477
                        if !withTimestamps {
70✔
2478
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2479
                                        channelsPerBlock[cid.BlockHeight],
22✔
2480
                                        chanInfo,
22✔
2481
                                )
22✔
2482

22✔
2483
                                continue
22✔
2484
                        }
2485

2486
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
26✔
2487

26✔
2488
                        rawPolicy := edges.Get(node1Key)
26✔
2489
                        if len(rawPolicy) != 0 {
36✔
2490
                                r := bytes.NewReader(rawPolicy)
10✔
2491

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

×
2497
                                        return err
×
2498
                                }
×
2499

2500
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
10✔
2501
                        }
2502

2503
                        rawPolicy = edges.Get(node2Key)
26✔
2504
                        if len(rawPolicy) != 0 {
41✔
2505
                                r := bytes.NewReader(rawPolicy)
15✔
2506

15✔
2507
                                edge, err := deserializeChanEdgePolicyRaw(r)
15✔
2508
                                if err != nil && !errors.Is(
15✔
2509
                                        err, ErrEdgePolicyOptionalFieldNotFound,
15✔
2510
                                ) {
15✔
2511

×
2512
                                        return err
×
2513
                                }
×
2514

2515
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
15✔
2516
                        }
2517

2518
                        channelsPerBlock[cid.BlockHeight] = append(
26✔
2519
                                channelsPerBlock[cid.BlockHeight], chanInfo,
26✔
2520
                        )
26✔
2521
                }
2522

2523
                return nil
15✔
2524
        }, func() {
15✔
2525
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
15✔
2526
        })
15✔
2527

2528
        switch {
15✔
2529
        // If we don't know of any channels yet, then there's nothing to
2530
        // filter, so we'll return an empty slice.
2531
        case err == ErrGraphNoEdgesFound || len(channelsPerBlock) == 0:
7✔
2532
                return nil, nil
7✔
2533

2534
        case err != nil:
×
2535
                return nil, err
×
2536
        }
2537

2538
        // Return the channel ranges in ascending block height order.
2539
        blocks := make([]uint32, 0, len(channelsPerBlock))
12✔
2540
        for block := range channelsPerBlock {
38✔
2541
                blocks = append(blocks, block)
26✔
2542
        }
26✔
2543
        sort.Slice(blocks, func(i, j int) bool {
36✔
2544
                return blocks[i] < blocks[j]
24✔
2545
        })
24✔
2546

2547
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
12✔
2548
        for _, block := range blocks {
38✔
2549
                channelRanges = append(channelRanges, BlockChannelRange{
26✔
2550
                        Height:   block,
26✔
2551
                        Channels: channelsPerBlock[block],
26✔
2552
                })
26✔
2553
        }
26✔
2554

2555
        return channelRanges, nil
12✔
2556
}
2557

2558
// FetchChanInfos returns the set of channel edges that correspond to the passed
2559
// channel ID's. If an edge is the query is unknown to the database, it will
2560
// skipped and the result will contain only those edges that exist at the time
2561
// of the query. This can be used to respond to peer queries that are seeking to
2562
// fill in gaps in their view of the channel graph.
2563
func (c *ChannelGraph) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
7✔
2564
        return c.fetchChanInfos(nil, chanIDs)
7✔
2565
}
7✔
2566

2567
// fetchChanInfos returns the set of channel edges that correspond to the passed
2568
// channel ID's. If an edge is the query is unknown to the database, it will
2569
// skipped and the result will contain only those edges that exist at the time
2570
// of the query. This can be used to respond to peer queries that are seeking to
2571
// fill in gaps in their view of the channel graph.
2572
//
2573
// NOTE: An optional transaction may be provided. If none is provided, then a
2574
// new one will be created.
2575
func (c *ChannelGraph) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2576
        []ChannelEdge, error) {
32✔
2577
        // TODO(roasbeef): sort cids?
32✔
2578

32✔
2579
        var (
32✔
2580
                chanEdges []ChannelEdge
32✔
2581
                cidBytes  [8]byte
32✔
2582
        )
32✔
2583

32✔
2584
        fetchChanInfos := func(tx kvdb.RTx) error {
64✔
2585
                edges := tx.ReadBucket(edgeBucket)
32✔
2586
                if edges == nil {
32✔
2587
                        return ErrGraphNoEdgesFound
×
2588
                }
×
2589
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
32✔
2590
                if edgeIndex == nil {
32✔
2591
                        return ErrGraphNoEdgesFound
×
2592
                }
×
2593
                nodes := tx.ReadBucket(nodeBucket)
32✔
2594
                if nodes == nil {
32✔
2595
                        return ErrGraphNotFound
×
2596
                }
×
2597

2598
                for _, cid := range chanIDs {
71✔
2599
                        byteOrder.PutUint64(cidBytes[:], cid)
39✔
2600

39✔
2601
                        // First, we'll fetch the static edge information. If
39✔
2602
                        // the edge is unknown, we will skip the edge and
39✔
2603
                        // continue gathering all known edges.
39✔
2604
                        edgeInfo, err := fetchChanEdgeInfo(
39✔
2605
                                edgeIndex, cidBytes[:],
39✔
2606
                        )
39✔
2607
                        switch {
39✔
2608
                        case errors.Is(err, ErrEdgeNotFound):
31✔
2609
                                continue
31✔
2610
                        case err != nil:
×
2611
                                return err
×
2612
                        }
2613

2614
                        // With the static information obtained, we'll now
2615
                        // fetch the dynamic policy info.
2616
                        edge1, edge2, err := fetchChanEdgePolicies(
12✔
2617
                                edgeIndex, edges, cidBytes[:],
12✔
2618
                        )
12✔
2619
                        if err != nil {
12✔
2620
                                return err
×
2621
                        }
×
2622

2623
                        node1, err := fetchLightningNode(
12✔
2624
                                nodes, edgeInfo.NodeKey1Bytes[:],
12✔
2625
                        )
12✔
2626
                        if err != nil {
12✔
2627
                                return err
×
2628
                        }
×
2629

2630
                        node2, err := fetchLightningNode(
12✔
2631
                                nodes, edgeInfo.NodeKey2Bytes[:],
12✔
2632
                        )
12✔
2633
                        if err != nil {
12✔
2634
                                return err
×
2635
                        }
×
2636

2637
                        chanEdges = append(chanEdges, ChannelEdge{
12✔
2638
                                Info:    &edgeInfo,
12✔
2639
                                Policy1: edge1,
12✔
2640
                                Policy2: edge2,
12✔
2641
                                Node1:   &node1,
12✔
2642
                                Node2:   &node2,
12✔
2643
                        })
12✔
2644
                }
2645
                return nil
32✔
2646
        }
2647

2648
        if tx == nil {
40✔
2649
                err := kvdb.View(c.db, fetchChanInfos, func() {
16✔
2650
                        chanEdges = nil
8✔
2651
                })
8✔
2652
                if err != nil {
8✔
2653
                        return nil, err
×
2654
                }
×
2655

2656
                return chanEdges, nil
8✔
2657
        }
2658

2659
        err := fetchChanInfos(tx)
24✔
2660
        if err != nil {
24✔
2661
                return nil, err
×
2662
        }
×
2663

2664
        return chanEdges, nil
24✔
2665
}
2666

2667
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2668
        edge1, edge2 *models.ChannelEdgePolicy) error {
149✔
2669

149✔
2670
        // First, we'll fetch the edge update index bucket which currently
149✔
2671
        // stores an entry for the channel we're about to delete.
149✔
2672
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
149✔
2673
        if updateIndex == nil {
149✔
2674
                // No edges in bucket, return early.
×
2675
                return nil
×
2676
        }
×
2677

2678
        // Now that we have the bucket, we'll attempt to construct a template
2679
        // for the index key: updateTime || chanid.
2680
        var indexKey [8 + 8]byte
149✔
2681
        byteOrder.PutUint64(indexKey[8:], chanID)
149✔
2682

149✔
2683
        // With the template constructed, we'll attempt to delete an entry that
149✔
2684
        // would have been created by both edges: we'll alternate the update
149✔
2685
        // times, as one may had overridden the other.
149✔
2686
        if edge1 != nil {
164✔
2687
                byteOrder.PutUint64(
15✔
2688
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
15✔
2689
                )
15✔
2690
                if err := updateIndex.Delete(indexKey[:]); err != nil {
15✔
2691
                        return err
×
2692
                }
×
2693
        }
2694

2695
        // We'll also attempt to delete the entry that may have been created by
2696
        // the second edge.
2697
        if edge2 != nil {
166✔
2698
                byteOrder.PutUint64(
17✔
2699
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
17✔
2700
                )
17✔
2701
                if err := updateIndex.Delete(indexKey[:]); err != nil {
17✔
2702
                        return err
×
2703
                }
×
2704
        }
2705

2706
        return nil
149✔
2707
}
2708

2709
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2710
// cache. It then goes on to delete any policy info and edge info for this
2711
// channel from the DB and finally, if isZombie is true, it will add an entry
2712
// for this channel in the zombie index.
2713
//
2714
// NOTE: this method MUST only be called if the cacheMu has already been
2715
// acquired.
2716
func (c *ChannelGraph) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2717
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2718
        strictZombie bool) error {
208✔
2719

208✔
2720
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
208✔
2721
        if err != nil {
267✔
2722
                return err
59✔
2723
        }
59✔
2724

2725
        if c.graphCache != nil {
298✔
2726
                c.graphCache.RemoveChannel(
149✔
2727
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
149✔
2728
                        edgeInfo.ChannelID,
149✔
2729
                )
149✔
2730
        }
149✔
2731

2732
        // We'll also remove the entry in the edge update index bucket before
2733
        // we delete the edges themselves so we can access their last update
2734
        // times.
2735
        cid := byteOrder.Uint64(chanID)
149✔
2736
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
149✔
2737
        if err != nil {
149✔
2738
                return err
×
2739
        }
×
2740
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
149✔
2741
        if err != nil {
149✔
2742
                return err
×
2743
        }
×
2744

2745
        // The edge key is of the format pubKey || chanID. First we construct
2746
        // the latter half, populating the channel ID.
2747
        var edgeKey [33 + 8]byte
149✔
2748
        copy(edgeKey[33:], chanID)
149✔
2749

149✔
2750
        // With the latter half constructed, copy over the first public key to
149✔
2751
        // delete the edge in this direction, then the second to delete the
149✔
2752
        // edge in the opposite direction.
149✔
2753
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
149✔
2754
        if edges.Get(edgeKey[:]) != nil {
298✔
2755
                if err := edges.Delete(edgeKey[:]); err != nil {
149✔
2756
                        return err
×
2757
                }
×
2758
        }
2759
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
149✔
2760
        if edges.Get(edgeKey[:]) != nil {
298✔
2761
                if err := edges.Delete(edgeKey[:]); err != nil {
149✔
2762
                        return err
×
2763
                }
×
2764
        }
2765

2766
        // As part of deleting the edge we also remove all disabled entries
2767
        // from the edgePolicyDisabledIndex bucket. We do that for both
2768
        // directions.
2769
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
149✔
2770
        if err != nil {
149✔
2771
                return err
×
2772
        }
×
2773
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
149✔
2774
        if err != nil {
149✔
2775
                return err
×
2776
        }
×
2777

2778
        // With the edge data deleted, we can purge the information from the two
2779
        // edge indexes.
2780
        if err := edgeIndex.Delete(chanID); err != nil {
149✔
2781
                return err
×
2782
        }
×
2783
        var b bytes.Buffer
149✔
2784
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
149✔
2785
                return err
×
2786
        }
×
2787
        if err := chanIndex.Delete(b.Bytes()); err != nil {
149✔
2788
                return err
×
2789
        }
×
2790

2791
        // Finally, we'll mark the edge as a zombie within our index if it's
2792
        // being removed due to the channel becoming a zombie. We do this to
2793
        // ensure we don't store unnecessary data for spent channels.
2794
        if !isZombie {
274✔
2795
                return nil
125✔
2796
        }
125✔
2797

2798
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
28✔
2799
        if strictZombie {
32✔
2800
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
4✔
2801
        }
4✔
2802

2803
        return markEdgeZombie(
28✔
2804
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
28✔
2805
        )
28✔
2806
}
2807

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

4✔
2827
        switch {
4✔
2828
        // If we don't have either edge policy, we'll return both pubkeys so
2829
        // that the channel can be resurrected by either party.
2830
        case e1 == nil && e2 == nil:
1✔
2831
                return info.NodeKey1Bytes, info.NodeKey2Bytes
1✔
2832

2833
        // If we're missing edge1, or if both edges are present but edge1 is
2834
        // older, we'll return edge1's pubkey and a blank pubkey for edge2. This
2835
        // means that only an update from edge1 will be able to resurrect the
2836
        // channel.
2837
        case e1 == nil || (e2 != nil && e1.LastUpdate.Before(e2.LastUpdate)):
1✔
2838
                return info.NodeKey1Bytes, [33]byte{}
1✔
2839

2840
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2841
        // return a blank pubkey for edge1. In this case, only an update from
2842
        // edge2 can resurect the channel.
2843
        default:
2✔
2844
                return [33]byte{}, info.NodeKey2Bytes
2✔
2845
        }
2846
}
2847

2848
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2849
// within the database for the referenced channel. The `flags` attribute within
2850
// the ChannelEdgePolicy determines which of the directed edges are being
2851
// updated. If the flag is 1, then the first node's information is being
2852
// updated, otherwise it's the second node's information. The node ordering is
2853
// determined by the lexicographical ordering of the identity public keys of the
2854
// nodes on either side of the channel.
2855
func (c *ChannelGraph) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2856
        op ...batch.SchedulerOption) error {
2,669✔
2857

2,669✔
2858
        var (
2,669✔
2859
                isUpdate1    bool
2,669✔
2860
                edgeNotFound bool
2,669✔
2861
        )
2,669✔
2862

2,669✔
2863
        r := &batch.Request{
2,669✔
2864
                Reset: func() {
5,338✔
2865
                        isUpdate1 = false
2,669✔
2866
                        edgeNotFound = false
2,669✔
2867
                },
2,669✔
2868
                Update: func(tx kvdb.RwTx) error {
2,669✔
2869
                        var err error
2,669✔
2870
                        isUpdate1, err = updateEdgePolicy(
2,669✔
2871
                                tx, edge, c.graphCache,
2,669✔
2872
                        )
2,669✔
2873

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

2881
                        return err
2,666✔
2882
                },
2883
                OnCommit: func(err error) error {
2,669✔
2884
                        switch {
2,669✔
2885
                        case err != nil:
×
2886
                                return err
×
2887
                        case edgeNotFound:
3✔
2888
                                return ErrEdgeNotFound
3✔
2889
                        default:
2,666✔
2890
                                c.updateEdgeCache(edge, isUpdate1)
2,666✔
2891
                                return nil
2,666✔
2892
                        }
2893
                },
2894
        }
2895

2896
        for _, f := range op {
2,673✔
2897
                f(r)
4✔
2898
        }
4✔
2899

2900
        return c.chanScheduler.Execute(r)
2,669✔
2901
}
2902

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

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

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

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

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

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

2,670✔
2954
        // With the channel ID, we then fetch the value storing the two
2,670✔
2955
        // nodes which connect this channel edge.
2,670✔
2956
        nodeInfo := edgeIndex.Get(chanID[:])
2,670✔
2957
        if nodeInfo == nil {
2,673✔
2958
                return false, ErrEdgeNotFound
3✔
2959
        }
3✔
2960

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

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

2982
        var (
2,667✔
2983
                fromNodePubKey route.Vertex
2,667✔
2984
                toNodePubKey   route.Vertex
2,667✔
2985
        )
2,667✔
2986
        copy(fromNodePubKey[:], fromNode)
2,667✔
2987
        copy(toNodePubKey[:], toNode)
2,667✔
2988

2,667✔
2989
        if graphCache != nil {
4,948✔
2990
                graphCache.UpdatePolicy(
2,281✔
2991
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,281✔
2992
                )
2,281✔
2993
        }
2,281✔
2994

2995
        return isUpdate1, nil
2,667✔
2996
}
2997

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

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

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

7✔
3021
                        nodeIsPublic = true
7✔
3022
                        return errDone
7✔
3023
                }
7✔
3024

3025
                // Since the edge _does_ extend to the source node, we'll also
3026
                // need to ensure that this is a public edge.
3027
                if info.AuthProof != nil {
21✔
3028
                        nodeIsPublic = true
10✔
3029
                        return errDone
10✔
3030
                }
10✔
3031

3032
                // Otherwise, we'll continue our search.
3033
                return nil
5✔
3034
        })
3035
        if err != nil && err != errDone {
17✔
3036
                return false, err
×
3037
        }
×
3038

3039
        return nodeIsPublic, nil
17✔
3040
}
3041

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

2,944✔
3049
        return c.fetchLightningNode(tx, nodePub)
2,944✔
3050
}
2,944✔
3051

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

841✔
3058
        return c.fetchLightningNode(nil, nodePub)
841✔
3059
}
841✔
3060

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

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

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

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

3092
                node = &n
3,771✔
3093

3,771✔
3094
                return nil
3,771✔
3095
        }
3096

3097
        if tx == nil {
4,626✔
3098
                err := kvdb.View(
841✔
3099
                        c.db, fetch, func() {
1,682✔
3100
                                node = nil
841✔
3101
                        },
841✔
3102
                )
3103
                if err != nil {
859✔
3104
                        return nil, err
18✔
3105
                }
18✔
3106

3107
                return node, nil
827✔
3108
        }
3109

3110
        err := fetch(tx)
2,944✔
3111
        if err != nil {
2,944✔
3112
                return nil, err
×
3113
        }
×
3114

3115
        return node, nil
2,944✔
3116
}
3117

3118
// graphCacheNode is a struct that wraps a LightningNode in a way that it can be
3119
// cached in the graph cache.
3120
type graphCacheNode struct {
3121
        pubKeyBytes route.Vertex
3122
        features    *lnwire.FeatureVector
3123
}
3124

3125
// newGraphCacheNode returns a new cache optimized node.
3126
func newGraphCacheNode(pubKey route.Vertex,
3127
        features *lnwire.FeatureVector) *graphCacheNode {
738✔
3128

738✔
3129
        return &graphCacheNode{
738✔
3130
                pubKeyBytes: pubKey,
738✔
3131
                features:    features,
738✔
3132
        }
738✔
3133
}
738✔
3134

3135
// PubKey returns the node's public identity key.
3136
func (n *graphCacheNode) PubKey() route.Vertex {
738✔
3137
        return n.pubKeyBytes
738✔
3138
}
738✔
3139

3140
// Features returns the node's features.
3141
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
718✔
3142
        return n.features
718✔
3143
}
718✔
3144

3145
// ForEachChannel iterates through all channels of this node, executing the
3146
// passed callback with an edge info structure and the policies of each end
3147
// of the channel. The first edge policy is the outgoing edge *to* the
3148
// connecting node, while the second is the incoming edge *from* the
3149
// connecting node. If the callback returns an error, then the iteration is
3150
// halted with the error propagated back up to the caller.
3151
//
3152
// Unknown policies are passed into the callback as nil values.
3153
func (n *graphCacheNode) ForEachChannel(tx kvdb.RTx,
3154
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3155
                *models.ChannelEdgePolicy) error) error {
638✔
3156

638✔
3157
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
638✔
3158
}
638✔
3159

3160
var _ GraphCacheNode = (*graphCacheNode)(nil)
3161

3162
// HasLightningNode determines if the graph has a vertex identified by the
3163
// target node identity public key. If the node exists in the database, a
3164
// timestamp of when the data for the node was lasted updated is returned along
3165
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3166
// boolean.
3167
func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool,
3168
        error) {
20✔
3169

20✔
3170
        var (
20✔
3171
                updateTime time.Time
20✔
3172
                exists     bool
20✔
3173
        )
20✔
3174

20✔
3175
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
40✔
3176
                // First grab the nodes bucket which stores the mapping from
20✔
3177
                // pubKey to node information.
20✔
3178
                nodes := tx.ReadBucket(nodeBucket)
20✔
3179
                if nodes == nil {
20✔
3180
                        return ErrGraphNotFound
×
3181
                }
×
3182

3183
                // If a key for this serialized public key isn't found, we can
3184
                // exit early.
3185
                nodeBytes := nodes.Get(nodePub[:])
20✔
3186
                if nodeBytes == nil {
27✔
3187
                        exists = false
7✔
3188
                        return nil
7✔
3189
                }
7✔
3190

3191
                // Otherwise we continue on to obtain the time stamp
3192
                // representing the last time the data for this node was
3193
                // updated.
3194
                nodeReader := bytes.NewReader(nodeBytes)
17✔
3195
                node, err := deserializeLightningNode(nodeReader)
17✔
3196
                if err != nil {
17✔
3197
                        return err
×
3198
                }
×
3199

3200
                exists = true
17✔
3201
                updateTime = node.LastUpdate
17✔
3202
                return nil
17✔
3203
        }, func() {
20✔
3204
                updateTime = time.Time{}
20✔
3205
                exists = false
20✔
3206
        })
20✔
3207
        if err != nil {
20✔
3208
                return time.Time{}, exists, err
×
3209
        }
×
3210

3211
        return updateTime, exists, nil
20✔
3212
}
3213

3214
// nodeTraversal is used to traverse all channels of a node given by its
3215
// public key and passes channel information into the specified callback.
3216
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3217
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3218
                *models.ChannelEdgePolicy) error) error {
1,884✔
3219

1,884✔
3220
        traversal := func(tx kvdb.RTx) error {
3,768✔
3221
                edges := tx.ReadBucket(edgeBucket)
1,884✔
3222
                if edges == nil {
1,884✔
3223
                        return ErrGraphNotFound
×
3224
                }
×
3225
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,884✔
3226
                if edgeIndex == nil {
1,884✔
3227
                        return ErrGraphNoEdgesFound
×
3228
                }
×
3229

3230
                // In order to reach all the edges for this node, we take
3231
                // advantage of the construction of the key-space within the
3232
                // edge bucket. The keys are stored in the form: pubKey ||
3233
                // chanID. Therefore, starting from a chanID of zero, we can
3234
                // scan forward in the bucket, grabbing all the edges for the
3235
                // node. Once the prefix no longer matches, then we know we're
3236
                // done.
3237
                var nodeStart [33 + 8]byte
1,884✔
3238
                copy(nodeStart[:], nodePub)
1,884✔
3239
                copy(nodeStart[33:], chanStart[:])
1,884✔
3240

1,884✔
3241
                // Starting from the key pubKey || 0, we seek forward in the
1,884✔
3242
                // bucket until the retrieved key no longer has the public key
1,884✔
3243
                // as its prefix. This indicates that we've stepped over into
1,884✔
3244
                // another node's edges, so we can terminate our scan.
1,884✔
3245
                edgeCursor := edges.ReadCursor()
1,884✔
3246
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
5,737✔
3247
                        // If the prefix still matches, the channel id is
3,853✔
3248
                        // returned in nodeEdge. Channel id is used to lookup
3,853✔
3249
                        // the node at the other end of the channel and both
3,853✔
3250
                        // edge policies.
3,853✔
3251
                        chanID := nodeEdge[33:]
3,853✔
3252
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3,853✔
3253
                        if err != nil {
3,853✔
3254
                                return err
×
3255
                        }
×
3256

3257
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,853✔
3258
                                edges, chanID, nodePub,
3,853✔
3259
                        )
3,853✔
3260
                        if err != nil {
3,853✔
3261
                                return err
×
3262
                        }
×
3263

3264
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,853✔
3265
                        if err != nil {
3,853✔
3266
                                return err
×
3267
                        }
×
3268

3269
                        incomingPolicy, err := fetchChanEdgePolicy(
3,853✔
3270
                                edges, chanID, otherNode[:],
3,853✔
3271
                        )
3,853✔
3272
                        if err != nil {
3,853✔
3273
                                return err
×
3274
                        }
×
3275

3276
                        // Finally, we execute the callback.
3277
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,853✔
3278
                        if err != nil {
3,866✔
3279
                                return err
13✔
3280
                        }
13✔
3281
                }
3282

3283
                return nil
1,875✔
3284
        }
3285

3286
        // If no transaction was provided, then we'll create a new transaction
3287
        // to execute the transaction within.
3288
        if tx == nil {
1,897✔
3289
                return kvdb.View(db, traversal, func() {})
26✔
3290
        }
3291

3292
        // Otherwise, we re-use the existing transaction to execute the graph
3293
        // traversal.
3294
        return traversal(tx)
1,875✔
3295
}
3296

3297
// ForEachNodeChannel iterates through all channels of the given node,
3298
// executing the passed callback with an edge info structure and the policies
3299
// of each end of the channel. The first edge policy is the outgoing edge *to*
3300
// the connecting node, while the second is the incoming edge *from* the
3301
// connecting node. If the callback returns an error, then the iteration is
3302
// halted with the error propagated back up to the caller.
3303
//
3304
// Unknown policies are passed into the callback as nil values.
3305
func (c *ChannelGraph) ForEachNodeChannel(nodePub route.Vertex,
3306
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3307
                *models.ChannelEdgePolicy) error) error {
10✔
3308

10✔
3309
        return nodeTraversal(nil, nodePub[:], c.db, cb)
10✔
3310
}
10✔
3311

3312
// ForEachNodeChannelTx iterates through all channels of the given node,
3313
// executing the passed callback with an edge info structure and the policies
3314
// of each end of the channel. The first edge policy is the outgoing edge *to*
3315
// the connecting node, while the second is the incoming edge *from* the
3316
// connecting node. If the callback returns an error, then the iteration is
3317
// halted with the error propagated back up to the caller.
3318
//
3319
// Unknown policies are passed into the callback as nil values.
3320
//
3321
// If the caller wishes to re-use an existing boltdb transaction, then it
3322
// should be passed as the first argument.  Otherwise, the first argument should
3323
// be nil and a fresh transaction will be created to execute the graph
3324
// traversal.
3325
func (c *ChannelGraph) ForEachNodeChannelTx(tx kvdb.RTx,
3326
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3327
                *models.ChannelEdgePolicy,
3328
                *models.ChannelEdgePolicy) error) error {
1,002✔
3329

1,002✔
3330
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,002✔
3331
}
1,002✔
3332

3333
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3334
// the target node in the channel. This is useful when one knows the pubkey of
3335
// one of the nodes, and wishes to obtain the full LightningNode for the other
3336
// end of the channel.
3337
func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx,
3338
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3339
        *models.LightningNode, error) {
4✔
3340

4✔
3341
        // Ensure that the node passed in is actually a member of the channel.
4✔
3342
        var targetNodeBytes [33]byte
4✔
3343
        switch {
4✔
3344
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
4✔
3345
                targetNodeBytes = channel.NodeKey2Bytes
4✔
3346
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
4✔
3347
                targetNodeBytes = channel.NodeKey1Bytes
4✔
3348
        default:
×
3349
                return nil, fmt.Errorf("node not participating in this channel")
×
3350
        }
3351

3352
        var targetNode *models.LightningNode
4✔
3353
        fetchNodeFunc := func(tx kvdb.RTx) error {
8✔
3354
                // First grab the nodes bucket which stores the mapping from
4✔
3355
                // pubKey to node information.
4✔
3356
                nodes := tx.ReadBucket(nodeBucket)
4✔
3357
                if nodes == nil {
4✔
3358
                        return ErrGraphNotFound
×
3359
                }
×
3360

3361
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
4✔
3362
                if err != nil {
4✔
3363
                        return err
×
3364
                }
×
3365

3366
                targetNode = &node
4✔
3367

4✔
3368
                return nil
4✔
3369
        }
3370

3371
        // If the transaction is nil, then we'll need to create a new one,
3372
        // otherwise we can use the existing db transaction.
3373
        var err error
4✔
3374
        if tx == nil {
4✔
3375
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3376
                        targetNode = nil
×
3377
                })
×
3378
        } else {
4✔
3379
                err = fetchNodeFunc(tx)
4✔
3380
        }
4✔
3381

3382
        return targetNode, err
4✔
3383
}
3384

3385
// computeEdgePolicyKeys is a helper function that can be used to compute the
3386
// keys used to index the channel edge policy info for the two nodes of the
3387
// edge. The keys for node 1 and node 2 are returned respectively.
3388
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
26✔
3389
        var (
26✔
3390
                node1Key [33 + 8]byte
26✔
3391
                node2Key [33 + 8]byte
26✔
3392
        )
26✔
3393

26✔
3394
        copy(node1Key[:], info.NodeKey1Bytes[:])
26✔
3395
        copy(node2Key[:], info.NodeKey2Bytes[:])
26✔
3396

26✔
3397
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
26✔
3398
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
26✔
3399

26✔
3400
        return node1Key[:], node2Key[:]
26✔
3401
}
26✔
3402

3403
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3404
// the channel identified by the funding outpoint. If the channel can't be
3405
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3406
// information for the channel itself is returned as well as two structs that
3407
// contain the routing policies for the channel in either direction.
3408
func (c *ChannelGraph) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3409
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3410
        *models.ChannelEdgePolicy, error) {
15✔
3411

15✔
3412
        var (
15✔
3413
                edgeInfo *models.ChannelEdgeInfo
15✔
3414
                policy1  *models.ChannelEdgePolicy
15✔
3415
                policy2  *models.ChannelEdgePolicy
15✔
3416
        )
15✔
3417

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

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

3438
                // If the channel's outpoint doesn't exist within the outpoint
3439
                // index, then the edge does not exist.
3440
                chanIndex := edges.NestedReadBucket(channelPointBucket)
15✔
3441
                if chanIndex == nil {
15✔
3442
                        return ErrGraphNoEdgesFound
×
3443
                }
×
3444
                var b bytes.Buffer
15✔
3445
                if err := WriteOutpoint(&b, op); err != nil {
15✔
3446
                        return err
×
3447
                }
×
3448
                chanID := chanIndex.Get(b.Bytes())
15✔
3449
                if chanID == nil {
29✔
3450
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
14✔
3451
                }
14✔
3452

3453
                // If the channel is found to exists, then we'll first retrieve
3454
                // the general information for the channel.
3455
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
5✔
3456
                if err != nil {
5✔
3457
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3458
                }
×
3459
                edgeInfo = &edge
5✔
3460

5✔
3461
                // Once we have the information about the channels' parameters,
5✔
3462
                // we'll fetch the routing policies for each for the directed
5✔
3463
                // edges.
5✔
3464
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
5✔
3465
                if err != nil {
5✔
3466
                        return fmt.Errorf("failed to find policy: %w", err)
×
3467
                }
×
3468

3469
                policy1 = e1
5✔
3470
                policy2 = e2
5✔
3471
                return nil
5✔
3472
        }, func() {
15✔
3473
                edgeInfo = nil
15✔
3474
                policy1 = nil
15✔
3475
                policy2 = nil
15✔
3476
        })
15✔
3477
        if err != nil {
29✔
3478
                return nil, nil, nil, err
14✔
3479
        }
14✔
3480

3481
        return edgeInfo, policy1, policy2, nil
5✔
3482
}
3483

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

31✔
3497
        var (
31✔
3498
                edgeInfo  *models.ChannelEdgeInfo
31✔
3499
                policy1   *models.ChannelEdgePolicy
31✔
3500
                policy2   *models.ChannelEdgePolicy
31✔
3501
                channelID [8]byte
31✔
3502
        )
31✔
3503

31✔
3504
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
62✔
3505
                // First, grab the node bucket. This will be used to populate
31✔
3506
                // the Node pointers in each edge read from disk.
31✔
3507
                nodes := tx.ReadBucket(nodeBucket)
31✔
3508
                if nodes == nil {
31✔
3509
                        return ErrGraphNotFound
×
3510
                }
×
3511

3512
                // Next, grab the edge bucket which stores the edges, and also
3513
                // the index itself so we can group the directed edges together
3514
                // logically.
3515
                edges := tx.ReadBucket(edgeBucket)
31✔
3516
                if edges == nil {
31✔
3517
                        return ErrGraphNoEdgesFound
×
3518
                }
×
3519
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
31✔
3520
                if edgeIndex == nil {
31✔
3521
                        return ErrGraphNoEdgesFound
×
3522
                }
×
3523

3524
                byteOrder.PutUint64(channelID[:], chanID)
31✔
3525

31✔
3526
                // Now, attempt to fetch edge.
31✔
3527
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
31✔
3528

31✔
3529
                // If it doesn't exist, we'll quickly check our zombie index to
31✔
3530
                // see if we've previously marked it as so.
31✔
3531
                if errors.Is(err, ErrEdgeNotFound) {
37✔
3532
                        // If the zombie index doesn't exist, or the edge is not
6✔
3533
                        // marked as a zombie within it, then we'll return the
6✔
3534
                        // original ErrEdgeNotFound error.
6✔
3535
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
6✔
3536
                        if zombieIndex == nil {
6✔
3537
                                return ErrEdgeNotFound
×
3538
                        }
×
3539

3540
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
6✔
3541
                                zombieIndex, chanID,
6✔
3542
                        )
6✔
3543
                        if !isZombie {
11✔
3544
                                return ErrEdgeNotFound
5✔
3545
                        }
5✔
3546

3547
                        // Otherwise, the edge is marked as a zombie, so we'll
3548
                        // populate the edge info with the public keys of each
3549
                        // party as this is the only information we have about
3550
                        // it and return an error signaling so.
3551
                        edgeInfo = &models.ChannelEdgeInfo{
5✔
3552
                                NodeKey1Bytes: pubKey1,
5✔
3553
                                NodeKey2Bytes: pubKey2,
5✔
3554
                        }
5✔
3555
                        return ErrZombieEdge
5✔
3556
                }
3557

3558
                // Otherwise, we'll just return the error if any.
3559
                if err != nil {
29✔
3560
                        return err
×
3561
                }
×
3562

3563
                edgeInfo = &edge
29✔
3564

29✔
3565
                // Then we'll attempt to fetch the accompanying policies of this
29✔
3566
                // edge.
29✔
3567
                e1, e2, err := fetchChanEdgePolicies(
29✔
3568
                        edgeIndex, edges, channelID[:],
29✔
3569
                )
29✔
3570
                if err != nil {
29✔
3571
                        return err
×
3572
                }
×
3573

3574
                policy1 = e1
29✔
3575
                policy2 = e2
29✔
3576
                return nil
29✔
3577
        }, func() {
31✔
3578
                edgeInfo = nil
31✔
3579
                policy1 = nil
31✔
3580
                policy2 = nil
31✔
3581
        })
31✔
3582
        if err == ErrZombieEdge {
36✔
3583
                return edgeInfo, nil, nil, err
5✔
3584
        }
5✔
3585
        if err != nil {
35✔
3586
                return nil, nil, nil, err
5✔
3587
        }
5✔
3588

3589
        return edgeInfo, policy1, policy2, nil
29✔
3590
}
3591

3592
// IsPublicNode is a helper method that determines whether the node with the
3593
// given public key is seen as a public node in the graph from the graph's
3594
// source node's point of view.
3595
func (c *ChannelGraph) IsPublicNode(pubKey [33]byte) (bool, error) {
17✔
3596
        var nodeIsPublic bool
17✔
3597
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
34✔
3598
                nodes := tx.ReadBucket(nodeBucket)
17✔
3599
                if nodes == nil {
17✔
3600
                        return ErrGraphNodesNotFound
×
3601
                }
×
3602
                ourPubKey := nodes.Get(sourceKey)
17✔
3603
                if ourPubKey == nil {
17✔
3604
                        return ErrSourceNodeNotSet
×
3605
                }
×
3606
                node, err := fetchLightningNode(nodes, pubKey[:])
17✔
3607
                if err != nil {
17✔
3608
                        return err
×
3609
                }
×
3610

3611
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
17✔
3612
                return err
17✔
3613
        }, func() {
17✔
3614
                nodeIsPublic = false
17✔
3615
        })
17✔
3616
        if err != nil {
17✔
3617
                return false, err
×
3618
        }
×
3619

3620
        return nodeIsPublic, nil
17✔
3621
}
3622

3623
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3624
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
50✔
3625
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
50✔
3626
        if err != nil {
50✔
3627
                return nil, err
×
3628
        }
×
3629

3630
        // With the witness script generated, we'll now turn it into a p2wsh
3631
        // script:
3632
        //  * OP_0 <sha256(script)>
3633
        bldr := txscript.NewScriptBuilder(
50✔
3634
                txscript.WithScriptAllocSize(input.P2WSHSize),
50✔
3635
        )
50✔
3636
        bldr.AddOp(txscript.OP_0)
50✔
3637
        scriptHash := sha256.Sum256(witnessScript)
50✔
3638
        bldr.AddData(scriptHash[:])
50✔
3639

50✔
3640
        return bldr.Script()
50✔
3641
}
3642

3643
// EdgePoint couples the outpoint of a channel with the funding script that it
3644
// creates. The FilteredChainView will use this to watch for spends of this
3645
// edge point on chain. We require both of these values as depending on the
3646
// concrete implementation, either the pkScript, or the out point will be used.
3647
type EdgePoint struct {
3648
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3649
        FundingPkScript []byte
3650

3651
        // OutPoint is the outpoint of the target channel.
3652
        OutPoint wire.OutPoint
3653
}
3654

3655
// String returns a human readable version of the target EdgePoint. We return
3656
// the outpoint directly as it is enough to uniquely identify the edge point.
3657
func (e *EdgePoint) String() string {
×
3658
        return e.OutPoint.String()
×
3659
}
×
3660

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

3684
                // Once we have the proper bucket, we'll range over each key
3685
                // (which is the channel point for the channel) and decode it,
3686
                // accumulating each entry.
3687
                return chanIndex.ForEach(
27✔
3688
                        func(chanPointBytes, chanID []byte) error {
73✔
3689
                                chanPointReader := bytes.NewReader(
46✔
3690
                                        chanPointBytes,
46✔
3691
                                )
46✔
3692

46✔
3693
                                var chanPoint wire.OutPoint
46✔
3694
                                err := ReadOutpoint(chanPointReader, &chanPoint)
46✔
3695
                                if err != nil {
46✔
3696
                                        return err
×
3697
                                }
×
3698

3699
                                edgeInfo, err := fetchChanEdgeInfo(
46✔
3700
                                        edgeIndex, chanID,
46✔
3701
                                )
46✔
3702
                                if err != nil {
46✔
3703
                                        return err
×
3704
                                }
×
3705

3706
                                pkScript, err := genMultiSigP2WSH(
46✔
3707
                                        edgeInfo.BitcoinKey1Bytes[:],
46✔
3708
                                        edgeInfo.BitcoinKey2Bytes[:],
46✔
3709
                                )
46✔
3710
                                if err != nil {
46✔
3711
                                        return err
×
3712
                                }
×
3713

3714
                                edgePoints = append(edgePoints, EdgePoint{
46✔
3715
                                        FundingPkScript: pkScript,
46✔
3716
                                        OutPoint:        chanPoint,
46✔
3717
                                })
46✔
3718

46✔
3719
                                return nil
46✔
3720
                        },
3721
                )
3722
        }, func() {
27✔
3723
                edgePoints = nil
27✔
3724
        }); err != nil {
27✔
3725
                return nil, err
×
3726
        }
×
3727

3728
        return edgePoints, nil
27✔
3729
}
3730

3731
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3732
// zombie. This method is used on an ad-hoc basis, when channels need to be
3733
// marked as zombies outside the normal pruning cycle.
3734
func (c *ChannelGraph) MarkEdgeZombie(chanID uint64,
3735
        pubKey1, pubKey2 [33]byte) error {
127✔
3736

127✔
3737
        c.cacheMu.Lock()
127✔
3738
        defer c.cacheMu.Unlock()
127✔
3739

127✔
3740
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
254✔
3741
                edges := tx.ReadWriteBucket(edgeBucket)
127✔
3742
                if edges == nil {
127✔
3743
                        return ErrGraphNoEdgesFound
×
3744
                }
×
3745
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
127✔
3746
                if err != nil {
127✔
3747
                        return fmt.Errorf("unable to create zombie "+
×
3748
                                "bucket: %w", err)
×
3749
                }
×
3750

3751
                if c.graphCache != nil {
254✔
3752
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
127✔
3753
                }
127✔
3754

3755
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
127✔
3756
        })
3757
        if err != nil {
127✔
3758
                return err
×
3759
        }
×
3760

3761
        c.rejectCache.remove(chanID)
127✔
3762
        c.chanCache.remove(chanID)
127✔
3763

127✔
3764
        return nil
127✔
3765
}
3766

3767
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3768
// keys should represent the node public keys of the two parties involved in the
3769
// edge.
3770
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3771
        pubKey2 [33]byte) error {
155✔
3772

155✔
3773
        var k [8]byte
155✔
3774
        byteOrder.PutUint64(k[:], chanID)
155✔
3775

155✔
3776
        var v [66]byte
155✔
3777
        copy(v[:33], pubKey1[:])
155✔
3778
        copy(v[33:], pubKey2[:])
155✔
3779

155✔
3780
        return zombieIndex.Put(k[:], v[:])
155✔
3781
}
155✔
3782

3783
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3784
func (c *ChannelGraph) MarkEdgeLive(chanID uint64) error {
6✔
3785
        c.cacheMu.Lock()
6✔
3786
        defer c.cacheMu.Unlock()
6✔
3787

6✔
3788
        return c.markEdgeLiveUnsafe(nil, chanID)
6✔
3789
}
6✔
3790

3791
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3792
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3793
// case a new transaction will be created.
3794
//
3795
// NOTE: this method MUST only be called if the cacheMu has already been
3796
// acquired.
3797
func (c *ChannelGraph) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
30✔
3798
        dbFn := func(tx kvdb.RwTx) error {
60✔
3799
                edges := tx.ReadWriteBucket(edgeBucket)
30✔
3800
                if edges == nil {
30✔
3801
                        return ErrGraphNoEdgesFound
×
3802
                }
×
3803
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
30✔
3804
                if zombieIndex == nil {
30✔
3805
                        return nil
×
3806
                }
×
3807

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

30✔
3811
                if len(zombieIndex.Get(k[:])) == 0 {
31✔
3812
                        return ErrZombieEdgeNotFound
1✔
3813
                }
1✔
3814

3815
                return zombieIndex.Delete(k[:])
29✔
3816
        }
3817

3818
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3819
        // the existing transaction
3820
        var err error
30✔
3821
        if tx == nil {
36✔
3822
                err = kvdb.Update(c.db, dbFn, func() {})
12✔
3823
        } else {
24✔
3824
                err = dbFn(tx)
24✔
3825
        }
24✔
3826
        if err != nil {
31✔
3827
                return err
1✔
3828
        }
1✔
3829

3830
        c.rejectCache.remove(chanID)
29✔
3831
        c.chanCache.remove(chanID)
29✔
3832

29✔
3833
        // We need to add the channel back into our graph cache, otherwise we
29✔
3834
        // won't use it for path finding.
29✔
3835
        if c.graphCache != nil {
58✔
3836
                edgeInfos, err := c.fetchChanInfos(tx, []uint64{chanID})
29✔
3837
                if err != nil {
29✔
3838
                        return err
×
3839
                }
×
3840

3841
                for _, edgeInfo := range edgeInfos {
29✔
3842
                        c.graphCache.AddChannel(
×
3843
                                edgeInfo.Info, edgeInfo.Policy1,
×
3844
                                edgeInfo.Policy2,
×
3845
                        )
×
3846
                }
×
3847
        }
3848

3849
        return nil
29✔
3850
}
3851

3852
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3853
// zombie, then the two node public keys corresponding to this edge are also
3854
// returned.
3855
func (c *ChannelGraph) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
5✔
3856
        var (
5✔
3857
                isZombie         bool
5✔
3858
                pubKey1, pubKey2 [33]byte
5✔
3859
        )
5✔
3860

5✔
3861
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3862
                edges := tx.ReadBucket(edgeBucket)
5✔
3863
                if edges == nil {
5✔
3864
                        return ErrGraphNoEdgesFound
×
3865
                }
×
3866
                zombieIndex := edges.NestedReadBucket(zombieBucket)
5✔
3867
                if zombieIndex == nil {
5✔
3868
                        return nil
×
3869
                }
×
3870

3871
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
5✔
3872
                return nil
5✔
3873
        }, func() {
5✔
3874
                isZombie = false
5✔
3875
                pubKey1 = [33]byte{}
5✔
3876
                pubKey2 = [33]byte{}
5✔
3877
        })
5✔
3878
        if err != nil {
5✔
3879
                return false, [33]byte{}, [33]byte{}
×
3880
        }
×
3881

3882
        return isZombie, pubKey1, pubKey2
5✔
3883
}
3884

3885
// isZombieEdge returns whether an entry exists for the given channel in the
3886
// zombie index. If an entry exists, then the two node public keys corresponding
3887
// to this edge are also returned.
3888
func isZombieEdge(zombieIndex kvdb.RBucket,
3889
        chanID uint64) (bool, [33]byte, [33]byte) {
216✔
3890

216✔
3891
        var k [8]byte
216✔
3892
        byteOrder.PutUint64(k[:], chanID)
216✔
3893

216✔
3894
        v := zombieIndex.Get(k[:])
216✔
3895
        if v == nil {
343✔
3896
                return false, [33]byte{}, [33]byte{}
127✔
3897
        }
127✔
3898

3899
        var pubKey1, pubKey2 [33]byte
93✔
3900
        copy(pubKey1[:], v[:33])
93✔
3901
        copy(pubKey2[:], v[33:])
93✔
3902

93✔
3903
        return true, pubKey1, pubKey2
93✔
3904
}
3905

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

3919
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3920
                        numZombies++
2✔
3921
                        return nil
2✔
3922
                })
2✔
3923
        }, func() {
4✔
3924
                numZombies = 0
4✔
3925
        })
4✔
3926
        if err != nil {
4✔
3927
                return 0, err
×
3928
        }
×
3929

3930
        return numZombies, nil
4✔
3931
}
3932

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

3943
                var k [8]byte
1✔
3944
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3945

1✔
3946
                return closedScids.Put(k[:], []byte{})
1✔
3947
        }, func() {})
1✔
3948
}
3949

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

3961
                var k [8]byte
6✔
3962
                byteOrder.PutUint64(k[:], scid.ToUint64())
6✔
3963

6✔
3964
                if closedScids.Get(k[:]) != nil {
7✔
3965
                        isClosed = true
1✔
3966
                        return nil
1✔
3967
                }
1✔
3968

3969
                return nil
5✔
3970
        }, func() {
6✔
3971
                isClosed = false
6✔
3972
        })
6✔
3973
        if err != nil {
6✔
3974
                return false, err
×
3975
        }
×
3976

3977
        return isClosed, nil
6✔
3978
}
3979

3980
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3981
        updateIndex kvdb.RwBucket, node *models.LightningNode) error {
1,002✔
3982

1,002✔
3983
        var (
1,002✔
3984
                scratch [16]byte
1,002✔
3985
                b       bytes.Buffer
1,002✔
3986
        )
1,002✔
3987

1,002✔
3988
        pub, err := node.PubKey()
1,002✔
3989
        if err != nil {
1,002✔
3990
                return err
×
3991
        }
×
3992
        nodePub := pub.SerializeCompressed()
1,002✔
3993

1,002✔
3994
        // If the node has the update time set, write it, else write 0.
1,002✔
3995
        updateUnix := uint64(0)
1,002✔
3996
        if node.LastUpdate.Unix() > 0 {
1,871✔
3997
                updateUnix = uint64(node.LastUpdate.Unix())
869✔
3998
        }
869✔
3999

4000
        byteOrder.PutUint64(scratch[:8], updateUnix)
1,002✔
4001
        if _, err := b.Write(scratch[:8]); err != nil {
1,002✔
4002
                return err
×
4003
        }
×
4004

4005
        if _, err := b.Write(nodePub); err != nil {
1,002✔
4006
                return err
×
4007
        }
×
4008

4009
        // If we got a node announcement for this node, we will have the rest
4010
        // of the data available. If not we don't have more data to write.
4011
        if !node.HaveNodeAnnouncement {
1,086✔
4012
                // Write HaveNodeAnnouncement=0.
84✔
4013
                byteOrder.PutUint16(scratch[:2], 0)
84✔
4014
                if _, err := b.Write(scratch[:2]); err != nil {
84✔
4015
                        return err
×
4016
                }
×
4017

4018
                return nodeBucket.Put(nodePub, b.Bytes())
84✔
4019
        }
4020

4021
        // Write HaveNodeAnnouncement=1.
4022
        byteOrder.PutUint16(scratch[:2], 1)
922✔
4023
        if _, err := b.Write(scratch[:2]); err != nil {
922✔
4024
                return err
×
4025
        }
×
4026

4027
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
922✔
4028
                return err
×
4029
        }
×
4030
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
922✔
4031
                return err
×
4032
        }
×
4033
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
922✔
4034
                return err
×
4035
        }
×
4036

4037
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
922✔
4038
                return err
×
4039
        }
×
4040

4041
        if err := node.Features.Encode(&b); err != nil {
922✔
4042
                return err
×
4043
        }
×
4044

4045
        numAddresses := uint16(len(node.Addresses))
922✔
4046
        byteOrder.PutUint16(scratch[:2], numAddresses)
922✔
4047
        if _, err := b.Write(scratch[:2]); err != nil {
922✔
4048
                return err
×
4049
        }
×
4050

4051
        for _, address := range node.Addresses {
2,072✔
4052
                if err := SerializeAddr(&b, address); err != nil {
1,150✔
4053
                        return err
×
4054
                }
×
4055
        }
4056

4057
        sigLen := len(node.AuthSigBytes)
922✔
4058
        if sigLen > 80 {
922✔
4059
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4060
                        sigLen)
×
4061
        }
×
4062

4063
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
922✔
4064
        if err != nil {
922✔
4065
                return err
×
4066
        }
×
4067

4068
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
922✔
4069
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4070
        }
×
4071
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
922✔
4072
        if err != nil {
922✔
4073
                return err
×
4074
        }
×
4075

4076
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
922✔
4077
                return err
×
4078
        }
×
4079

4080
        // With the alias bucket updated, we'll now update the index that
4081
        // tracks the time series of node updates.
4082
        var indexKey [8 + 33]byte
922✔
4083
        byteOrder.PutUint64(indexKey[:8], updateUnix)
922✔
4084
        copy(indexKey[8:], nodePub)
922✔
4085

922✔
4086
        // If there was already an old index entry for this node, then we'll
922✔
4087
        // delete the old one before we write the new entry.
922✔
4088
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
1,030✔
4089
                // Extract out the old update time to we can reconstruct the
108✔
4090
                // prior index key to delete it from the index.
108✔
4091
                oldUpdateTime := nodeBytes[:8]
108✔
4092

108✔
4093
                var oldIndexKey [8 + 33]byte
108✔
4094
                copy(oldIndexKey[:8], oldUpdateTime)
108✔
4095
                copy(oldIndexKey[8:], nodePub)
108✔
4096

108✔
4097
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
108✔
4098
                        return err
×
4099
                }
×
4100
        }
4101

4102
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
922✔
4103
                return err
×
4104
        }
×
4105

4106
        return nodeBucket.Put(nodePub, b.Bytes())
922✔
4107
}
4108

4109
func fetchLightningNode(nodeBucket kvdb.RBucket,
4110
        nodePub []byte) (models.LightningNode, error) {
3,640✔
4111

3,640✔
4112
        nodeBytes := nodeBucket.Get(nodePub)
3,640✔
4113
        if nodeBytes == nil {
3,723✔
4114
                return models.LightningNode{}, ErrGraphNodeNotFound
83✔
4115
        }
83✔
4116

4117
        nodeReader := bytes.NewReader(nodeBytes)
3,561✔
4118
        return deserializeLightningNode(nodeReader)
3,561✔
4119
}
4120

4121
func deserializeLightningNodeCacheable(r io.Reader) (*graphCacheNode, error) {
124✔
4122
        // Always populate a feature vector, even if we don't have a node
124✔
4123
        // announcement and short circuit below.
124✔
4124
        node := newGraphCacheNode(
124✔
4125
                route.Vertex{},
124✔
4126
                lnwire.EmptyFeatureVector(),
124✔
4127
        )
124✔
4128

124✔
4129
        var nodeScratch [8]byte
124✔
4130

124✔
4131
        // Skip ahead:
124✔
4132
        // - LastUpdate (8 bytes)
124✔
4133
        if _, err := r.Read(nodeScratch[:]); err != nil {
124✔
4134
                return nil, err
×
4135
        }
×
4136

4137
        if _, err := io.ReadFull(r, node.pubKeyBytes[:]); err != nil {
124✔
4138
                return nil, err
×
4139
        }
×
4140

4141
        // Read the node announcement flag.
4142
        if _, err := r.Read(nodeScratch[:2]); err != nil {
124✔
4143
                return nil, err
×
4144
        }
×
4145
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
124✔
4146

124✔
4147
        // The rest of the data is optional, and will only be there if we got a
124✔
4148
        // node announcement for this node.
124✔
4149
        if hasNodeAnn == 0 {
128✔
4150
                return node, nil
4✔
4151
        }
4✔
4152

4153
        // We did get a node announcement for this node, so we'll have the rest
4154
        // of the data available.
4155
        var rgb uint8
124✔
4156
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
124✔
4157
                return nil, err
×
4158
        }
×
4159
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
124✔
4160
                return nil, err
×
4161
        }
×
4162
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
124✔
4163
                return nil, err
×
4164
        }
×
4165

4166
        if _, err := wire.ReadVarString(r, 0); err != nil {
124✔
4167
                return nil, err
×
4168
        }
×
4169

4170
        if err := node.features.Decode(r); err != nil {
124✔
4171
                return nil, err
×
4172
        }
×
4173

4174
        return node, nil
124✔
4175
}
4176

4177
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,519✔
4178
        var (
8,519✔
4179
                node    models.LightningNode
8,519✔
4180
                scratch [8]byte
8,519✔
4181
                err     error
8,519✔
4182
        )
8,519✔
4183

8,519✔
4184
        // Always populate a feature vector, even if we don't have a node
8,519✔
4185
        // announcement and short circuit below.
8,519✔
4186
        node.Features = lnwire.EmptyFeatureVector()
8,519✔
4187

8,519✔
4188
        if _, err := r.Read(scratch[:]); err != nil {
8,519✔
4189
                return models.LightningNode{}, err
×
4190
        }
×
4191

4192
        unix := int64(byteOrder.Uint64(scratch[:]))
8,519✔
4193
        node.LastUpdate = time.Unix(unix, 0)
8,519✔
4194

8,519✔
4195
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,519✔
4196
                return models.LightningNode{}, err
×
4197
        }
×
4198

4199
        if _, err := r.Read(scratch[:2]); err != nil {
8,519✔
4200
                return models.LightningNode{}, err
×
4201
        }
×
4202

4203
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,519✔
4204
        if hasNodeAnn == 1 {
16,894✔
4205
                node.HaveNodeAnnouncement = true
8,375✔
4206
        } else {
8,523✔
4207
                node.HaveNodeAnnouncement = false
148✔
4208
        }
148✔
4209

4210
        // The rest of the data is optional, and will only be there if we got a
4211
        // node announcement for this node.
4212
        if !node.HaveNodeAnnouncement {
8,667✔
4213
                return node, nil
148✔
4214
        }
148✔
4215

4216
        // We did get a node announcement for this node, so we'll have the rest
4217
        // of the data available.
4218
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,375✔
4219
                return models.LightningNode{}, err
×
4220
        }
×
4221
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,375✔
4222
                return models.LightningNode{}, err
×
4223
        }
×
4224
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,375✔
4225
                return models.LightningNode{}, err
×
4226
        }
×
4227

4228
        node.Alias, err = wire.ReadVarString(r, 0)
8,375✔
4229
        if err != nil {
8,375✔
4230
                return models.LightningNode{}, err
×
4231
        }
×
4232

4233
        err = node.Features.Decode(r)
8,375✔
4234
        if err != nil {
8,375✔
4235
                return models.LightningNode{}, err
×
4236
        }
×
4237

4238
        if _, err := r.Read(scratch[:2]); err != nil {
8,375✔
4239
                return models.LightningNode{}, err
×
4240
        }
×
4241
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,375✔
4242

8,375✔
4243
        var addresses []net.Addr
8,375✔
4244
        for i := 0; i < numAddresses; i++ {
18,987✔
4245
                address, err := DeserializeAddr(r)
10,612✔
4246
                if err != nil {
10,612✔
4247
                        return models.LightningNode{}, err
×
4248
                }
×
4249
                addresses = append(addresses, address)
10,612✔
4250
        }
4251
        node.Addresses = addresses
8,375✔
4252

8,375✔
4253
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,375✔
4254
        if err != nil {
8,375✔
4255
                return models.LightningNode{}, err
×
4256
        }
×
4257

4258
        // We'll try and see if there are any opaque bytes left, if not, then
4259
        // we'll ignore the EOF error and return the node as is.
4260
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
8,375✔
4261
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,375✔
4262
        )
8,375✔
4263
        switch {
8,375✔
4264
        case err == io.ErrUnexpectedEOF:
×
4265
        case err == io.EOF:
×
4266
        case err != nil:
×
4267
                return models.LightningNode{}, err
×
4268
        }
4269

4270
        return node, nil
8,375✔
4271
}
4272

4273
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4274
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,491✔
4275

1,491✔
4276
        var b bytes.Buffer
1,491✔
4277

1,491✔
4278
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,491✔
4279
                return err
×
4280
        }
×
4281
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,491✔
4282
                return err
×
4283
        }
×
4284
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,491✔
4285
                return err
×
4286
        }
×
4287
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,491✔
4288
                return err
×
4289
        }
×
4290

4291
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,491✔
4292
                return err
×
4293
        }
×
4294

4295
        authProof := edgeInfo.AuthProof
1,491✔
4296
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,491✔
4297
        if authProof != nil {
2,899✔
4298
                nodeSig1 = authProof.NodeSig1Bytes
1,408✔
4299
                nodeSig2 = authProof.NodeSig2Bytes
1,408✔
4300
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,408✔
4301
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,408✔
4302
        }
1,408✔
4303

4304
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,491✔
4305
                return err
×
4306
        }
×
4307
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,491✔
4308
                return err
×
4309
        }
×
4310
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,491✔
4311
                return err
×
4312
        }
×
4313
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,491✔
4314
                return err
×
4315
        }
×
4316

4317
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,491✔
4318
                return err
×
4319
        }
×
4320
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
1,491✔
4321
        if err != nil {
1,491✔
4322
                return err
×
4323
        }
×
4324
        if _, err := b.Write(chanID[:]); err != nil {
1,491✔
4325
                return err
×
4326
        }
×
4327
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,491✔
4328
                return err
×
4329
        }
×
4330

4331
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,491✔
4332
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4333
        }
×
4334
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,491✔
4335
        if err != nil {
1,491✔
4336
                return err
×
4337
        }
×
4338

4339
        return edgeIndex.Put(chanID[:], b.Bytes())
1,491✔
4340
}
4341

4342
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4343
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,203✔
4344

4,203✔
4345
        edgeInfoBytes := edgeIndex.Get(chanID)
4,203✔
4346
        if edgeInfoBytes == nil {
4,295✔
4347
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
92✔
4348
        }
92✔
4349

4350
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,115✔
4351
        return deserializeChanEdgeInfo(edgeInfoReader)
4,115✔
4352
}
4353

4354
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,749✔
4355
        var (
4,749✔
4356
                err      error
4,749✔
4357
                edgeInfo models.ChannelEdgeInfo
4,749✔
4358
        )
4,749✔
4359

4,749✔
4360
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,749✔
4361
                return models.ChannelEdgeInfo{}, err
×
4362
        }
×
4363
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,749✔
4364
                return models.ChannelEdgeInfo{}, err
×
4365
        }
×
4366
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,749✔
4367
                return models.ChannelEdgeInfo{}, err
×
4368
        }
×
4369
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,749✔
4370
                return models.ChannelEdgeInfo{}, err
×
4371
        }
×
4372

4373
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,749✔
4374
        if err != nil {
4,749✔
4375
                return models.ChannelEdgeInfo{}, err
×
4376
        }
×
4377

4378
        proof := &models.ChannelAuthProof{}
4,749✔
4379

4,749✔
4380
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,749✔
4381
        if err != nil {
4,749✔
4382
                return models.ChannelEdgeInfo{}, err
×
4383
        }
×
4384
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,749✔
4385
        if err != nil {
4,749✔
4386
                return models.ChannelEdgeInfo{}, err
×
4387
        }
×
4388
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,749✔
4389
        if err != nil {
4,749✔
4390
                return models.ChannelEdgeInfo{}, err
×
4391
        }
×
4392
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,749✔
4393
        if err != nil {
4,749✔
4394
                return models.ChannelEdgeInfo{}, err
×
4395
        }
×
4396

4397
        if !proof.IsEmpty() {
6,545✔
4398
                edgeInfo.AuthProof = proof
1,796✔
4399
        }
1,796✔
4400

4401
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,749✔
4402
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,749✔
4403
                return models.ChannelEdgeInfo{}, err
×
4404
        }
×
4405
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,749✔
4406
                return models.ChannelEdgeInfo{}, err
×
4407
        }
×
4408
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,749✔
4409
                return models.ChannelEdgeInfo{}, err
×
4410
        }
×
4411

4412
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,749✔
4413
                return models.ChannelEdgeInfo{}, err
×
4414
        }
×
4415

4416
        // We'll try and see if there are any opaque bytes left, if not, then
4417
        // we'll ignore the EOF error and return the edge as is.
4418
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
4,749✔
4419
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
4,749✔
4420
        )
4,749✔
4421
        switch {
4,749✔
4422
        case err == io.ErrUnexpectedEOF:
×
4423
        case err == io.EOF:
×
4424
        case err != nil:
×
4425
                return models.ChannelEdgeInfo{}, err
×
4426
        }
4427

4428
        return edgeInfo, nil
4,749✔
4429
}
4430

4431
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4432
        from, to []byte) error {
2,667✔
4433

2,667✔
4434
        var edgeKey [33 + 8]byte
2,667✔
4435
        copy(edgeKey[:], from)
2,667✔
4436
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,667✔
4437

2,667✔
4438
        var b bytes.Buffer
2,667✔
4439
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,667✔
4440
                return err
×
4441
        }
×
4442

4443
        // Before we write out the new edge, we'll create a new entry in the
4444
        // update index in order to keep it fresh.
4445
        updateUnix := uint64(edge.LastUpdate.Unix())
2,667✔
4446
        var indexKey [8 + 8]byte
2,667✔
4447
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,667✔
4448
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,667✔
4449

2,667✔
4450
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,667✔
4451
        if err != nil {
2,667✔
4452
                return err
×
4453
        }
×
4454

4455
        // If there was already an entry for this edge, then we'll need to
4456
        // delete the old one to ensure we don't leave around any after-images.
4457
        // An unknown policy value does not have a update time recorded, so
4458
        // it also does not need to be removed.
4459
        if edgeBytes := edges.Get(edgeKey[:]); edgeBytes != nil &&
2,667✔
4460
                !bytes.Equal(edgeBytes[:], unknownPolicy) {
2,695✔
4461

28✔
4462
                // In order to delete the old entry, we'll need to obtain the
28✔
4463
                // *prior* update time in order to delete it. To do this, we'll
28✔
4464
                // need to deserialize the existing policy within the database
28✔
4465
                // (now outdated by the new one), and delete its corresponding
28✔
4466
                // entry within the update index. We'll ignore any
28✔
4467
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
28✔
4468
                // the channel ID and update time to delete the entry.
28✔
4469
                // TODO(halseth): get rid of these invalid policies in a
28✔
4470
                // migration.
28✔
4471
                oldEdgePolicy, err := deserializeChanEdgePolicy(
28✔
4472
                        bytes.NewReader(edgeBytes),
28✔
4473
                )
28✔
4474
                if err != nil && err != ErrEdgePolicyOptionalFieldNotFound {
28✔
4475
                        return err
×
4476
                }
×
4477

4478
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
28✔
4479

28✔
4480
                var oldIndexKey [8 + 8]byte
28✔
4481
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
28✔
4482
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
28✔
4483

28✔
4484
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
28✔
4485
                        return err
×
4486
                }
×
4487
        }
4488

4489
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,667✔
4490
                return err
×
4491
        }
×
4492

4493
        err = updateEdgePolicyDisabledIndex(
2,667✔
4494
                edges, edge.ChannelID,
2,667✔
4495
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,667✔
4496
                edge.IsDisabled(),
2,667✔
4497
        )
2,667✔
4498
        if err != nil {
2,667✔
4499
                return err
×
4500
        }
×
4501

4502
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,667✔
4503
}
4504

4505
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4506
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4507
// one.
4508
// The direction represents the direction of the edge and disabled is used for
4509
// deciding whether to remove or add an entry to the bucket.
4510
// In general a channel is disabled if two entries for the same chanID exist
4511
// in this bucket.
4512
// Maintaining the bucket this way allows a fast retrieval of disabled
4513
// channels, for example when prune is needed.
4514
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4515
        direction bool, disabled bool) error {
2,957✔
4516

2,957✔
4517
        var disabledEdgeKey [8 + 1]byte
2,957✔
4518
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,957✔
4519
        if direction {
4,433✔
4520
                disabledEdgeKey[8] = 1
1,476✔
4521
        }
1,476✔
4522

4523
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,957✔
4524
                disabledEdgePolicyBucket,
2,957✔
4525
        )
2,957✔
4526
        if err != nil {
2,957✔
4527
                return err
×
4528
        }
×
4529

4530
        if disabled {
2,987✔
4531
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
30✔
4532
        }
30✔
4533

4534
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,931✔
4535
}
4536

4537
// putChanEdgePolicyUnknown marks the edge policy as unknown
4538
// in the edges bucket.
4539
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4540
        from []byte) error {
2,976✔
4541

2,976✔
4542
        var edgeKey [33 + 8]byte
2,976✔
4543
        copy(edgeKey[:], from)
2,976✔
4544
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,976✔
4545

2,976✔
4546
        if edges.Get(edgeKey[:]) != nil {
2,976✔
4547
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4548
                        " when there is already a policy present", channelID)
×
4549
        }
×
4550

4551
        return edges.Put(edgeKey[:], unknownPolicy)
2,976✔
4552
}
4553

4554
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4555
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,194✔
4556

8,194✔
4557
        var edgeKey [33 + 8]byte
8,194✔
4558
        copy(edgeKey[:], nodePub)
8,194✔
4559
        copy(edgeKey[33:], chanID[:])
8,194✔
4560

8,194✔
4561
        edgeBytes := edges.Get(edgeKey[:])
8,194✔
4562
        if edgeBytes == nil {
8,194✔
4563
                return nil, ErrEdgeNotFound
×
4564
        }
×
4565

4566
        // No need to deserialize unknown policy.
4567
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,582✔
4568
                return nil, nil
388✔
4569
        }
388✔
4570

4571
        edgeReader := bytes.NewReader(edgeBytes)
7,810✔
4572

7,810✔
4573
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,810✔
4574
        switch {
7,810✔
4575
        // If the db policy was missing an expected optional field, we return
4576
        // nil as if the policy was unknown.
4577
        case err == ErrEdgePolicyOptionalFieldNotFound:
1✔
4578
                return nil, nil
1✔
4579

4580
        case err != nil:
×
4581
                return nil, err
×
4582
        }
4583

4584
        return ep, nil
7,809✔
4585
}
4586

4587
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4588
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4589
        error) {
250✔
4590

250✔
4591
        edgeInfo := edgeIndex.Get(chanID)
250✔
4592
        if edgeInfo == nil {
250✔
4593
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4594
                        chanID)
×
4595
        }
×
4596

4597
        // The first node is contained within the first half of the edge
4598
        // information. We only propagate the error here and below if it's
4599
        // something other than edge non-existence.
4600
        node1Pub := edgeInfo[:33]
250✔
4601
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
250✔
4602
        if err != nil {
250✔
4603
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4604
                        node1Pub)
×
4605
        }
×
4606

4607
        // Similarly, the second node is contained within the latter
4608
        // half of the edge information.
4609
        node2Pub := edgeInfo[33:66]
250✔
4610
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
250✔
4611
        if err != nil {
250✔
4612
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4613
                        node2Pub)
×
4614
        }
×
4615

4616
        return edge1, edge2, nil
250✔
4617
}
4618

4619
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4620
        to []byte) error {
2,669✔
4621

2,669✔
4622
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,669✔
4623
        if err != nil {
2,669✔
4624
                return err
×
4625
        }
×
4626

4627
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,669✔
4628
                return err
×
4629
        }
×
4630

4631
        var scratch [8]byte
2,669✔
4632
        updateUnix := uint64(edge.LastUpdate.Unix())
2,669✔
4633
        byteOrder.PutUint64(scratch[:], updateUnix)
2,669✔
4634
        if _, err := w.Write(scratch[:]); err != nil {
2,669✔
4635
                return err
×
4636
        }
×
4637

4638
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,669✔
4639
                return err
×
4640
        }
×
4641
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,669✔
4642
                return err
×
4643
        }
×
4644
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,669✔
4645
                return err
×
4646
        }
×
4647
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,669✔
4648
                return err
×
4649
        }
×
4650
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
2,669✔
4651
        if err != nil {
2,669✔
4652
                return err
×
4653
        }
×
4654
        err = binary.Write(
2,669✔
4655
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
2,669✔
4656
        )
2,669✔
4657
        if err != nil {
2,669✔
4658
                return err
×
4659
        }
×
4660

4661
        if _, err := w.Write(to); err != nil {
2,669✔
4662
                return err
×
4663
        }
×
4664

4665
        // If the max_htlc field is present, we write it. To be compatible with
4666
        // older versions that wasn't aware of this field, we write it as part
4667
        // of the opaque data.
4668
        // TODO(halseth): clean up when moving to TLV.
4669
        var opaqueBuf bytes.Buffer
2,669✔
4670
        if edge.MessageFlags.HasMaxHtlc() {
4,954✔
4671
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,285✔
4672
                if err != nil {
2,285✔
4673
                        return err
×
4674
                }
×
4675
        }
4676

4677
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,669✔
4678
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4679
        }
×
4680
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,669✔
4681
                return err
×
4682
        }
×
4683

4684
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,669✔
4685
                return err
×
4686
        }
×
4687
        return nil
2,669✔
4688
}
4689

4690
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,835✔
4691
        // Deserialize the policy. Note that in case an optional field is not
7,835✔
4692
        // found, both an error and a populated policy object are returned.
7,835✔
4693
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,835✔
4694
        if deserializeErr != nil &&
7,835✔
4695
                deserializeErr != ErrEdgePolicyOptionalFieldNotFound {
7,835✔
4696

×
4697
                return nil, deserializeErr
×
4698
        }
×
4699

4700
        return edge, deserializeErr
7,835✔
4701
}
4702

4703
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4704
        error) {
8,842✔
4705

8,842✔
4706
        edge := &models.ChannelEdgePolicy{}
8,842✔
4707

8,842✔
4708
        var err error
8,842✔
4709
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,842✔
4710
        if err != nil {
8,842✔
4711
                return nil, err
×
4712
        }
×
4713

4714
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,842✔
4715
                return nil, err
×
4716
        }
×
4717

4718
        var scratch [8]byte
8,842✔
4719
        if _, err := r.Read(scratch[:]); err != nil {
8,842✔
4720
                return nil, err
×
4721
        }
×
4722
        unix := int64(byteOrder.Uint64(scratch[:]))
8,842✔
4723
        edge.LastUpdate = time.Unix(unix, 0)
8,842✔
4724

8,842✔
4725
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,842✔
4726
                return nil, err
×
4727
        }
×
4728
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,842✔
4729
                return nil, err
×
4730
        }
×
4731
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,842✔
4732
                return nil, err
×
4733
        }
×
4734

4735
        var n uint64
8,842✔
4736
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,842✔
4737
                return nil, err
×
4738
        }
×
4739
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,842✔
4740

8,842✔
4741
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,842✔
4742
                return nil, err
×
4743
        }
×
4744
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,842✔
4745

8,842✔
4746
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,842✔
4747
                return nil, err
×
4748
        }
×
4749
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,842✔
4750

8,842✔
4751
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,842✔
4752
                return nil, err
×
4753
        }
×
4754

4755
        // We'll try and see if there are any opaque bytes left, if not, then
4756
        // we'll ignore the EOF error and return the edge as is.
4757
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,842✔
4758
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,842✔
4759
        )
8,842✔
4760
        switch {
8,842✔
4761
        case err == io.ErrUnexpectedEOF:
×
4762
        case err == io.EOF:
3✔
4763
        case err != nil:
×
4764
                return nil, err
×
4765
        }
4766

4767
        // See if optional fields are present.
4768
        if edge.MessageFlags.HasMaxHtlc() {
17,304✔
4769
                // The max_htlc field should be at the beginning of the opaque
8,462✔
4770
                // bytes.
8,462✔
4771
                opq := edge.ExtraOpaqueData
8,462✔
4772

8,462✔
4773
                // If the max_htlc field is not present, it might be old data
8,462✔
4774
                // stored before this field was validated. We'll return the
8,462✔
4775
                // edge along with an error.
8,462✔
4776
                if len(opq) < 8 {
8,465✔
4777
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4778
                }
3✔
4779

4780
                maxHtlc := byteOrder.Uint64(opq[:8])
8,459✔
4781
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,459✔
4782

8,459✔
4783
                // Exclude the parsed field from the rest of the opaque data.
8,459✔
4784
                edge.ExtraOpaqueData = opq[8:]
8,459✔
4785
        }
4786

4787
        return edge, nil
8,839✔
4788
}
4789

4790
// MakeTestGraph creates a new instance of the ChannelGraph for testing
4791
// purposes.
4792
func MakeTestGraph(t testing.TB, modifiers ...OptionModifier) (*ChannelGraph,
4793
        error) {
40✔
4794

40✔
4795
        opts := DefaultOptions()
40✔
4796
        for _, modifier := range modifiers {
40✔
4797
                modifier(opts)
×
4798
        }
×
4799

4800
        // Next, create channelgraph for the first time.
4801
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
40✔
4802
        if err != nil {
40✔
4803
                backendCleanup()
×
4804
                return nil, err
×
4805
        }
×
4806

4807
        graph, err := NewChannelGraph(backend)
40✔
4808
        if err != nil {
40✔
4809
                backendCleanup()
×
4810
                return nil, err
×
4811
        }
×
4812

4813
        t.Cleanup(func() {
80✔
4814
                _ = backend.Close()
40✔
4815
                backendCleanup()
40✔
4816
        })
40✔
4817

4818
        return graph, nil
40✔
4819
}
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