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

lightningnetwork / lnd / 12947350568

24 Jan 2025 09:58AM UTC coverage: 58.706% (-0.09%) from 58.795%
12947350568

Pull #9232

github

Abdulkbk
docs: add release note
Pull Request #9232: chanbackup: archive old channel backup files

52 of 69 new or added lines in 2 files covered. (75.36%)

244 existing lines in 26 files now uncovered.

135827 of 231369 relevant lines covered (58.71%)

19284.67 hits per line

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

77.12
/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) {
175✔
202

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

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

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

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

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

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

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

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

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

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

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

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

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

583✔
285
                        return nil
583✔
286
                }
583✔
287

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

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

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

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

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

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

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

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

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

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

403
        return nil
175✔
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) {
135✔
409
        if c.graphCache != nil {
216✔
410
                return nil, nil
81✔
411
        }
81✔
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) {
3✔
423

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

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

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

439
        return true, node.Addresses, nil
3✔
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 {
146✔
453

146✔
454
        return c.db.View(func(tx kvdb.RTx) error {
292✔
455
                edges := tx.ReadBucket(edgeBucket)
146✔
456
                if edges == nil {
146✔
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)
146✔
463
                if err != nil {
146✔
464
                        return err
×
465
                }
×
466

467
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
146✔
468
                if edgeIndex == nil {
146✔
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(
146✔
475
                        edgeIndex, func(k, edgeInfoBytes []byte) error {
643✔
476
                                var chanID [8]byte
497✔
477
                                copy(chanID[:], k)
497✔
478

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

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

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

497✔
497
                                return cb(&info, policy1, policy2)
497✔
498
                        },
499
                )
500
        }, func() {})
146✔
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 {
705✔
511

705✔
512
        if c.graphCache != nil {
1,168✔
513
                return c.graphCache.ForEachChannel(node, cb)
463✔
514
        }
463✔
515

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

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

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

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

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

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

559
                return cb(directedChannel)
497✔
560
        }
561
        return nodeTraversal(tx, node[:], c.db, dbCallback)
244✔
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,141✔
568

1,141✔
569
        if c.graphCache != nil {
1,596✔
570
                return c.graphCache.GetFeatures(node), nil
455✔
571
        }
455✔
572

573
        // Fallback that uses the database.
574
        targetNode, err := c.FetchLightningNode(node)
688✔
575
        switch err {
688✔
576
        // If the node exists and has features, return them directly.
577
        case nil:
677✔
578
                return targetNode.Features, nil
677✔
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 {
131✔
725

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

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

742
                        nodeReader := bytes.NewReader(nodeBytes)
1,180✔
743
                        node, err := deserializeLightningNode(nodeReader)
1,180✔
744
                        if err != nil {
1,180✔
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,180✔
751
                })
752
        }
753

754
        return kvdb.View(c.db, traversal, func() {})
262✔
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 {
143✔
763

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

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

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

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

794
        return kvdb.View(c.db, traversal, func() {})
286✔
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) {
234✔
802
        var source *models.LightningNode
234✔
803
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
468✔
804
                // First grab the nodes bucket which stores the mapping from
234✔
805
                // pubKey to node information.
234✔
806
                nodes := tx.ReadBucket(nodeBucket)
234✔
807
                if nodes == nil {
234✔
808
                        return ErrGraphNotFound
×
809
                }
×
810

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

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

825
        return source, nil
233✔
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 {
120✔
854
        nodePubBytes := node.PubKeyBytes[:]
120✔
855

120✔
856
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
240✔
857
                // First grab the nodes bucket which stores the mapping from
120✔
858
                // pubKey to node information.
120✔
859
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
120✔
860
                if err != nil {
120✔
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 {
120✔
867
                        return err
×
868
                }
×
869

870
                // Finally, we commit the information of the lightning node
871
                // itself.
872
                return addLightningNode(tx, node)
120✔
873
        }, func() {})
120✔
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 {
801✔
886

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

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

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

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

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

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

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

928
        return putLightningNode(nodes, aliases, updateIndex, node)
989✔
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) {
4✔
934
        var alias string
4✔
935

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

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

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

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

964
        return alias, nil
3✔
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 {
65✔
989

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

995
        if err := aliases.Delete(compressedPubKey); err != nil {
65✔
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)
65✔
1003
        if err != nil {
65✔
1004
                return err
×
1005
        }
×
1006

1007
        if err := nodes.Delete(compressedPubKey); err != nil {
65✔
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)
65✔
1015
        if nodeUpdateIndex == nil {
65✔
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())
65✔
1022
        var indexKey [8 + 33]byte
65✔
1023
        byteOrder.PutUint64(indexKey[:8], updateUnix)
65✔
1024
        copy(indexKey[8:], compressedPubKey)
65✔
1025

65✔
1026
        return nodeUpdateIndex.Delete(indexKey[:])
65✔
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,707✔
1037

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

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

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

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

1074
                f(r)
2✔
1075
        }
1076

1077
        return c.chanScheduler.Execute(r)
1,707✔
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,707✔
1084

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

1,707✔
1089
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,707✔
1090
        if err != nil {
1,707✔
1091
                return err
×
1092
        }
×
1093
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,707✔
1094
        if err != nil {
1,707✔
1095
                return err
×
1096
        }
×
1097
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,707✔
1098
        if err != nil {
1,707✔
1099
                return err
×
1100
        }
×
1101
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,707✔
1102
        if err != nil {
1,707✔
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,941✔
1109
                return ErrEdgeAlreadyExist
234✔
1110
        }
234✔
1111

1112
        if c.graphCache != nil {
2,756✔
1113
                c.graphCache.AddChannel(edge, nil, nil)
1,283✔
1114
        }
1,283✔
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,473✔
1121
        switch {
1,473✔
1122
        case node1Err == ErrGraphNodeNotFound:
20✔
1123
                node1Shell := models.LightningNode{
20✔
1124
                        PubKeyBytes:          edge.NodeKey1Bytes,
20✔
1125
                        HaveNodeAnnouncement: false,
20✔
1126
                }
20✔
1127
                err := addLightningNode(tx, &node1Shell)
20✔
1128
                if err != nil {
20✔
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,473✔
1137
        switch {
1,473✔
1138
        case node2Err == ErrGraphNodeNotFound:
54✔
1139
                node2Shell := models.LightningNode{
54✔
1140
                        PubKeyBytes:          edge.NodeKey2Bytes,
54✔
1141
                        HaveNodeAnnouncement: false,
54✔
1142
                }
54✔
1143
                err := addLightningNode(tx, &node2Shell)
54✔
1144
                if err != nil {
54✔
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,473✔
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,473✔
1162
                &edge.NodeKey1Bytes,
1,473✔
1163
                &edge.NodeKey2Bytes,
1,473✔
1164
        }
1,473✔
1165
        for _, key := range keys {
4,417✔
1166
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,944✔
1167
                if err != nil {
2,944✔
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,473✔
1175
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
1,473✔
1176
                return err
×
1177
        }
×
1178
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,473✔
1179
}
1180

1181
// HasChannelEdge returns true if the database knows of a channel edge with the
1182
// passed channel ID, and false otherwise. If an edge with that ID is found
1183
// within the graph, then two time stamps representing the last time the edge
1184
// was updated for both directed edges are returned along with the boolean. If
1185
// it is not found, then the zombie index is checked and its result is returned
1186
// as the second boolean.
1187
func (c *ChannelGraph) HasChannelEdge(
1188
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
212✔
1189

212✔
1190
        var (
212✔
1191
                upd1Time time.Time
212✔
1192
                upd2Time time.Time
212✔
1193
                exists   bool
212✔
1194
                isZombie bool
212✔
1195
        )
212✔
1196

212✔
1197
        // We'll query the cache with the shared lock held to allow multiple
212✔
1198
        // readers to access values in the cache concurrently if they exist.
212✔
1199
        c.cacheMu.RLock()
212✔
1200
        if entry, ok := c.rejectCache.get(chanID); ok {
286✔
1201
                c.cacheMu.RUnlock()
74✔
1202
                upd1Time = time.Unix(entry.upd1Time, 0)
74✔
1203
                upd2Time = time.Unix(entry.upd2Time, 0)
74✔
1204
                exists, isZombie = entry.flags.unpack()
74✔
1205
                return upd1Time, upd2Time, exists, isZombie, nil
74✔
1206
        }
74✔
1207
        c.cacheMu.RUnlock()
140✔
1208

140✔
1209
        c.cacheMu.Lock()
140✔
1210
        defer c.cacheMu.Unlock()
140✔
1211

140✔
1212
        // The item was not found with the shared lock, so we'll acquire the
140✔
1213
        // exclusive lock and check the cache again in case another method added
140✔
1214
        // the entry to the cache while no lock was held.
140✔
1215
        if entry, ok := c.rejectCache.get(chanID); ok {
148✔
1216
                upd1Time = time.Unix(entry.upd1Time, 0)
8✔
1217
                upd2Time = time.Unix(entry.upd2Time, 0)
8✔
1218
                exists, isZombie = entry.flags.unpack()
8✔
1219
                return upd1Time, upd2Time, exists, isZombie, nil
8✔
1220
        }
8✔
1221

1222
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
268✔
1223
                edges := tx.ReadBucket(edgeBucket)
134✔
1224
                if edges == nil {
134✔
1225
                        return ErrGraphNoEdgesFound
×
1226
                }
×
1227
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
134✔
1228
                if edgeIndex == nil {
134✔
1229
                        return ErrGraphNoEdgesFound
×
1230
                }
×
1231

1232
                var channelID [8]byte
134✔
1233
                byteOrder.PutUint64(channelID[:], chanID)
134✔
1234

134✔
1235
                // If the edge doesn't exist, then we'll also check our zombie
134✔
1236
                // index.
134✔
1237
                if edgeIndex.Get(channelID[:]) == nil {
218✔
1238
                        exists = false
84✔
1239
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
84✔
1240
                        if zombieIndex != nil {
168✔
1241
                                isZombie, _, _ = isZombieEdge(
84✔
1242
                                        zombieIndex, chanID,
84✔
1243
                                )
84✔
1244
                        }
84✔
1245

1246
                        return nil
84✔
1247
                }
1248

1249
                exists = true
52✔
1250
                isZombie = false
52✔
1251

52✔
1252
                // If the channel has been found in the graph, then retrieve
52✔
1253
                // the edges itself so we can return the last updated
52✔
1254
                // timestamps.
52✔
1255
                nodes := tx.ReadBucket(nodeBucket)
52✔
1256
                if nodes == nil {
52✔
1257
                        return ErrGraphNodeNotFound
×
1258
                }
×
1259

1260
                e1, e2, err := fetchChanEdgePolicies(
52✔
1261
                        edgeIndex, edges, channelID[:],
52✔
1262
                )
52✔
1263
                if err != nil {
52✔
1264
                        return err
×
1265
                }
×
1266

1267
                // As we may have only one of the edges populated, only set the
1268
                // update time if the edge was found in the database.
1269
                if e1 != nil {
72✔
1270
                        upd1Time = e1.LastUpdate
20✔
1271
                }
20✔
1272
                if e2 != nil {
70✔
1273
                        upd2Time = e2.LastUpdate
18✔
1274
                }
18✔
1275

1276
                return nil
52✔
1277
        }, func() {}); err != nil {
134✔
1278
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1279
        }
×
1280

1281
        c.rejectCache.insert(chanID, rejectCacheEntry{
134✔
1282
                upd1Time: upd1Time.Unix(),
134✔
1283
                upd2Time: upd2Time.Unix(),
134✔
1284
                flags:    packRejectFlags(exists, isZombie),
134✔
1285
        })
134✔
1286

134✔
1287
        return upd1Time, upd2Time, exists, isZombie, nil
134✔
1288
}
1289

1290
// UpdateChannelEdge retrieves and update edge of the graph database. Method
1291
// only reserved for updating an edge info after its already been created.
1292
// In order to maintain this constraints, we return an error in the scenario
1293
// that an edge info hasn't yet been created yet, but someone attempts to update
1294
// it.
1295
func (c *ChannelGraph) UpdateChannelEdge(edge *models.ChannelEdgeInfo) error {
3✔
1296
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1297
        var chanKey [8]byte
3✔
1298
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1299

3✔
1300
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1301
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1302
                if edge == nil {
3✔
1303
                        return ErrEdgeNotFound
×
1304
                }
×
1305

1306
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1307
                if edgeIndex == nil {
3✔
1308
                        return ErrEdgeNotFound
×
1309
                }
×
1310

1311
                if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo == nil {
3✔
1312
                        return ErrEdgeNotFound
×
1313
                }
×
1314

1315
                if c.graphCache != nil {
6✔
1316
                        c.graphCache.UpdateChannel(edge)
3✔
1317
                }
3✔
1318

1319
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
3✔
1320
        }, func() {})
3✔
1321
}
1322

1323
const (
1324
        // pruneTipBytes is the total size of the value which stores a prune
1325
        // entry of the graph in the prune log. The "prune tip" is the last
1326
        // entry in the prune log, and indicates if the channel graph is in
1327
        // sync with the current UTXO state. The structure of the value
1328
        // is: blockHash, taking 32 bytes total.
1329
        pruneTipBytes = 32
1330
)
1331

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

247✔
1343
        c.cacheMu.Lock()
247✔
1344
        defer c.cacheMu.Unlock()
247✔
1345

247✔
1346
        var chansClosed []*models.ChannelEdgeInfo
247✔
1347

247✔
1348
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
494✔
1349
                // First grab the edges bucket which houses the information
247✔
1350
                // we'd like to delete
247✔
1351
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
247✔
1352
                if err != nil {
247✔
1353
                        return err
×
1354
                }
×
1355

1356
                // Next grab the two edge indexes which will also need to be
1357
                // updated.
1358
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
247✔
1359
                if err != nil {
247✔
1360
                        return err
×
1361
                }
×
1362
                chanIndex, err := edges.CreateBucketIfNotExists(
247✔
1363
                        channelPointBucket,
247✔
1364
                )
247✔
1365
                if err != nil {
247✔
1366
                        return err
×
1367
                }
×
1368
                nodes := tx.ReadWriteBucket(nodeBucket)
247✔
1369
                if nodes == nil {
247✔
1370
                        return ErrSourceNodeNotSet
×
1371
                }
×
1372
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
247✔
1373
                if err != nil {
247✔
1374
                        return err
×
1375
                }
×
1376

1377
                // For each of the outpoints that have been spent within the
1378
                // block, we attempt to delete them from the graph as if that
1379
                // outpoint was a channel, then it has now been closed.
1380
                for _, chanPoint := range spentOutputs {
379✔
1381
                        // TODO(roasbeef): load channel bloom filter, continue
132✔
1382
                        // if NOT if filter
132✔
1383

132✔
1384
                        var opBytes bytes.Buffer
132✔
1385
                        err := WriteOutpoint(&opBytes, chanPoint)
132✔
1386
                        if err != nil {
132✔
1387
                                return err
×
1388
                        }
×
1389

1390
                        // First attempt to see if the channel exists within
1391
                        // the database, if not, then we can exit early.
1392
                        chanID := chanIndex.Get(opBytes.Bytes())
132✔
1393
                        if chanID == nil {
241✔
1394
                                continue
109✔
1395
                        }
1396

1397
                        // However, if it does, then we'll read out the full
1398
                        // version so we can add it to the set of deleted
1399
                        // channels.
1400
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
23✔
1401
                        if err != nil {
23✔
1402
                                return err
×
1403
                        }
×
1404

1405
                        // Attempt to delete the channel, an ErrEdgeNotFound
1406
                        // will be returned if that outpoint isn't known to be
1407
                        // a channel. If no error is returned, then a channel
1408
                        // was successfully pruned.
1409
                        err = c.delChannelEdgeUnsafe(
23✔
1410
                                edges, edgeIndex, chanIndex, zombieIndex,
23✔
1411
                                chanID, false, false,
23✔
1412
                        )
23✔
1413
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
23✔
1414
                                return err
×
1415
                        }
×
1416

1417
                        chansClosed = append(chansClosed, &edgeInfo)
23✔
1418
                }
1419

1420
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
247✔
1421
                if err != nil {
247✔
1422
                        return err
×
1423
                }
×
1424

1425
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
247✔
1426
                        pruneLogBucket,
247✔
1427
                )
247✔
1428
                if err != nil {
247✔
1429
                        return err
×
1430
                }
×
1431

1432
                // With the graph pruned, add a new entry to the prune log,
1433
                // which can be used to check if the graph is fully synced with
1434
                // the current UTXO state.
1435
                var blockHeightBytes [4]byte
247✔
1436
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
247✔
1437

247✔
1438
                var newTip [pruneTipBytes]byte
247✔
1439
                copy(newTip[:], blockHash[:])
247✔
1440

247✔
1441
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
247✔
1442
                if err != nil {
247✔
1443
                        return err
×
1444
                }
×
1445

1446
                // Now that the graph has been pruned, we'll also attempt to
1447
                // prune any nodes that have had a channel closed within the
1448
                // latest block.
1449
                return c.pruneGraphNodes(nodes, edgeIndex)
247✔
1450
        }, func() {
247✔
1451
                chansClosed = nil
247✔
1452
        })
247✔
1453
        if err != nil {
247✔
1454
                return nil, err
×
1455
        }
×
1456

1457
        for _, channel := range chansClosed {
270✔
1458
                c.rejectCache.remove(channel.ChannelID)
23✔
1459
                c.chanCache.remove(channel.ChannelID)
23✔
1460
        }
23✔
1461

1462
        if c.graphCache != nil {
494✔
1463
                log.Debugf("Pruned graph, cache now has %s",
247✔
1464
                        c.graphCache.Stats())
247✔
1465
        }
247✔
1466

1467
        return chansClosed, nil
247✔
1468
}
1469

1470
// PruneGraphNodes is a garbage collection method which attempts to prune out
1471
// any nodes from the channel graph that are currently unconnected. This ensure
1472
// that we only maintain a graph of reachable nodes. In the event that a pruned
1473
// node gains more channels, it will be re-added back to the graph.
1474
func (c *ChannelGraph) PruneGraphNodes() error {
26✔
1475
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
52✔
1476
                nodes := tx.ReadWriteBucket(nodeBucket)
26✔
1477
                if nodes == nil {
26✔
1478
                        return ErrGraphNodesNotFound
×
1479
                }
×
1480
                edges := tx.ReadWriteBucket(edgeBucket)
26✔
1481
                if edges == nil {
26✔
1482
                        return ErrGraphNotFound
×
1483
                }
×
1484
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
26✔
1485
                if edgeIndex == nil {
26✔
1486
                        return ErrGraphNoEdgesFound
×
1487
                }
×
1488

1489
                return c.pruneGraphNodes(nodes, edgeIndex)
26✔
1490
        }, func() {})
26✔
1491
}
1492

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

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

271✔
1501
        // We'll retrieve the graph's source node to ensure we don't remove it
271✔
1502
        // even if it no longer has any open channels.
271✔
1503
        sourceNode, err := c.sourceNode(nodes)
271✔
1504
        if err != nil {
271✔
1505
                return err
×
1506
        }
×
1507

1508
        // We'll use this map to keep count the number of references to a node
1509
        // in the graph. A node should only be removed once it has no more
1510
        // references in the graph.
1511
        nodeRefCounts := make(map[[33]byte]int)
271✔
1512
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,592✔
1513
                // If this is the source key, then we skip this
1,321✔
1514
                // iteration as the value for this key is a pubKey
1,321✔
1515
                // rather than raw node information.
1,321✔
1516
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
2,130✔
1517
                        return nil
809✔
1518
                }
809✔
1519

1520
                var nodePub [33]byte
514✔
1521
                copy(nodePub[:], pubKey)
514✔
1522
                nodeRefCounts[nodePub] = 0
514✔
1523

514✔
1524
                return nil
514✔
1525
        })
1526
        if err != nil {
271✔
1527
                return err
×
1528
        }
×
1529

1530
        // To ensure we never delete the source node, we'll start off by
1531
        // bumping its ref count to 1.
1532
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
271✔
1533

271✔
1534
        // Next, we'll run through the edgeIndex which maps a channel ID to the
271✔
1535
        // edge info. We'll use this scan to populate our reference count map
271✔
1536
        // above.
271✔
1537
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
467✔
1538
                // The first 66 bytes of the edge info contain the pubkeys of
196✔
1539
                // the nodes that this edge attaches. We'll extract them, and
196✔
1540
                // add them to the ref count map.
196✔
1541
                var node1, node2 [33]byte
196✔
1542
                copy(node1[:], edgeInfoBytes[:33])
196✔
1543
                copy(node2[:], edgeInfoBytes[33:])
196✔
1544

196✔
1545
                // With the nodes extracted, we'll increase the ref count of
196✔
1546
                // each of the nodes.
196✔
1547
                nodeRefCounts[node1]++
196✔
1548
                nodeRefCounts[node2]++
196✔
1549

196✔
1550
                return nil
196✔
1551
        })
196✔
1552
        if err != nil {
271✔
1553
                return err
×
1554
        }
×
1555

1556
        // Finally, we'll make a second pass over the set of nodes, and delete
1557
        // any nodes that have a ref count of zero.
1558
        var numNodesPruned int
271✔
1559
        for nodePubKey, refCount := range nodeRefCounts {
785✔
1560
                // If the ref count of the node isn't zero, then we can safely
514✔
1561
                // skip it as it still has edges to or from it within the
514✔
1562
                // graph.
514✔
1563
                if refCount != 0 {
968✔
1564
                        continue
454✔
1565
                }
1566

1567
                if c.graphCache != nil {
124✔
1568
                        c.graphCache.RemoveNode(nodePubKey)
62✔
1569
                }
62✔
1570

1571
                // If we reach this point, then there are no longer any edges
1572
                // that connect this node, so we can delete it.
1573
                err := c.deleteLightningNode(nodes, nodePubKey[:])
62✔
1574
                if err != nil {
62✔
1575
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1576
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1577

×
1578
                                log.Warnf("Unable to prune node %x from the "+
×
1579
                                        "graph: %v", nodePubKey, err)
×
1580
                                continue
×
1581
                        }
1582

1583
                        return err
×
1584
                }
1585

1586
                log.Infof("Pruned unconnected node %x from channel graph",
62✔
1587
                        nodePubKey[:])
62✔
1588

62✔
1589
                numNodesPruned++
62✔
1590
        }
1591

1592
        if numNodesPruned > 0 {
317✔
1593
                log.Infof("Pruned %v unconnected nodes from the channel graph",
46✔
1594
                        numNodesPruned)
46✔
1595
        }
46✔
1596

1597
        return nil
271✔
1598
}
1599

1600
// DisconnectBlockAtHeight is used to indicate that the block specified
1601
// by the passed height has been disconnected from the main chain. This
1602
// will "rewind" the graph back to the height below, deleting channels
1603
// that are no longer confirmed from the graph. The prune log will be
1604
// set to the last prune height valid for the remaining chain.
1605
// Channels that were removed from the graph resulting from the
1606
// disconnected block are returned.
1607
func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) (
1608
        []*models.ChannelEdgeInfo, error) {
168✔
1609

168✔
1610
        // Every channel having a ShortChannelID starting at 'height'
168✔
1611
        // will no longer be confirmed.
168✔
1612
        startShortChanID := lnwire.ShortChannelID{
168✔
1613
                BlockHeight: height,
168✔
1614
        }
168✔
1615

168✔
1616
        // Delete everything after this height from the db up until the
168✔
1617
        // SCID alias range.
168✔
1618
        endShortChanID := aliasmgr.StartingAlias
168✔
1619

168✔
1620
        // The block height will be the 3 first bytes of the channel IDs.
168✔
1621
        var chanIDStart [8]byte
168✔
1622
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
168✔
1623
        var chanIDEnd [8]byte
168✔
1624
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
168✔
1625

168✔
1626
        c.cacheMu.Lock()
168✔
1627
        defer c.cacheMu.Unlock()
168✔
1628

168✔
1629
        // Keep track of the channels that are removed from the graph.
168✔
1630
        var removedChans []*models.ChannelEdgeInfo
168✔
1631

168✔
1632
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
336✔
1633
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
168✔
1634
                if err != nil {
168✔
1635
                        return err
×
1636
                }
×
1637
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
168✔
1638
                if err != nil {
168✔
1639
                        return err
×
1640
                }
×
1641
                chanIndex, err := edges.CreateBucketIfNotExists(
168✔
1642
                        channelPointBucket,
168✔
1643
                )
168✔
1644
                if err != nil {
168✔
1645
                        return err
×
1646
                }
×
1647
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
168✔
1648
                if err != nil {
168✔
1649
                        return err
×
1650
                }
×
1651

1652
                // Scan from chanIDStart to chanIDEnd, deleting every
1653
                // found edge.
1654
                // NOTE: we must delete the edges after the cursor loop, since
1655
                // modifying the bucket while traversing is not safe.
1656
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1657
                // so that the StartingAlias itself isn't deleted.
1658
                var keys [][]byte
168✔
1659
                cursor := edgeIndex.ReadWriteCursor()
168✔
1660

168✔
1661
                //nolint:ll
168✔
1662
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
168✔
1663
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
255✔
1664
                        edgeInfoReader := bytes.NewReader(v)
87✔
1665
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
87✔
1666
                        if err != nil {
87✔
1667
                                return err
×
1668
                        }
×
1669

1670
                        keys = append(keys, k)
87✔
1671
                        removedChans = append(removedChans, &edgeInfo)
87✔
1672
                }
1673

1674
                for _, k := range keys {
255✔
1675
                        err = c.delChannelEdgeUnsafe(
87✔
1676
                                edges, edgeIndex, chanIndex, zombieIndex,
87✔
1677
                                k, false, false,
87✔
1678
                        )
87✔
1679
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
87✔
1680
                                return err
×
1681
                        }
×
1682
                }
1683

1684
                // Delete all the entries in the prune log having a height
1685
                // greater or equal to the block disconnected.
1686
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
168✔
1687
                if err != nil {
168✔
1688
                        return err
×
1689
                }
×
1690

1691
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(
168✔
1692
                        pruneLogBucket,
168✔
1693
                )
168✔
1694
                if err != nil {
168✔
1695
                        return err
×
1696
                }
×
1697

1698
                var pruneKeyStart [4]byte
168✔
1699
                byteOrder.PutUint32(pruneKeyStart[:], height)
168✔
1700

168✔
1701
                var pruneKeyEnd [4]byte
168✔
1702
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
168✔
1703

168✔
1704
                // To avoid modifying the bucket while traversing, we delete
168✔
1705
                // the keys in a second loop.
168✔
1706
                var pruneKeys [][]byte
168✔
1707
                pruneCursor := pruneBucket.ReadWriteCursor()
168✔
1708
                //nolint:ll
168✔
1709
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
168✔
1710
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
265✔
1711
                        pruneKeys = append(pruneKeys, k)
97✔
1712
                }
97✔
1713

1714
                for _, k := range pruneKeys {
265✔
1715
                        if err := pruneBucket.Delete(k); err != nil {
97✔
1716
                                return err
×
1717
                        }
×
1718
                }
1719

1720
                return nil
168✔
1721
        }, func() {
168✔
1722
                removedChans = nil
168✔
1723
        }); err != nil {
168✔
1724
                return nil, err
×
1725
        }
×
1726

1727
        for _, channel := range removedChans {
255✔
1728
                c.rejectCache.remove(channel.ChannelID)
87✔
1729
                c.chanCache.remove(channel.ChannelID)
87✔
1730
        }
87✔
1731

1732
        return removedChans, nil
168✔
1733
}
1734

1735
// PruneTip returns the block height and hash of the latest block that has been
1736
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1737
// to tell if the graph is currently in sync with the current best known UTXO
1738
// state.
1739
func (c *ChannelGraph) PruneTip() (*chainhash.Hash, uint32, error) {
57✔
1740
        var (
57✔
1741
                tipHash   chainhash.Hash
57✔
1742
                tipHeight uint32
57✔
1743
        )
57✔
1744

57✔
1745
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
114✔
1746
                graphMeta := tx.ReadBucket(graphMetaBucket)
57✔
1747
                if graphMeta == nil {
57✔
1748
                        return ErrGraphNotFound
×
1749
                }
×
1750
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
57✔
1751
                if pruneBucket == nil {
57✔
1752
                        return ErrGraphNeverPruned
×
1753
                }
×
1754

1755
                pruneCursor := pruneBucket.ReadCursor()
57✔
1756

57✔
1757
                // The prune key with the largest block height will be our
57✔
1758
                // prune tip.
57✔
1759
                k, v := pruneCursor.Last()
57✔
1760
                if k == nil {
78✔
1761
                        return ErrGraphNeverPruned
21✔
1762
                }
21✔
1763

1764
                // Once we have the prune tip, the value will be the block hash,
1765
                // and the key the block height.
1766
                copy(tipHash[:], v[:])
38✔
1767
                tipHeight = byteOrder.Uint32(k[:])
38✔
1768

38✔
1769
                return nil
38✔
1770
        }, func() {})
57✔
1771
        if err != nil {
78✔
1772
                return nil, 0, err
21✔
1773
        }
21✔
1774

1775
        return &tipHash, tipHeight, nil
38✔
1776
}
1777

1778
// DeleteChannelEdges removes edges with the given channel IDs from the
1779
// database and marks them as zombies. This ensures that we're unable to re-add
1780
// it to our database once again. If an edge does not exist within the
1781
// database, then ErrEdgeNotFound will be returned. If strictZombiePruning is
1782
// true, then when we mark these edges as zombies, we'll set up the keys such
1783
// that we require the node that failed to send the fresh update to be the one
1784
// that resurrects the channel from its zombie state. The markZombie bool
1785
// denotes whether or not to mark the channel as a zombie.
1786
func (c *ChannelGraph) DeleteChannelEdges(strictZombiePruning, markZombie bool,
1787
        chanIDs ...uint64) error {
152✔
1788

152✔
1789
        // TODO(roasbeef): possibly delete from node bucket if node has no more
152✔
1790
        // channels
152✔
1791
        // TODO(roasbeef): don't delete both edges?
152✔
1792

152✔
1793
        c.cacheMu.Lock()
152✔
1794
        defer c.cacheMu.Unlock()
152✔
1795

152✔
1796
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
304✔
1797
                edges := tx.ReadWriteBucket(edgeBucket)
152✔
1798
                if edges == nil {
152✔
1799
                        return ErrEdgeNotFound
×
1800
                }
×
1801
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
152✔
1802
                if edgeIndex == nil {
152✔
1803
                        return ErrEdgeNotFound
×
1804
                }
×
1805
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
152✔
1806
                if chanIndex == nil {
152✔
1807
                        return ErrEdgeNotFound
×
1808
                }
×
1809
                nodes := tx.ReadWriteBucket(nodeBucket)
152✔
1810
                if nodes == nil {
152✔
1811
                        return ErrGraphNodeNotFound
×
1812
                }
×
1813
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
152✔
1814
                if err != nil {
152✔
1815
                        return err
×
1816
                }
×
1817

1818
                var rawChanID [8]byte
152✔
1819
                for _, chanID := range chanIDs {
238✔
1820
                        byteOrder.PutUint64(rawChanID[:], chanID)
86✔
1821
                        err := c.delChannelEdgeUnsafe(
86✔
1822
                                edges, edgeIndex, chanIndex, zombieIndex,
86✔
1823
                                rawChanID[:], markZombie, strictZombiePruning,
86✔
1824
                        )
86✔
1825
                        if err != nil {
147✔
1826
                                return err
61✔
1827
                        }
61✔
1828
                }
1829

1830
                return nil
91✔
1831
        }, func() {})
152✔
1832
        if err != nil {
213✔
1833
                return err
61✔
1834
        }
61✔
1835

1836
        for _, chanID := range chanIDs {
116✔
1837
                c.rejectCache.remove(chanID)
25✔
1838
                c.chanCache.remove(chanID)
25✔
1839
        }
25✔
1840

1841
        return nil
91✔
1842
}
1843

1844
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1845
// passed channel point (outpoint). If the passed channel doesn't exist within
1846
// the database, then ErrEdgeNotFound is returned.
1847
func (c *ChannelGraph) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
3✔
1848
        var chanID uint64
3✔
1849
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1850
                var err error
3✔
1851
                chanID, err = getChanID(tx, chanPoint)
3✔
1852
                return err
3✔
1853
        }, func() {
6✔
1854
                chanID = 0
3✔
1855
        }); err != nil {
5✔
1856
                return 0, err
2✔
1857
        }
2✔
1858

1859
        return chanID, nil
3✔
1860
}
1861

1862
// getChanID returns the assigned channel ID for a given channel point.
1863
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
3✔
1864
        var b bytes.Buffer
3✔
1865
        if err := WriteOutpoint(&b, chanPoint); err != nil {
3✔
1866
                return 0, err
×
1867
        }
×
1868

1869
        edges := tx.ReadBucket(edgeBucket)
3✔
1870
        if edges == nil {
3✔
1871
                return 0, ErrGraphNoEdgesFound
×
1872
        }
×
1873
        chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
1874
        if chanIndex == nil {
3✔
1875
                return 0, ErrGraphNoEdgesFound
×
1876
        }
×
1877

1878
        chanIDBytes := chanIndex.Get(b.Bytes())
3✔
1879
        if chanIDBytes == nil {
5✔
1880
                return 0, ErrEdgeNotFound
2✔
1881
        }
2✔
1882

1883
        chanID := byteOrder.Uint64(chanIDBytes)
3✔
1884

3✔
1885
        return chanID, nil
3✔
1886
}
1887

1888
// TODO(roasbeef): allow updates to use Batch?
1889

1890
// HighestChanID returns the "highest" known channel ID in the channel graph.
1891
// This represents the "newest" channel from the PoV of the chain. This method
1892
// can be used by peers to quickly determine if they're graphs are in sync.
1893
func (c *ChannelGraph) HighestChanID() (uint64, error) {
5✔
1894
        var cid uint64
5✔
1895

5✔
1896
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
1897
                edges := tx.ReadBucket(edgeBucket)
5✔
1898
                if edges == nil {
5✔
1899
                        return ErrGraphNoEdgesFound
×
1900
                }
×
1901
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
5✔
1902
                if edgeIndex == nil {
5✔
1903
                        return ErrGraphNoEdgesFound
×
1904
                }
×
1905

1906
                // In order to find the highest chan ID, we'll fetch a cursor
1907
                // and use that to seek to the "end" of our known rage.
1908
                cidCursor := edgeIndex.ReadCursor()
5✔
1909

5✔
1910
                lastChanID, _ := cidCursor.Last()
5✔
1911

5✔
1912
                // If there's no key, then this means that we don't actually
5✔
1913
                // know of any channels, so we'll return a predicable error.
5✔
1914
                if lastChanID == nil {
8✔
1915
                        return ErrGraphNoEdgesFound
3✔
1916
                }
3✔
1917

1918
                // Otherwise, we'll de serialize the channel ID and return it
1919
                // to the caller.
1920
                cid = byteOrder.Uint64(lastChanID)
4✔
1921
                return nil
4✔
1922
        }, func() {
5✔
1923
                cid = 0
5✔
1924
        })
5✔
1925
        if err != nil && err != ErrGraphNoEdgesFound {
5✔
1926
                return 0, err
×
1927
        }
×
1928

1929
        return cid, nil
5✔
1930
}
1931

1932
// ChannelEdge represents the complete set of information for a channel edge in
1933
// the known channel graph. This struct couples the core information of the
1934
// edge as well as each of the known advertised edge policies.
1935
type ChannelEdge struct {
1936
        // Info contains all the static information describing the channel.
1937
        Info *models.ChannelEdgeInfo
1938

1939
        // Policy1 points to the "first" edge policy of the channel containing
1940
        // the dynamic information required to properly route through the edge.
1941
        Policy1 *models.ChannelEdgePolicy
1942

1943
        // Policy2 points to the "second" edge policy of the channel containing
1944
        // the dynamic information required to properly route through the edge.
1945
        Policy2 *models.ChannelEdgePolicy
1946

1947
        // Node1 is "node 1" in the channel. This is the node that would have
1948
        // produced Policy1 if it exists.
1949
        Node1 *models.LightningNode
1950

1951
        // Node2 is "node 2" in the channel. This is the node that would have
1952
        // produced Policy2 if it exists.
1953
        Node2 *models.LightningNode
1954
}
1955

1956
// ChanUpdatesInHorizon returns all the known channel edges which have at least
1957
// one edge that has an update timestamp within the specified horizon.
1958
func (c *ChannelGraph) ChanUpdatesInHorizon(startTime,
1959
        endTime time.Time) ([]ChannelEdge, error) {
137✔
1960

137✔
1961
        // To ensure we don't return duplicate ChannelEdges, we'll use an
137✔
1962
        // additional map to keep track of the edges already seen to prevent
137✔
1963
        // re-adding it.
137✔
1964
        var edgesSeen map[uint64]struct{}
137✔
1965
        var edgesToCache map[uint64]ChannelEdge
137✔
1966
        var edgesInHorizon []ChannelEdge
137✔
1967

137✔
1968
        c.cacheMu.Lock()
137✔
1969
        defer c.cacheMu.Unlock()
137✔
1970

137✔
1971
        var hits int
137✔
1972
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
274✔
1973
                edges := tx.ReadBucket(edgeBucket)
137✔
1974
                if edges == nil {
137✔
1975
                        return ErrGraphNoEdgesFound
×
1976
                }
×
1977
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
137✔
1978
                if edgeIndex == nil {
137✔
1979
                        return ErrGraphNoEdgesFound
×
1980
                }
×
1981
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
137✔
1982
                if edgeUpdateIndex == nil {
137✔
1983
                        return ErrGraphNoEdgesFound
×
1984
                }
×
1985

1986
                nodes := tx.ReadBucket(nodeBucket)
137✔
1987
                if nodes == nil {
137✔
1988
                        return ErrGraphNodesNotFound
×
1989
                }
×
1990

1991
                // We'll now obtain a cursor to perform a range query within
1992
                // the index to find all channels within the horizon.
1993
                updateCursor := edgeUpdateIndex.ReadCursor()
137✔
1994

137✔
1995
                var startTimeBytes, endTimeBytes [8 + 8]byte
137✔
1996
                byteOrder.PutUint64(
137✔
1997
                        startTimeBytes[:8], uint64(startTime.Unix()),
137✔
1998
                )
137✔
1999
                byteOrder.PutUint64(
137✔
2000
                        endTimeBytes[:8], uint64(endTime.Unix()),
137✔
2001
                )
137✔
2002

137✔
2003
                // With our start and end times constructed, we'll step through
137✔
2004
                // the index collecting the info and policy of each update of
137✔
2005
                // each channel that has a last update within the time range.
137✔
2006
                //
137✔
2007
                //nolint:ll
137✔
2008
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
137✔
2009
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
185✔
2010

48✔
2011
                        // We have a new eligible entry, so we'll slice of the
48✔
2012
                        // chan ID so we can query it in the DB.
48✔
2013
                        chanID := indexKey[8:]
48✔
2014

48✔
2015
                        // If we've already retrieved the info and policies for
48✔
2016
                        // this edge, then we can skip it as we don't need to do
48✔
2017
                        // so again.
48✔
2018
                        chanIDInt := byteOrder.Uint64(chanID)
48✔
2019
                        if _, ok := edgesSeen[chanIDInt]; ok {
67✔
2020
                                continue
19✔
2021
                        }
2022

2023
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
40✔
2024
                                hits++
11✔
2025
                                edgesSeen[chanIDInt] = struct{}{}
11✔
2026
                                edgesInHorizon = append(edgesInHorizon, channel)
11✔
2027
                                continue
11✔
2028
                        }
2029

2030
                        // First, we'll fetch the static edge information.
2031
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
20✔
2032
                        if err != nil {
20✔
2033
                                chanID := byteOrder.Uint64(chanID)
×
2034
                                return fmt.Errorf("unable to fetch info for "+
×
2035
                                        "edge with chan_id=%v: %v", chanID, err)
×
2036
                        }
×
2037

2038
                        // With the static information obtained, we'll now
2039
                        // fetch the dynamic policy info.
2040
                        edge1, edge2, err := fetchChanEdgePolicies(
20✔
2041
                                edgeIndex, edges, chanID,
20✔
2042
                        )
20✔
2043
                        if err != nil {
20✔
2044
                                chanID := byteOrder.Uint64(chanID)
×
2045
                                return fmt.Errorf("unable to fetch policies "+
×
2046
                                        "for edge with chan_id=%v: %v", chanID,
×
2047
                                        err)
×
2048
                        }
×
2049

2050
                        node1, err := fetchLightningNode(
20✔
2051
                                nodes, edgeInfo.NodeKey1Bytes[:],
20✔
2052
                        )
20✔
2053
                        if err != nil {
20✔
2054
                                return err
×
2055
                        }
×
2056

2057
                        node2, err := fetchLightningNode(
20✔
2058
                                nodes, edgeInfo.NodeKey2Bytes[:],
20✔
2059
                        )
20✔
2060
                        if err != nil {
20✔
2061
                                return err
×
2062
                        }
×
2063

2064
                        // Finally, we'll collate this edge with the rest of
2065
                        // edges to be returned.
2066
                        edgesSeen[chanIDInt] = struct{}{}
20✔
2067
                        channel := ChannelEdge{
20✔
2068
                                Info:    &edgeInfo,
20✔
2069
                                Policy1: edge1,
20✔
2070
                                Policy2: edge2,
20✔
2071
                                Node1:   &node1,
20✔
2072
                                Node2:   &node2,
20✔
2073
                        }
20✔
2074
                        edgesInHorizon = append(edgesInHorizon, channel)
20✔
2075
                        edgesToCache[chanIDInt] = channel
20✔
2076
                }
2077

2078
                return nil
137✔
2079
        }, func() {
137✔
2080
                edgesSeen = make(map[uint64]struct{})
137✔
2081
                edgesToCache = make(map[uint64]ChannelEdge)
137✔
2082
                edgesInHorizon = nil
137✔
2083
        })
137✔
2084
        switch {
137✔
2085
        case err == ErrGraphNoEdgesFound:
×
2086
                fallthrough
×
2087
        case err == ErrGraphNodesNotFound:
×
2088
                break
×
2089

2090
        case err != nil:
×
2091
                return nil, err
×
2092
        }
2093

2094
        // Insert any edges loaded from disk into the cache.
2095
        for chanid, channel := range edgesToCache {
157✔
2096
                c.chanCache.insert(chanid, channel)
20✔
2097
        }
20✔
2098

2099
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
137✔
2100
                float64(hits)/float64(len(edgesInHorizon)), hits,
137✔
2101
                len(edgesInHorizon))
137✔
2102

137✔
2103
        return edgesInHorizon, nil
137✔
2104
}
2105

2106
// NodeUpdatesInHorizon returns all the known lightning node which have an
2107
// update timestamp within the passed range. This method can be used by two
2108
// nodes to quickly determine if they have the same set of up to date node
2109
// announcements.
2110
func (c *ChannelGraph) NodeUpdatesInHorizon(startTime,
2111
        endTime time.Time) ([]models.LightningNode, error) {
10✔
2112

10✔
2113
        var nodesInHorizon []models.LightningNode
10✔
2114

10✔
2115
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
20✔
2116
                nodes := tx.ReadBucket(nodeBucket)
10✔
2117
                if nodes == nil {
10✔
2118
                        return ErrGraphNodesNotFound
×
2119
                }
×
2120

2121
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
10✔
2122
                if nodeUpdateIndex == nil {
10✔
2123
                        return ErrGraphNodesNotFound
×
2124
                }
×
2125

2126
                // We'll now obtain a cursor to perform a range query within
2127
                // the index to find all node announcements within the horizon.
2128
                updateCursor := nodeUpdateIndex.ReadCursor()
10✔
2129

10✔
2130
                var startTimeBytes, endTimeBytes [8 + 33]byte
10✔
2131
                byteOrder.PutUint64(
10✔
2132
                        startTimeBytes[:8], uint64(startTime.Unix()),
10✔
2133
                )
10✔
2134
                byteOrder.PutUint64(
10✔
2135
                        endTimeBytes[:8], uint64(endTime.Unix()),
10✔
2136
                )
10✔
2137

10✔
2138
                // With our start and end times constructed, we'll step through
10✔
2139
                // the index collecting info for each node within the time
10✔
2140
                // range.
10✔
2141
                //
10✔
2142
                //nolint:ll
10✔
2143
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
10✔
2144
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
41✔
2145

31✔
2146
                        nodePub := indexKey[8:]
31✔
2147
                        node, err := fetchLightningNode(nodes, nodePub)
31✔
2148
                        if err != nil {
31✔
2149
                                return err
×
2150
                        }
×
2151

2152
                        nodesInHorizon = append(nodesInHorizon, node)
31✔
2153
                }
2154

2155
                return nil
10✔
2156
        }, func() {
10✔
2157
                nodesInHorizon = nil
10✔
2158
        })
10✔
2159
        switch {
10✔
2160
        case err == ErrGraphNoEdgesFound:
×
2161
                fallthrough
×
2162
        case err == ErrGraphNodesNotFound:
×
2163
                break
×
2164

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

2169
        return nodesInHorizon, nil
10✔
2170
}
2171

2172
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2173
// ID's that we don't know and are not known zombies of the passed set. In other
2174
// words, we perform a set difference of our set of chan ID's and the ones
2175
// passed in. This method can be used by callers to determine the set of
2176
// channels another peer knows of that we don't.
2177
func (c *ChannelGraph) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo,
2178
        isZombieChan func(time.Time, time.Time) bool) ([]uint64, error) {
119✔
2179

119✔
2180
        var newChanIDs []uint64
119✔
2181

119✔
2182
        c.cacheMu.Lock()
119✔
2183
        defer c.cacheMu.Unlock()
119✔
2184

119✔
2185
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
238✔
2186
                edges := tx.ReadBucket(edgeBucket)
119✔
2187
                if edges == nil {
119✔
2188
                        return ErrGraphNoEdgesFound
×
2189
                }
×
2190
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
119✔
2191
                if edgeIndex == nil {
119✔
2192
                        return ErrGraphNoEdgesFound
×
2193
                }
×
2194

2195
                // Fetch the zombie index, it may not exist if no edges have
2196
                // ever been marked as zombies. If the index has been
2197
                // initialized, we will use it later to skip known zombie edges.
2198
                zombieIndex := edges.NestedReadBucket(zombieBucket)
119✔
2199

119✔
2200
                // We'll run through the set of chanIDs and collate only the
119✔
2201
                // set of channel that are unable to be found within our db.
119✔
2202
                var cidBytes [8]byte
119✔
2203
                for _, info := range chansInfo {
224✔
2204
                        scid := info.ShortChannelID.ToUint64()
105✔
2205
                        byteOrder.PutUint64(cidBytes[:], scid)
105✔
2206

105✔
2207
                        // If the edge is already known, skip it.
105✔
2208
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
124✔
2209
                                continue
19✔
2210
                        }
2211

2212
                        // If the edge is a known zombie, skip it.
2213
                        if zombieIndex != nil {
176✔
2214
                                isZombie, _, _ := isZombieEdge(
88✔
2215
                                        zombieIndex, scid,
88✔
2216
                                )
88✔
2217

88✔
2218
                                // TODO(ziggie): Make sure that for the strict
88✔
2219
                                // pruning case we compare the pubkeys and
88✔
2220
                                // whether the right timestamp is not older than
88✔
2221
                                // the `ChannelPruneExpiry`.
88✔
2222
                                //
88✔
2223
                                // NOTE: The timestamp data has no verification
88✔
2224
                                // attached to it in the `ReplyChannelRange` msg
88✔
2225
                                // so we are trusting this data at this point.
88✔
2226
                                // However it is not critical because we are
88✔
2227
                                // just removing the channel from the db when
88✔
2228
                                // the timestamps are more recent. During the
88✔
2229
                                // querying of the gossip msg verification
88✔
2230
                                // happens as usual.
88✔
2231
                                // However we should start punishing peers when
88✔
2232
                                // they don't provide us honest data ?
88✔
2233
                                isStillZombie := isZombieChan(
88✔
2234
                                        info.Node1UpdateTimestamp,
88✔
2235
                                        info.Node2UpdateTimestamp,
88✔
2236
                                )
88✔
2237

88✔
2238
                                switch {
88✔
2239
                                // If the edge is a known zombie and if we
2240
                                // would still consider it a zombie given the
2241
                                // latest update timestamps, then we skip this
2242
                                // channel.
2243
                                case isZombie && isStillZombie:
25✔
2244
                                        continue
25✔
2245

2246
                                // Otherwise, if we have marked it as a zombie
2247
                                // but the latest update timestamps could bring
2248
                                // it back from the dead, then we mark it alive,
2249
                                // and we let it be added to the set of IDs to
2250
                                // query our peer for.
2251
                                case isZombie && !isStillZombie:
22✔
2252
                                        err := c.markEdgeLiveUnsafe(tx, scid)
22✔
2253
                                        if err != nil {
22✔
2254
                                                return err
×
2255
                                        }
×
2256
                                }
2257
                        }
2258

2259
                        newChanIDs = append(newChanIDs, scid)
63✔
2260
                }
2261

2262
                return nil
119✔
2263
        }, func() {
119✔
2264
                newChanIDs = nil
119✔
2265
        })
119✔
2266
        switch {
119✔
2267
        // If we don't know of any edges yet, then we'll return the entire set
2268
        // of chan IDs specified.
2269
        case err == ErrGraphNoEdgesFound:
×
2270
                ogChanIDs := make([]uint64, len(chansInfo))
×
2271
                for i, info := range chansInfo {
×
2272
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2273
                }
×
2274

2275
                return ogChanIDs, nil
×
2276

2277
        case err != nil:
×
2278
                return nil, err
×
2279
        }
2280

2281
        return newChanIDs, nil
119✔
2282
}
2283

2284
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2285
// latest received channel updates for the channel.
2286
type ChannelUpdateInfo struct {
2287
        // ShortChannelID is the SCID identifier of the channel.
2288
        ShortChannelID lnwire.ShortChannelID
2289

2290
        // Node1UpdateTimestamp is the timestamp of the latest received update
2291
        // from the node 1 channel peer. This will be set to zero time if no
2292
        // update has yet been received from this node.
2293
        Node1UpdateTimestamp time.Time
2294

2295
        // Node2UpdateTimestamp is the timestamp of the latest received update
2296
        // from the node 2 channel peer. This will be set to zero time if no
2297
        // update has yet been received from this node.
2298
        Node2UpdateTimestamp time.Time
2299
}
2300

2301
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2302
// timestamps with zero seconds unix timestamp which equals
2303
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2304
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2305
        node2Timestamp time.Time) ChannelUpdateInfo {
220✔
2306

220✔
2307
        chanInfo := ChannelUpdateInfo{
220✔
2308
                ShortChannelID:       scid,
220✔
2309
                Node1UpdateTimestamp: node1Timestamp,
220✔
2310
                Node2UpdateTimestamp: node2Timestamp,
220✔
2311
        }
220✔
2312

220✔
2313
        if node1Timestamp.IsZero() {
430✔
2314
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
210✔
2315
        }
210✔
2316

2317
        if node2Timestamp.IsZero() {
430✔
2318
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
210✔
2319
        }
210✔
2320

2321
        return chanInfo
220✔
2322
}
2323

2324
// BlockChannelRange represents a range of channels for a given block height.
2325
type BlockChannelRange struct {
2326
        // Height is the height of the block all of the channels below were
2327
        // included in.
2328
        Height uint32
2329

2330
        // Channels is the list of channels identified by their short ID
2331
        // representation known to us that were included in the block height
2332
        // above. The list may include channel update timestamp information if
2333
        // requested.
2334
        Channels []ChannelUpdateInfo
2335
}
2336

2337
// FilterChannelRange returns the channel ID's of all known channels which were
2338
// mined in a block height within the passed range. The channel IDs are grouped
2339
// by their common block height. This method can be used to quickly share with a
2340
// peer the set of channels we know of within a particular range to catch them
2341
// up after a period of time offline. If withTimestamps is true then the
2342
// timestamp info of the latest received channel update messages of the channel
2343
// will be included in the response.
2344
func (c *ChannelGraph) FilterChannelRange(startHeight,
2345
        endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error) {
13✔
2346

13✔
2347
        startChanID := &lnwire.ShortChannelID{
13✔
2348
                BlockHeight: startHeight,
13✔
2349
        }
13✔
2350

13✔
2351
        endChanID := lnwire.ShortChannelID{
13✔
2352
                BlockHeight: endHeight,
13✔
2353
                TxIndex:     math.MaxUint32 & 0x00ffffff,
13✔
2354
                TxPosition:  math.MaxUint16,
13✔
2355
        }
13✔
2356

13✔
2357
        // As we need to perform a range scan, we'll convert the starting and
13✔
2358
        // ending height to their corresponding values when encoded using short
13✔
2359
        // channel ID's.
13✔
2360
        var chanIDStart, chanIDEnd [8]byte
13✔
2361
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
13✔
2362
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
13✔
2363

13✔
2364
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
13✔
2365
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
26✔
2366
                edges := tx.ReadBucket(edgeBucket)
13✔
2367
                if edges == nil {
13✔
2368
                        return ErrGraphNoEdgesFound
×
2369
                }
×
2370
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
13✔
2371
                if edgeIndex == nil {
13✔
2372
                        return ErrGraphNoEdgesFound
×
2373
                }
×
2374

2375
                cursor := edgeIndex.ReadCursor()
13✔
2376

13✔
2377
                // We'll now iterate through the database, and find each
13✔
2378
                // channel ID that resides within the specified range.
13✔
2379
                //
13✔
2380
                //nolint:ll
13✔
2381
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
13✔
2382
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
59✔
2383
                        // Don't send alias SCIDs during gossip sync.
46✔
2384
                        edgeReader := bytes.NewReader(v)
46✔
2385
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
46✔
2386
                        if err != nil {
46✔
2387
                                return err
×
2388
                        }
×
2389

2390
                        if edgeInfo.AuthProof == nil {
48✔
2391
                                continue
2✔
2392
                        }
2393

2394
                        // This channel ID rests within the target range, so
2395
                        // we'll add it to our returned set.
2396
                        rawCid := byteOrder.Uint64(k)
46✔
2397
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
46✔
2398

46✔
2399
                        chanInfo := NewChannelUpdateInfo(
46✔
2400
                                cid, time.Time{}, time.Time{},
46✔
2401
                        )
46✔
2402

46✔
2403
                        if !withTimestamps {
68✔
2404
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2405
                                        channelsPerBlock[cid.BlockHeight],
22✔
2406
                                        chanInfo,
22✔
2407
                                )
22✔
2408

22✔
2409
                                continue
22✔
2410
                        }
2411

2412
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
24✔
2413

24✔
2414
                        rawPolicy := edges.Get(node1Key)
24✔
2415
                        if len(rawPolicy) != 0 {
32✔
2416
                                r := bytes.NewReader(rawPolicy)
8✔
2417

8✔
2418
                                edge, err := deserializeChanEdgePolicyRaw(r)
8✔
2419
                                if err != nil && !errors.Is(
8✔
2420
                                        err, ErrEdgePolicyOptionalFieldNotFound,
8✔
2421
                                ) {
8✔
2422

×
2423
                                        return err
×
2424
                                }
×
2425

2426
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
8✔
2427
                        }
2428

2429
                        rawPolicy = edges.Get(node2Key)
24✔
2430
                        if len(rawPolicy) != 0 {
37✔
2431
                                r := bytes.NewReader(rawPolicy)
13✔
2432

13✔
2433
                                edge, err := deserializeChanEdgePolicyRaw(r)
13✔
2434
                                if err != nil && !errors.Is(
13✔
2435
                                        err, ErrEdgePolicyOptionalFieldNotFound,
13✔
2436
                                ) {
13✔
2437

×
2438
                                        return err
×
2439
                                }
×
2440

2441
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
13✔
2442
                        }
2443

2444
                        channelsPerBlock[cid.BlockHeight] = append(
24✔
2445
                                channelsPerBlock[cid.BlockHeight], chanInfo,
24✔
2446
                        )
24✔
2447
                }
2448

2449
                return nil
13✔
2450
        }, func() {
13✔
2451
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
13✔
2452
        })
13✔
2453

2454
        switch {
13✔
2455
        // If we don't know of any channels yet, then there's nothing to
2456
        // filter, so we'll return an empty slice.
2457
        case err == ErrGraphNoEdgesFound || len(channelsPerBlock) == 0:
5✔
2458
                return nil, nil
5✔
2459

2460
        case err != nil:
×
2461
                return nil, err
×
2462
        }
2463

2464
        // Return the channel ranges in ascending block height order.
2465
        blocks := make([]uint32, 0, len(channelsPerBlock))
10✔
2466
        for block := range channelsPerBlock {
34✔
2467
                blocks = append(blocks, block)
24✔
2468
        }
24✔
2469
        sort.Slice(blocks, func(i, j int) bool {
29✔
2470
                return blocks[i] < blocks[j]
19✔
2471
        })
19✔
2472

2473
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
10✔
2474
        for _, block := range blocks {
34✔
2475
                channelRanges = append(channelRanges, BlockChannelRange{
24✔
2476
                        Height:   block,
24✔
2477
                        Channels: channelsPerBlock[block],
24✔
2478
                })
24✔
2479
        }
24✔
2480

2481
        return channelRanges, nil
10✔
2482
}
2483

2484
// FetchChanInfos returns the set of channel edges that correspond to the passed
2485
// channel ID's. If an edge is the query is unknown to the database, it will
2486
// skipped and the result will contain only those edges that exist at the time
2487
// of the query. This can be used to respond to peer queries that are seeking to
2488
// fill in gaps in their view of the channel graph.
2489
func (c *ChannelGraph) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
5✔
2490
        return c.fetchChanInfos(nil, chanIDs)
5✔
2491
}
5✔
2492

2493
// fetchChanInfos returns the set of channel edges that correspond to the passed
2494
// channel ID's. If an edge is the query is unknown to the database, it will
2495
// skipped and the result will contain only those edges that exist at the time
2496
// of the query. This can be used to respond to peer queries that are seeking to
2497
// fill in gaps in their view of the channel graph.
2498
//
2499
// NOTE: An optional transaction may be provided. If none is provided, then a
2500
// new one will be created.
2501
func (c *ChannelGraph) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2502
        []ChannelEdge, error) {
28✔
2503
        // TODO(roasbeef): sort cids?
28✔
2504

28✔
2505
        var (
28✔
2506
                chanEdges []ChannelEdge
28✔
2507
                cidBytes  [8]byte
28✔
2508
        )
28✔
2509

28✔
2510
        fetchChanInfos := func(tx kvdb.RTx) error {
56✔
2511
                edges := tx.ReadBucket(edgeBucket)
28✔
2512
                if edges == nil {
28✔
2513
                        return ErrGraphNoEdgesFound
×
2514
                }
×
2515
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
28✔
2516
                if edgeIndex == nil {
28✔
2517
                        return ErrGraphNoEdgesFound
×
2518
                }
×
2519
                nodes := tx.ReadBucket(nodeBucket)
28✔
2520
                if nodes == nil {
28✔
2521
                        return ErrGraphNotFound
×
2522
                }
×
2523

2524
                for _, cid := range chanIDs {
63✔
2525
                        byteOrder.PutUint64(cidBytes[:], cid)
35✔
2526

35✔
2527
                        // First, we'll fetch the static edge information. If
35✔
2528
                        // the edge is unknown, we will skip the edge and
35✔
2529
                        // continue gathering all known edges.
35✔
2530
                        edgeInfo, err := fetchChanEdgeInfo(
35✔
2531
                                edgeIndex, cidBytes[:],
35✔
2532
                        )
35✔
2533
                        switch {
35✔
2534
                        case errors.Is(err, ErrEdgeNotFound):
25✔
2535
                                continue
25✔
2536
                        case err != nil:
×
2537
                                return err
×
2538
                        }
2539

2540
                        // With the static information obtained, we'll now
2541
                        // fetch the dynamic policy info.
2542
                        edge1, edge2, err := fetchChanEdgePolicies(
10✔
2543
                                edgeIndex, edges, cidBytes[:],
10✔
2544
                        )
10✔
2545
                        if err != nil {
10✔
2546
                                return err
×
2547
                        }
×
2548

2549
                        node1, err := fetchLightningNode(
10✔
2550
                                nodes, edgeInfo.NodeKey1Bytes[:],
10✔
2551
                        )
10✔
2552
                        if err != nil {
10✔
2553
                                return err
×
2554
                        }
×
2555

2556
                        node2, err := fetchLightningNode(
10✔
2557
                                nodes, edgeInfo.NodeKey2Bytes[:],
10✔
2558
                        )
10✔
2559
                        if err != nil {
10✔
2560
                                return err
×
2561
                        }
×
2562

2563
                        chanEdges = append(chanEdges, ChannelEdge{
10✔
2564
                                Info:    &edgeInfo,
10✔
2565
                                Policy1: edge1,
10✔
2566
                                Policy2: edge2,
10✔
2567
                                Node1:   &node1,
10✔
2568
                                Node2:   &node2,
10✔
2569
                        })
10✔
2570
                }
2571
                return nil
28✔
2572
        }
2573

2574
        if tx == nil {
34✔
2575
                err := kvdb.View(c.db, fetchChanInfos, func() {
12✔
2576
                        chanEdges = nil
6✔
2577
                })
6✔
2578
                if err != nil {
6✔
2579
                        return nil, err
×
2580
                }
×
2581

2582
                return chanEdges, nil
6✔
2583
        }
2584

2585
        err := fetchChanInfos(tx)
22✔
2586
        if err != nil {
22✔
2587
                return nil, err
×
2588
        }
×
2589

2590
        return chanEdges, nil
22✔
2591
}
2592

2593
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2594
        edge1, edge2 *models.ChannelEdgePolicy) error {
132✔
2595

132✔
2596
        // First, we'll fetch the edge update index bucket which currently
132✔
2597
        // stores an entry for the channel we're about to delete.
132✔
2598
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
132✔
2599
        if updateIndex == nil {
132✔
2600
                // No edges in bucket, return early.
×
2601
                return nil
×
2602
        }
×
2603

2604
        // Now that we have the bucket, we'll attempt to construct a template
2605
        // for the index key: updateTime || chanid.
2606
        var indexKey [8 + 8]byte
132✔
2607
        byteOrder.PutUint64(indexKey[8:], chanID)
132✔
2608

132✔
2609
        // With the template constructed, we'll attempt to delete an entry that
132✔
2610
        // would have been created by both edges: we'll alternate the update
132✔
2611
        // times, as one may had overridden the other.
132✔
2612
        if edge1 != nil {
144✔
2613
                byteOrder.PutUint64(
12✔
2614
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
12✔
2615
                )
12✔
2616
                if err := updateIndex.Delete(indexKey[:]); err != nil {
12✔
2617
                        return err
×
2618
                }
×
2619
        }
2620

2621
        // We'll also attempt to delete the entry that may have been created by
2622
        // the second edge.
2623
        if edge2 != nil {
146✔
2624
                byteOrder.PutUint64(
14✔
2625
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
14✔
2626
                )
14✔
2627
                if err := updateIndex.Delete(indexKey[:]); err != nil {
14✔
2628
                        return err
×
2629
                }
×
2630
        }
2631

2632
        return nil
132✔
2633
}
2634

2635
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2636
// cache. It then goes on to delete any policy info and edge info for this
2637
// channel from the DB and finally, if isZombie is true, it will add an entry
2638
// for this channel in the zombie index.
2639
//
2640
// NOTE: this method MUST only be called if the cacheMu has already been
2641
// acquired.
2642
func (c *ChannelGraph) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2643
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2644
        strictZombie bool) error {
193✔
2645

193✔
2646
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
193✔
2647
        if err != nil {
254✔
2648
                return err
61✔
2649
        }
61✔
2650

2651
        if c.graphCache != nil {
264✔
2652
                c.graphCache.RemoveChannel(
132✔
2653
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
132✔
2654
                        edgeInfo.ChannelID,
132✔
2655
                )
132✔
2656
        }
132✔
2657

2658
        // We'll also remove the entry in the edge update index bucket before
2659
        // we delete the edges themselves so we can access their last update
2660
        // times.
2661
        cid := byteOrder.Uint64(chanID)
132✔
2662
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
132✔
2663
        if err != nil {
132✔
2664
                return err
×
2665
        }
×
2666
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
132✔
2667
        if err != nil {
132✔
2668
                return err
×
2669
        }
×
2670

2671
        // The edge key is of the format pubKey || chanID. First we construct
2672
        // the latter half, populating the channel ID.
2673
        var edgeKey [33 + 8]byte
132✔
2674
        copy(edgeKey[33:], chanID)
132✔
2675

132✔
2676
        // With the latter half constructed, copy over the first public key to
132✔
2677
        // delete the edge in this direction, then the second to delete the
132✔
2678
        // edge in the opposite direction.
132✔
2679
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
132✔
2680
        if edges.Get(edgeKey[:]) != nil {
264✔
2681
                if err := edges.Delete(edgeKey[:]); err != nil {
132✔
2682
                        return err
×
2683
                }
×
2684
        }
2685
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
132✔
2686
        if edges.Get(edgeKey[:]) != nil {
264✔
2687
                if err := edges.Delete(edgeKey[:]); err != nil {
132✔
2688
                        return err
×
2689
                }
×
2690
        }
2691

2692
        // As part of deleting the edge we also remove all disabled entries
2693
        // from the edgePolicyDisabledIndex bucket. We do that for both
2694
        // directions.
2695
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
132✔
2696
        if err != nil {
132✔
2697
                return err
×
2698
        }
×
2699
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
132✔
2700
        if err != nil {
132✔
2701
                return err
×
2702
        }
×
2703

2704
        // With the edge data deleted, we can purge the information from the two
2705
        // edge indexes.
2706
        if err := edgeIndex.Delete(chanID); err != nil {
132✔
2707
                return err
×
2708
        }
×
2709
        var b bytes.Buffer
132✔
2710
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
132✔
2711
                return err
×
2712
        }
×
2713
        if err := chanIndex.Delete(b.Bytes()); err != nil {
132✔
2714
                return err
×
2715
        }
×
2716

2717
        // Finally, we'll mark the edge as a zombie within our index if it's
2718
        // being removed due to the channel becoming a zombie. We do this to
2719
        // ensure we don't store unnecessary data for spent channels.
2720
        if !isZombie {
243✔
2721
                return nil
111✔
2722
        }
111✔
2723

2724
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
23✔
2725
        if strictZombie {
26✔
2726
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2727
        }
3✔
2728

2729
        return markEdgeZombie(
23✔
2730
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
23✔
2731
        )
23✔
2732
}
2733

2734
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2735
// particular pair of channel policies. The return values are one of:
2736
//  1. (pubkey1, pubkey2)
2737
//  2. (pubkey1, blank)
2738
//  3. (blank, pubkey2)
2739
//
2740
// A blank pubkey means that corresponding node will be unable to resurrect a
2741
// channel on its own. For example, node1 may continue to publish recent
2742
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2743
// we don't want another fresh update from node1 to resurrect, as the edge can
2744
// only become live once node2 finally sends something recent.
2745
//
2746
// In the case where we have neither update, we allow either party to resurrect
2747
// the channel. If the channel were to be marked zombie again, it would be
2748
// marked with the correct lagging channel since we received an update from only
2749
// one side.
2750
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
2751
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
3✔
2752

3✔
2753
        switch {
3✔
2754
        // If we don't have either edge policy, we'll return both pubkeys so
2755
        // that the channel can be resurrected by either party.
UNCOV
2756
        case e1 == nil && e2 == nil:
×
UNCOV
2757
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2758

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

2766
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2767
        // return a blank pubkey for edge1. In this case, only an update from
2768
        // edge2 can resurect the channel.
2769
        default:
2✔
2770
                return [33]byte{}, info.NodeKey2Bytes
2✔
2771
        }
2772
}
2773

2774
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2775
// within the database for the referenced channel. The `flags` attribute within
2776
// the ChannelEdgePolicy determines which of the directed edges are being
2777
// updated. If the flag is 1, then the first node's information is being
2778
// updated, otherwise it's the second node's information. The node ordering is
2779
// determined by the lexicographical ordering of the identity public keys of the
2780
// nodes on either side of the channel.
2781
func (c *ChannelGraph) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2782
        op ...batch.SchedulerOption) error {
2,665✔
2783

2,665✔
2784
        var (
2,665✔
2785
                isUpdate1    bool
2,665✔
2786
                edgeNotFound bool
2,665✔
2787
        )
2,665✔
2788

2,665✔
2789
        r := &batch.Request{
2,665✔
2790
                Reset: func() {
5,330✔
2791
                        isUpdate1 = false
2,665✔
2792
                        edgeNotFound = false
2,665✔
2793
                },
2,665✔
2794
                Update: func(tx kvdb.RwTx) error {
2,665✔
2795
                        var err error
2,665✔
2796
                        isUpdate1, err = updateEdgePolicy(
2,665✔
2797
                                tx, edge, c.graphCache,
2,665✔
2798
                        )
2,665✔
2799

2,665✔
2800
                        if err != nil {
2,668✔
2801
                                log.Errorf("UpdateEdgePolicy faild: %v", err)
3✔
2802
                        }
3✔
2803

2804
                        // Silence ErrEdgeNotFound so that the batch can
2805
                        // succeed, but propagate the error via local state.
2806
                        if errors.Is(err, ErrEdgeNotFound) {
2,668✔
2807
                                edgeNotFound = true
3✔
2808
                                return nil
3✔
2809
                        }
3✔
2810

2811
                        return err
2,662✔
2812
                },
2813
                OnCommit: func(err error) error {
2,665✔
2814
                        switch {
2,665✔
2815
                        case err != nil:
×
2816
                                return err
×
2817
                        case edgeNotFound:
3✔
2818
                                return ErrEdgeNotFound
3✔
2819
                        default:
2,662✔
2820
                                c.updateEdgeCache(edge, isUpdate1)
2,662✔
2821
                                return nil
2,662✔
2822
                        }
2823
                },
2824
        }
2825

2826
        for _, f := range op {
2,667✔
2827
                f(r)
2✔
2828
        }
2✔
2829

2830
        return c.chanScheduler.Execute(r)
2,665✔
2831
}
2832

2833
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2834
        isUpdate1 bool) {
2,662✔
2835

2,662✔
2836
        // If an entry for this channel is found in reject cache, we'll modify
2,662✔
2837
        // the entry with the updated timestamp for the direction that was just
2,662✔
2838
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,662✔
2839
        // during the next query for this edge.
2,662✔
2840
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,669✔
2841
                if isUpdate1 {
12✔
2842
                        entry.upd1Time = e.LastUpdate.Unix()
5✔
2843
                } else {
9✔
2844
                        entry.upd2Time = e.LastUpdate.Unix()
4✔
2845
                }
4✔
2846
                c.rejectCache.insert(e.ChannelID, entry)
7✔
2847
        }
2848

2849
        // If an entry for this channel is found in channel cache, we'll modify
2850
        // the entry with the updated policy for the direction that was just
2851
        // written. If the edge doesn't exist, we'll defer loading the info and
2852
        // policies and lazily read from disk during the next query.
2853
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
2,664✔
2854
                if isUpdate1 {
4✔
2855
                        channel.Policy1 = e
2✔
2856
                } else {
4✔
2857
                        channel.Policy2 = e
2✔
2858
                }
2✔
2859
                c.chanCache.insert(e.ChannelID, channel)
2✔
2860
        }
2861
}
2862

2863
// updateEdgePolicy attempts to update an edge's policy within the relevant
2864
// buckets using an existing database transaction. The returned boolean will be
2865
// true if the updated policy belongs to node1, and false if the policy belonged
2866
// to node2.
2867
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy,
2868
        graphCache *GraphCache) (bool, error) {
2,665✔
2869

2,665✔
2870
        edges := tx.ReadWriteBucket(edgeBucket)
2,665✔
2871
        if edges == nil {
2,665✔
2872
                return false, ErrEdgeNotFound
×
2873
        }
×
2874
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,665✔
2875
        if edgeIndex == nil {
2,665✔
2876
                return false, ErrEdgeNotFound
×
2877
        }
×
2878

2879
        // Create the channelID key be converting the channel ID
2880
        // integer into a byte slice.
2881
        var chanID [8]byte
2,665✔
2882
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,665✔
2883

2,665✔
2884
        // With the channel ID, we then fetch the value storing the two
2,665✔
2885
        // nodes which connect this channel edge.
2,665✔
2886
        nodeInfo := edgeIndex.Get(chanID[:])
2,665✔
2887
        if nodeInfo == nil {
2,668✔
2888
                return false, ErrEdgeNotFound
3✔
2889
        }
3✔
2890

2891
        // Depending on the flags value passed above, either the first
2892
        // or second edge policy is being updated.
2893
        var fromNode, toNode []byte
2,662✔
2894
        var isUpdate1 bool
2,662✔
2895
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3,996✔
2896
                fromNode = nodeInfo[:33]
1,334✔
2897
                toNode = nodeInfo[33:66]
1,334✔
2898
                isUpdate1 = true
1,334✔
2899
        } else {
2,664✔
2900
                fromNode = nodeInfo[33:66]
1,330✔
2901
                toNode = nodeInfo[:33]
1,330✔
2902
                isUpdate1 = false
1,330✔
2903
        }
1,330✔
2904

2905
        // Finally, with the direction of the edge being updated
2906
        // identified, we update the on-disk edge representation.
2907
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,662✔
2908
        if err != nil {
2,662✔
2909
                return false, err
×
2910
        }
×
2911

2912
        var (
2,662✔
2913
                fromNodePubKey route.Vertex
2,662✔
2914
                toNodePubKey   route.Vertex
2,662✔
2915
        )
2,662✔
2916
        copy(fromNodePubKey[:], fromNode)
2,662✔
2917
        copy(toNodePubKey[:], toNode)
2,662✔
2918

2,662✔
2919
        if graphCache != nil {
4,938✔
2920
                graphCache.UpdatePolicy(
2,276✔
2921
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,276✔
2922
                )
2,276✔
2923
        }
2,276✔
2924

2925
        return isUpdate1, nil
2,662✔
2926
}
2927

2928
// isPublic determines whether the node is seen as public within the graph from
2929
// the source node's point of view. An existing database transaction can also be
2930
// specified.
2931
func (c *ChannelGraph) isPublic(tx kvdb.RTx, nodePub route.Vertex,
2932
        sourcePubKey []byte) (bool, error) {
15✔
2933

15✔
2934
        // In order to determine whether this node is publicly advertised within
15✔
2935
        // the graph, we'll need to look at all of its edges and check whether
15✔
2936
        // they extend to any other node than the source node. errDone will be
15✔
2937
        // used to terminate the check early.
15✔
2938
        nodeIsPublic := false
15✔
2939
        errDone := errors.New("done")
15✔
2940
        err := c.ForEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
15✔
2941
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
15✔
2942
                _ *models.ChannelEdgePolicy) error {
27✔
2943

12✔
2944
                // If this edge doesn't extend to the source node, we'll
12✔
2945
                // terminate our search as we can now conclude that the node is
12✔
2946
                // publicly advertised within the graph due to the local node
12✔
2947
                // knowing of the current edge.
12✔
2948
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
12✔
2949
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
17✔
2950

5✔
2951
                        nodeIsPublic = true
5✔
2952
                        return errDone
5✔
2953
                }
5✔
2954

2955
                // Since the edge _does_ extend to the source node, we'll also
2956
                // need to ensure that this is a public edge.
2957
                if info.AuthProof != nil {
17✔
2958
                        nodeIsPublic = true
8✔
2959
                        return errDone
8✔
2960
                }
8✔
2961

2962
                // Otherwise, we'll continue our search.
2963
                return nil
3✔
2964
        })
2965
        if err != nil && err != errDone {
15✔
2966
                return false, err
×
2967
        }
×
2968

2969
        return nodeIsPublic, nil
15✔
2970
}
2971

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

2,944✔
2979
        return c.fetchLightningNode(tx, nodePub)
2,944✔
2980
}
2,944✔
2981

2982
// FetchLightningNode attempts to look up a target node by its identity public
2983
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2984
// returned.
2985
func (c *ChannelGraph) FetchLightningNode(nodePub route.Vertex) (
2986
        *models.LightningNode, error) {
839✔
2987

839✔
2988
        return c.fetchLightningNode(nil, nodePub)
839✔
2989
}
839✔
2990

2991
// fetchLightningNode attempts to look up a target node by its identity public
2992
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2993
// returned. An optional transaction may be provided. If none is provided, then
2994
// a new one will be created.
2995
func (c *ChannelGraph) fetchLightningNode(tx kvdb.RTx,
2996
        nodePub route.Vertex) (*models.LightningNode, error) {
3,783✔
2997

3,783✔
2998
        var node *models.LightningNode
3,783✔
2999
        fetch := func(tx kvdb.RTx) error {
7,566✔
3000
                // First grab the nodes bucket which stores the mapping from
3,783✔
3001
                // pubKey to node information.
3,783✔
3002
                nodes := tx.ReadBucket(nodeBucket)
3,783✔
3003
                if nodes == nil {
3,783✔
3004
                        return ErrGraphNotFound
×
3005
                }
×
3006

3007
                // If a key for this serialized public key isn't found, then
3008
                // the target node doesn't exist within the database.
3009
                nodeBytes := nodes.Get(nodePub[:])
3,783✔
3010
                if nodeBytes == nil {
3,799✔
3011
                        return ErrGraphNodeNotFound
16✔
3012
                }
16✔
3013

3014
                // If the node is found, then we can de deserialize the node
3015
                // information to return to the user.
3016
                nodeReader := bytes.NewReader(nodeBytes)
3,769✔
3017
                n, err := deserializeLightningNode(nodeReader)
3,769✔
3018
                if err != nil {
3,769✔
3019
                        return err
×
3020
                }
×
3021

3022
                node = &n
3,769✔
3023

3,769✔
3024
                return nil
3,769✔
3025
        }
3026

3027
        if tx == nil {
4,622✔
3028
                err := kvdb.View(
839✔
3029
                        c.db, fetch, func() {
1,678✔
3030
                                node = nil
839✔
3031
                        },
839✔
3032
                )
3033
                if err != nil {
855✔
3034
                        return nil, err
16✔
3035
                }
16✔
3036

3037
                return node, nil
825✔
3038
        }
3039

3040
        err := fetch(tx)
2,944✔
3041
        if err != nil {
2,944✔
3042
                return nil, err
×
3043
        }
×
3044

3045
        return node, nil
2,944✔
3046
}
3047

3048
// graphCacheNode is a struct that wraps a LightningNode in a way that it can be
3049
// cached in the graph cache.
3050
type graphCacheNode struct {
3051
        pubKeyBytes route.Vertex
3052
        features    *lnwire.FeatureVector
3053
}
3054

3055
// newGraphCacheNode returns a new cache optimized node.
3056
func newGraphCacheNode(pubKey route.Vertex,
3057
        features *lnwire.FeatureVector) *graphCacheNode {
734✔
3058

734✔
3059
        return &graphCacheNode{
734✔
3060
                pubKeyBytes: pubKey,
734✔
3061
                features:    features,
734✔
3062
        }
734✔
3063
}
734✔
3064

3065
// PubKey returns the node's public identity key.
3066
func (n *graphCacheNode) PubKey() route.Vertex {
734✔
3067
        return n.pubKeyBytes
734✔
3068
}
734✔
3069

3070
// Features returns the node's features.
3071
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
714✔
3072
        return n.features
714✔
3073
}
714✔
3074

3075
// ForEachChannel iterates through all channels of this node, executing the
3076
// passed callback with an edge info structure and the policies of each end
3077
// of the channel. The first edge policy is the outgoing edge *to* the
3078
// connecting node, while the second is the incoming edge *from* the
3079
// connecting node. If the callback returns an error, then the iteration is
3080
// halted with the error propagated back up to the caller.
3081
//
3082
// Unknown policies are passed into the callback as nil values.
3083
func (n *graphCacheNode) ForEachChannel(tx kvdb.RTx,
3084
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3085
                *models.ChannelEdgePolicy) error) error {
634✔
3086

634✔
3087
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
634✔
3088
}
634✔
3089

3090
var _ GraphCacheNode = (*graphCacheNode)(nil)
3091

3092
// HasLightningNode determines if the graph has a vertex identified by the
3093
// target node identity public key. If the node exists in the database, a
3094
// timestamp of when the data for the node was lasted updated is returned along
3095
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3096
// boolean.
3097
func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool,
3098
        error) {
18✔
3099

18✔
3100
        var (
18✔
3101
                updateTime time.Time
18✔
3102
                exists     bool
18✔
3103
        )
18✔
3104

18✔
3105
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
36✔
3106
                // First grab the nodes bucket which stores the mapping from
18✔
3107
                // pubKey to node information.
18✔
3108
                nodes := tx.ReadBucket(nodeBucket)
18✔
3109
                if nodes == nil {
18✔
3110
                        return ErrGraphNotFound
×
3111
                }
×
3112

3113
                // If a key for this serialized public key isn't found, we can
3114
                // exit early.
3115
                nodeBytes := nodes.Get(nodePub[:])
18✔
3116
                if nodeBytes == nil {
23✔
3117
                        exists = false
5✔
3118
                        return nil
5✔
3119
                }
5✔
3120

3121
                // Otherwise we continue on to obtain the time stamp
3122
                // representing the last time the data for this node was
3123
                // updated.
3124
                nodeReader := bytes.NewReader(nodeBytes)
15✔
3125
                node, err := deserializeLightningNode(nodeReader)
15✔
3126
                if err != nil {
15✔
3127
                        return err
×
3128
                }
×
3129

3130
                exists = true
15✔
3131
                updateTime = node.LastUpdate
15✔
3132
                return nil
15✔
3133
        }, func() {
18✔
3134
                updateTime = time.Time{}
18✔
3135
                exists = false
18✔
3136
        })
18✔
3137
        if err != nil {
18✔
3138
                return time.Time{}, exists, err
×
3139
        }
×
3140

3141
        return updateTime, exists, nil
18✔
3142
}
3143

3144
// nodeTraversal is used to traverse all channels of a node given by its
3145
// public key and passes channel information into the specified callback.
3146
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3147
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3148
                *models.ChannelEdgePolicy) error) error {
1,880✔
3149

1,880✔
3150
        traversal := func(tx kvdb.RTx) error {
3,760✔
3151
                edges := tx.ReadBucket(edgeBucket)
1,880✔
3152
                if edges == nil {
1,880✔
3153
                        return ErrGraphNotFound
×
3154
                }
×
3155
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,880✔
3156
                if edgeIndex == nil {
1,880✔
3157
                        return ErrGraphNoEdgesFound
×
3158
                }
×
3159

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

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

3187
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,851✔
3188
                                edges, chanID, nodePub,
3,851✔
3189
                        )
3,851✔
3190
                        if err != nil {
3,851✔
3191
                                return err
×
3192
                        }
×
3193

3194
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,851✔
3195
                        if err != nil {
3,851✔
3196
                                return err
×
3197
                        }
×
3198

3199
                        incomingPolicy, err := fetchChanEdgePolicy(
3,851✔
3200
                                edges, chanID, otherNode[:],
3,851✔
3201
                        )
3,851✔
3202
                        if err != nil {
3,851✔
3203
                                return err
×
3204
                        }
×
3205

3206
                        // Finally, we execute the callback.
3207
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,851✔
3208
                        if err != nil {
3,862✔
3209
                                return err
11✔
3210
                        }
11✔
3211
                }
3212

3213
                return nil
1,871✔
3214
        }
3215

3216
        // If no transaction was provided, then we'll create a new transaction
3217
        // to execute the transaction within.
3218
        if tx == nil {
1,891✔
3219
                return kvdb.View(db, traversal, func() {})
22✔
3220
        }
3221

3222
        // Otherwise, we re-use the existing transaction to execute the graph
3223
        // traversal.
3224
        return traversal(tx)
1,871✔
3225
}
3226

3227
// ForEachNodeChannel iterates through all channels of the given node,
3228
// executing the passed callback with an edge info structure and the policies
3229
// of each end of the channel. The first edge policy is the outgoing edge *to*
3230
// the connecting node, while the second is the incoming edge *from* the
3231
// connecting node. If the callback returns an error, then the iteration is
3232
// halted with the error propagated back up to the caller.
3233
//
3234
// Unknown policies are passed into the callback as nil values.
3235
func (c *ChannelGraph) ForEachNodeChannel(nodePub route.Vertex,
3236
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3237
                *models.ChannelEdgePolicy) error) error {
8✔
3238

8✔
3239
        return nodeTraversal(nil, nodePub[:], c.db, cb)
8✔
3240
}
8✔
3241

3242
// ForEachNodeChannelTx iterates through all channels of the given node,
3243
// executing the passed callback with an edge info structure and the policies
3244
// of each end of the channel. The first edge policy is the outgoing edge *to*
3245
// the connecting node, while the second is the incoming edge *from* the
3246
// connecting node. If the callback returns an error, then the iteration is
3247
// halted with the error propagated back up to the caller.
3248
//
3249
// Unknown policies are passed into the callback as nil values.
3250
//
3251
// If the caller wishes to re-use an existing boltdb transaction, then it
3252
// should be passed as the first argument.  Otherwise, the first argument should
3253
// be nil and a fresh transaction will be created to execute the graph
3254
// traversal.
3255
func (c *ChannelGraph) ForEachNodeChannelTx(tx kvdb.RTx,
3256
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3257
                *models.ChannelEdgePolicy,
3258
                *models.ChannelEdgePolicy) error) error {
1,000✔
3259

1,000✔
3260
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,000✔
3261
}
1,000✔
3262

3263
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3264
// the target node in the channel. This is useful when one knows the pubkey of
3265
// one of the nodes, and wishes to obtain the full LightningNode for the other
3266
// end of the channel.
3267
func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx,
3268
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (
3269
        *models.LightningNode, error) {
2✔
3270

2✔
3271
        // Ensure that the node passed in is actually a member of the channel.
2✔
3272
        var targetNodeBytes [33]byte
2✔
3273
        switch {
2✔
3274
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
2✔
3275
                targetNodeBytes = channel.NodeKey2Bytes
2✔
3276
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
2✔
3277
                targetNodeBytes = channel.NodeKey1Bytes
2✔
3278
        default:
×
3279
                return nil, fmt.Errorf("node not participating in this channel")
×
3280
        }
3281

3282
        var targetNode *models.LightningNode
2✔
3283
        fetchNodeFunc := func(tx kvdb.RTx) error {
4✔
3284
                // First grab the nodes bucket which stores the mapping from
2✔
3285
                // pubKey to node information.
2✔
3286
                nodes := tx.ReadBucket(nodeBucket)
2✔
3287
                if nodes == nil {
2✔
3288
                        return ErrGraphNotFound
×
3289
                }
×
3290

3291
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
2✔
3292
                if err != nil {
2✔
3293
                        return err
×
3294
                }
×
3295

3296
                targetNode = &node
2✔
3297

2✔
3298
                return nil
2✔
3299
        }
3300

3301
        // If the transaction is nil, then we'll need to create a new one,
3302
        // otherwise we can use the existing db transaction.
3303
        var err error
2✔
3304
        if tx == nil {
2✔
3305
                err = kvdb.View(c.db, fetchNodeFunc, func() {
×
3306
                        targetNode = nil
×
3307
                })
×
3308
        } else {
2✔
3309
                err = fetchNodeFunc(tx)
2✔
3310
        }
2✔
3311

3312
        return targetNode, err
2✔
3313
}
3314

3315
// computeEdgePolicyKeys is a helper function that can be used to compute the
3316
// keys used to index the channel edge policy info for the two nodes of the
3317
// edge. The keys for node 1 and node 2 are returned respectively.
3318
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
24✔
3319
        var (
24✔
3320
                node1Key [33 + 8]byte
24✔
3321
                node2Key [33 + 8]byte
24✔
3322
        )
24✔
3323

24✔
3324
        copy(node1Key[:], info.NodeKey1Bytes[:])
24✔
3325
        copy(node2Key[:], info.NodeKey2Bytes[:])
24✔
3326

24✔
3327
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
24✔
3328
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
24✔
3329

24✔
3330
        return node1Key[:], node2Key[:]
24✔
3331
}
24✔
3332

3333
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3334
// the channel identified by the funding outpoint. If the channel can't be
3335
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3336
// information for the channel itself is returned as well as two structs that
3337
// contain the routing policies for the channel in either direction.
3338
func (c *ChannelGraph) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3339
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3340
        *models.ChannelEdgePolicy, error) {
13✔
3341

13✔
3342
        var (
13✔
3343
                edgeInfo *models.ChannelEdgeInfo
13✔
3344
                policy1  *models.ChannelEdgePolicy
13✔
3345
                policy2  *models.ChannelEdgePolicy
13✔
3346
        )
13✔
3347

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

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

3368
                // If the channel's outpoint doesn't exist within the outpoint
3369
                // index, then the edge does not exist.
3370
                chanIndex := edges.NestedReadBucket(channelPointBucket)
13✔
3371
                if chanIndex == nil {
13✔
3372
                        return ErrGraphNoEdgesFound
×
3373
                }
×
3374
                var b bytes.Buffer
13✔
3375
                if err := WriteOutpoint(&b, op); err != nil {
13✔
3376
                        return err
×
3377
                }
×
3378
                chanID := chanIndex.Get(b.Bytes())
13✔
3379
                if chanID == nil {
25✔
3380
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
12✔
3381
                }
12✔
3382

3383
                // If the channel is found to exists, then we'll first retrieve
3384
                // the general information for the channel.
3385
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
3386
                if err != nil {
3✔
3387
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3388
                }
×
3389
                edgeInfo = &edge
3✔
3390

3✔
3391
                // Once we have the information about the channels' parameters,
3✔
3392
                // we'll fetch the routing policies for each for the directed
3✔
3393
                // edges.
3✔
3394
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
3395
                if err != nil {
3✔
3396
                        return fmt.Errorf("failed to find policy: %w", err)
×
3397
                }
×
3398

3399
                policy1 = e1
3✔
3400
                policy2 = e2
3✔
3401
                return nil
3✔
3402
        }, func() {
13✔
3403
                edgeInfo = nil
13✔
3404
                policy1 = nil
13✔
3405
                policy2 = nil
13✔
3406
        })
13✔
3407
        if err != nil {
25✔
3408
                return nil, nil, nil, err
12✔
3409
        }
12✔
3410

3411
        return edgeInfo, policy1, policy2, nil
3✔
3412
}
3413

3414
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3415
// channel identified by the channel ID. If the channel can't be found, then
3416
// ErrEdgeNotFound is returned. A struct which houses the general information
3417
// for the channel itself is returned as well as two structs that contain the
3418
// routing policies for the channel in either direction.
3419
//
3420
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3421
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3422
// the ChannelEdgeInfo will only include the public keys of each node.
3423
func (c *ChannelGraph) FetchChannelEdgesByID(chanID uint64) (
3424
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3425
        *models.ChannelEdgePolicy, error) {
27✔
3426

27✔
3427
        var (
27✔
3428
                edgeInfo  *models.ChannelEdgeInfo
27✔
3429
                policy1   *models.ChannelEdgePolicy
27✔
3430
                policy2   *models.ChannelEdgePolicy
27✔
3431
                channelID [8]byte
27✔
3432
        )
27✔
3433

27✔
3434
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
54✔
3435
                // First, grab the node bucket. This will be used to populate
27✔
3436
                // the Node pointers in each edge read from disk.
27✔
3437
                nodes := tx.ReadBucket(nodeBucket)
27✔
3438
                if nodes == nil {
27✔
3439
                        return ErrGraphNotFound
×
3440
                }
×
3441

3442
                // Next, grab the edge bucket which stores the edges, and also
3443
                // the index itself so we can group the directed edges together
3444
                // logically.
3445
                edges := tx.ReadBucket(edgeBucket)
27✔
3446
                if edges == nil {
27✔
3447
                        return ErrGraphNoEdgesFound
×
3448
                }
×
3449
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
27✔
3450
                if edgeIndex == nil {
27✔
3451
                        return ErrGraphNoEdgesFound
×
3452
                }
×
3453

3454
                byteOrder.PutUint64(channelID[:], chanID)
27✔
3455

27✔
3456
                // Now, attempt to fetch edge.
27✔
3457
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
27✔
3458

27✔
3459
                // If it doesn't exist, we'll quickly check our zombie index to
27✔
3460
                // see if we've previously marked it as so.
27✔
3461
                if errors.Is(err, ErrEdgeNotFound) {
30✔
3462
                        // If the zombie index doesn't exist, or the edge is not
3✔
3463
                        // marked as a zombie within it, then we'll return the
3✔
3464
                        // original ErrEdgeNotFound error.
3✔
3465
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
3✔
3466
                        if zombieIndex == nil {
3✔
3467
                                return ErrEdgeNotFound
×
3468
                        }
×
3469

3470
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3471
                                zombieIndex, chanID,
3✔
3472
                        )
3✔
3473
                        if !isZombie {
5✔
3474
                                return ErrEdgeNotFound
2✔
3475
                        }
2✔
3476

3477
                        // Otherwise, the edge is marked as a zombie, so we'll
3478
                        // populate the edge info with the public keys of each
3479
                        // party as this is the only information we have about
3480
                        // it and return an error signaling so.
3481
                        edgeInfo = &models.ChannelEdgeInfo{
3✔
3482
                                NodeKey1Bytes: pubKey1,
3✔
3483
                                NodeKey2Bytes: pubKey2,
3✔
3484
                        }
3✔
3485
                        return ErrZombieEdge
3✔
3486
                }
3487

3488
                // Otherwise, we'll just return the error if any.
3489
                if err != nil {
26✔
3490
                        return err
×
3491
                }
×
3492

3493
                edgeInfo = &edge
26✔
3494

26✔
3495
                // Then we'll attempt to fetch the accompanying policies of this
26✔
3496
                // edge.
26✔
3497
                e1, e2, err := fetchChanEdgePolicies(
26✔
3498
                        edgeIndex, edges, channelID[:],
26✔
3499
                )
26✔
3500
                if err != nil {
26✔
3501
                        return err
×
3502
                }
×
3503

3504
                policy1 = e1
26✔
3505
                policy2 = e2
26✔
3506
                return nil
26✔
3507
        }, func() {
27✔
3508
                edgeInfo = nil
27✔
3509
                policy1 = nil
27✔
3510
                policy2 = nil
27✔
3511
        })
27✔
3512
        if err == ErrZombieEdge {
30✔
3513
                return edgeInfo, nil, nil, err
3✔
3514
        }
3✔
3515
        if err != nil {
28✔
3516
                return nil, nil, nil, err
2✔
3517
        }
2✔
3518

3519
        return edgeInfo, policy1, policy2, nil
26✔
3520
}
3521

3522
// IsPublicNode is a helper method that determines whether the node with the
3523
// given public key is seen as a public node in the graph from the graph's
3524
// source node's point of view.
3525
func (c *ChannelGraph) IsPublicNode(pubKey [33]byte) (bool, error) {
15✔
3526
        var nodeIsPublic bool
15✔
3527
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
30✔
3528
                nodes := tx.ReadBucket(nodeBucket)
15✔
3529
                if nodes == nil {
15✔
3530
                        return ErrGraphNodesNotFound
×
3531
                }
×
3532
                ourPubKey := nodes.Get(sourceKey)
15✔
3533
                if ourPubKey == nil {
15✔
3534
                        return ErrSourceNodeNotSet
×
3535
                }
×
3536
                node, err := fetchLightningNode(nodes, pubKey[:])
15✔
3537
                if err != nil {
15✔
3538
                        return err
×
3539
                }
×
3540

3541
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
15✔
3542
                return err
15✔
3543
        }, func() {
15✔
3544
                nodeIsPublic = false
15✔
3545
        })
15✔
3546
        if err != nil {
15✔
3547
                return false, err
×
3548
        }
×
3549

3550
        return nodeIsPublic, nil
15✔
3551
}
3552

3553
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3554
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
48✔
3555
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
48✔
3556
        if err != nil {
48✔
3557
                return nil, err
×
3558
        }
×
3559

3560
        // With the witness script generated, we'll now turn it into a p2wsh
3561
        // script:
3562
        //  * OP_0 <sha256(script)>
3563
        bldr := txscript.NewScriptBuilder(
48✔
3564
                txscript.WithScriptAllocSize(input.P2WSHSize),
48✔
3565
        )
48✔
3566
        bldr.AddOp(txscript.OP_0)
48✔
3567
        scriptHash := sha256.Sum256(witnessScript)
48✔
3568
        bldr.AddData(scriptHash[:])
48✔
3569

48✔
3570
        return bldr.Script()
48✔
3571
}
3572

3573
// EdgePoint couples the outpoint of a channel with the funding script that it
3574
// creates. The FilteredChainView will use this to watch for spends of this
3575
// edge point on chain. We require both of these values as depending on the
3576
// concrete implementation, either the pkScript, or the out point will be used.
3577
type EdgePoint struct {
3578
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3579
        FundingPkScript []byte
3580

3581
        // OutPoint is the outpoint of the target channel.
3582
        OutPoint wire.OutPoint
3583
}
3584

3585
// String returns a human readable version of the target EdgePoint. We return
3586
// the outpoint directly as it is enough to uniquely identify the edge point.
3587
func (e *EdgePoint) String() string {
×
3588
        return e.OutPoint.String()
×
3589
}
×
3590

3591
// ChannelView returns the verifiable edge information for each active channel
3592
// within the known channel graph. The set of UTXO's (along with their scripts)
3593
// returned are the ones that need to be watched on chain to detect channel
3594
// closes on the resident blockchain.
3595
func (c *ChannelGraph) ChannelView() ([]EdgePoint, error) {
25✔
3596
        var edgePoints []EdgePoint
25✔
3597
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
50✔
3598
                // We're going to iterate over the entire channel index, so
25✔
3599
                // we'll need to fetch the edgeBucket to get to the index as
25✔
3600
                // it's a sub-bucket.
25✔
3601
                edges := tx.ReadBucket(edgeBucket)
25✔
3602
                if edges == nil {
25✔
3603
                        return ErrGraphNoEdgesFound
×
3604
                }
×
3605
                chanIndex := edges.NestedReadBucket(channelPointBucket)
25✔
3606
                if chanIndex == nil {
25✔
3607
                        return ErrGraphNoEdgesFound
×
3608
                }
×
3609
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
25✔
3610
                if edgeIndex == nil {
25✔
3611
                        return ErrGraphNoEdgesFound
×
3612
                }
×
3613

3614
                // Once we have the proper bucket, we'll range over each key
3615
                // (which is the channel point for the channel) and decode it,
3616
                // accumulating each entry.
3617
                return chanIndex.ForEach(
25✔
3618
                        func(chanPointBytes, chanID []byte) error {
69✔
3619
                                chanPointReader := bytes.NewReader(
44✔
3620
                                        chanPointBytes,
44✔
3621
                                )
44✔
3622

44✔
3623
                                var chanPoint wire.OutPoint
44✔
3624
                                err := ReadOutpoint(chanPointReader, &chanPoint)
44✔
3625
                                if err != nil {
44✔
3626
                                        return err
×
3627
                                }
×
3628

3629
                                edgeInfo, err := fetchChanEdgeInfo(
44✔
3630
                                        edgeIndex, chanID,
44✔
3631
                                )
44✔
3632
                                if err != nil {
44✔
3633
                                        return err
×
3634
                                }
×
3635

3636
                                pkScript, err := genMultiSigP2WSH(
44✔
3637
                                        edgeInfo.BitcoinKey1Bytes[:],
44✔
3638
                                        edgeInfo.BitcoinKey2Bytes[:],
44✔
3639
                                )
44✔
3640
                                if err != nil {
44✔
3641
                                        return err
×
3642
                                }
×
3643

3644
                                edgePoints = append(edgePoints, EdgePoint{
44✔
3645
                                        FundingPkScript: pkScript,
44✔
3646
                                        OutPoint:        chanPoint,
44✔
3647
                                })
44✔
3648

44✔
3649
                                return nil
44✔
3650
                        },
3651
                )
3652
        }, func() {
25✔
3653
                edgePoints = nil
25✔
3654
        }); err != nil {
25✔
3655
                return nil, err
×
3656
        }
×
3657

3658
        return edgePoints, nil
25✔
3659
}
3660

3661
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3662
// zombie. This method is used on an ad-hoc basis, when channels need to be
3663
// marked as zombies outside the normal pruning cycle.
3664
func (c *ChannelGraph) MarkEdgeZombie(chanID uint64,
3665
        pubKey1, pubKey2 [33]byte) error {
133✔
3666

133✔
3667
        c.cacheMu.Lock()
133✔
3668
        defer c.cacheMu.Unlock()
133✔
3669

133✔
3670
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
266✔
3671
                edges := tx.ReadWriteBucket(edgeBucket)
133✔
3672
                if edges == nil {
133✔
3673
                        return ErrGraphNoEdgesFound
×
3674
                }
×
3675
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
133✔
3676
                if err != nil {
133✔
3677
                        return fmt.Errorf("unable to create zombie "+
×
3678
                                "bucket: %w", err)
×
3679
                }
×
3680

3681
                if c.graphCache != nil {
266✔
3682
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
133✔
3683
                }
133✔
3684

3685
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
133✔
3686
        })
3687
        if err != nil {
133✔
3688
                return err
×
3689
        }
×
3690

3691
        c.rejectCache.remove(chanID)
133✔
3692
        c.chanCache.remove(chanID)
133✔
3693

133✔
3694
        return nil
133✔
3695
}
3696

3697
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3698
// keys should represent the node public keys of the two parties involved in the
3699
// edge.
3700
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3701
        pubKey2 [33]byte) error {
156✔
3702

156✔
3703
        var k [8]byte
156✔
3704
        byteOrder.PutUint64(k[:], chanID)
156✔
3705

156✔
3706
        var v [66]byte
156✔
3707
        copy(v[:33], pubKey1[:])
156✔
3708
        copy(v[33:], pubKey2[:])
156✔
3709

156✔
3710
        return zombieIndex.Put(k[:], v[:])
156✔
3711
}
156✔
3712

3713
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3714
func (c *ChannelGraph) MarkEdgeLive(chanID uint64) error {
2✔
3715
        c.cacheMu.Lock()
2✔
3716
        defer c.cacheMu.Unlock()
2✔
3717

2✔
3718
        return c.markEdgeLiveUnsafe(nil, chanID)
2✔
3719
}
2✔
3720

3721
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3722
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3723
// case a new transaction will be created.
3724
//
3725
// NOTE: this method MUST only be called if the cacheMu has already been
3726
// acquired.
3727
func (c *ChannelGraph) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
24✔
3728
        dbFn := func(tx kvdb.RwTx) error {
48✔
3729
                edges := tx.ReadWriteBucket(edgeBucket)
24✔
3730
                if edges == nil {
24✔
3731
                        return ErrGraphNoEdgesFound
×
3732
                }
×
3733
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
24✔
3734
                if zombieIndex == nil {
24✔
3735
                        return nil
×
3736
                }
×
3737

3738
                var k [8]byte
24✔
3739
                byteOrder.PutUint64(k[:], chanID)
24✔
3740

24✔
3741
                if len(zombieIndex.Get(k[:])) == 0 {
25✔
3742
                        return ErrZombieEdgeNotFound
1✔
3743
                }
1✔
3744

3745
                return zombieIndex.Delete(k[:])
23✔
3746
        }
3747

3748
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3749
        // the existing transaction
3750
        var err error
24✔
3751
        if tx == nil {
26✔
3752
                err = kvdb.Update(c.db, dbFn, func() {})
4✔
3753
        } else {
22✔
3754
                err = dbFn(tx)
22✔
3755
        }
22✔
3756
        if err != nil {
25✔
3757
                return err
1✔
3758
        }
1✔
3759

3760
        c.rejectCache.remove(chanID)
23✔
3761
        c.chanCache.remove(chanID)
23✔
3762

23✔
3763
        // We need to add the channel back into our graph cache, otherwise we
23✔
3764
        // won't use it for path finding.
23✔
3765
        if c.graphCache != nil {
46✔
3766
                edgeInfos, err := c.fetchChanInfos(tx, []uint64{chanID})
23✔
3767
                if err != nil {
23✔
3768
                        return err
×
3769
                }
×
3770

3771
                for _, edgeInfo := range edgeInfos {
23✔
3772
                        c.graphCache.AddChannel(
×
3773
                                edgeInfo.Info, edgeInfo.Policy1,
×
3774
                                edgeInfo.Policy2,
×
3775
                        )
×
3776
                }
×
3777
        }
3778

3779
        return nil
23✔
3780
}
3781

3782
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3783
// zombie, then the two node public keys corresponding to this edge are also
3784
// returned.
3785
func (c *ChannelGraph) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
5✔
3786
        var (
5✔
3787
                isZombie         bool
5✔
3788
                pubKey1, pubKey2 [33]byte
5✔
3789
        )
5✔
3790

5✔
3791
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3792
                edges := tx.ReadBucket(edgeBucket)
5✔
3793
                if edges == nil {
5✔
3794
                        return ErrGraphNoEdgesFound
×
3795
                }
×
3796
                zombieIndex := edges.NestedReadBucket(zombieBucket)
5✔
3797
                if zombieIndex == nil {
5✔
3798
                        return nil
×
3799
                }
×
3800

3801
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
5✔
3802
                return nil
5✔
3803
        }, func() {
5✔
3804
                isZombie = false
5✔
3805
                pubKey1 = [33]byte{}
5✔
3806
                pubKey2 = [33]byte{}
5✔
3807
        })
5✔
3808
        if err != nil {
5✔
3809
                return false, [33]byte{}, [33]byte{}
×
3810
        }
×
3811

3812
        return isZombie, pubKey1, pubKey2
5✔
3813
}
3814

3815
// isZombieEdge returns whether an entry exists for the given channel in the
3816
// zombie index. If an entry exists, then the two node public keys corresponding
3817
// to this edge are also returned.
3818
func isZombieEdge(zombieIndex kvdb.RBucket,
3819
        chanID uint64) (bool, [33]byte, [33]byte) {
176✔
3820

176✔
3821
        var k [8]byte
176✔
3822
        byteOrder.PutUint64(k[:], chanID)
176✔
3823

176✔
3824
        v := zombieIndex.Get(k[:])
176✔
3825
        if v == nil {
272✔
3826
                return false, [33]byte{}, [33]byte{}
96✔
3827
        }
96✔
3828

3829
        var pubKey1, pubKey2 [33]byte
82✔
3830
        copy(pubKey1[:], v[:33])
82✔
3831
        copy(pubKey2[:], v[33:])
82✔
3832

82✔
3833
        return true, pubKey1, pubKey2
82✔
3834
}
3835

3836
// NumZombies returns the current number of zombie channels in the graph.
3837
func (c *ChannelGraph) NumZombies() (uint64, error) {
4✔
3838
        var numZombies uint64
4✔
3839
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3840
                edges := tx.ReadBucket(edgeBucket)
4✔
3841
                if edges == nil {
4✔
3842
                        return nil
×
3843
                }
×
3844
                zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3845
                if zombieIndex == nil {
4✔
3846
                        return nil
×
3847
                }
×
3848

3849
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3850
                        numZombies++
2✔
3851
                        return nil
2✔
3852
                })
2✔
3853
        }, func() {
4✔
3854
                numZombies = 0
4✔
3855
        })
4✔
3856
        if err != nil {
4✔
3857
                return 0, err
×
3858
        }
×
3859

3860
        return numZombies, nil
4✔
3861
}
3862

3863
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3864
// that we can ignore channel announcements that we know to be closed without
3865
// having to validate them and fetch a block.
3866
func (c *ChannelGraph) PutClosedScid(scid lnwire.ShortChannelID) error {
1✔
3867
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
2✔
3868
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
1✔
3869
                if err != nil {
1✔
3870
                        return err
×
3871
                }
×
3872

3873
                var k [8]byte
1✔
3874
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3875

1✔
3876
                return closedScids.Put(k[:], []byte{})
1✔
3877
        }, func() {})
1✔
3878
}
3879

3880
// IsClosedScid checks whether a channel identified by the passed in scid is
3881
// closed. This helps avoid having to perform expensive validation checks.
3882
// TODO: Add an LRU cache to cut down on disc reads.
3883
func (c *ChannelGraph) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
4✔
3884
        var isClosed bool
4✔
3885
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3886
                closedScids := tx.ReadBucket(closedScidBucket)
4✔
3887
                if closedScids == nil {
4✔
3888
                        return ErrClosedScidsNotFound
×
3889
                }
×
3890

3891
                var k [8]byte
4✔
3892
                byteOrder.PutUint64(k[:], scid.ToUint64())
4✔
3893

4✔
3894
                if closedScids.Get(k[:]) != nil {
5✔
3895
                        isClosed = true
1✔
3896
                        return nil
1✔
3897
                }
1✔
3898

3899
                return nil
3✔
3900
        }, func() {
4✔
3901
                isClosed = false
4✔
3902
        })
4✔
3903
        if err != nil {
4✔
3904
                return false, err
×
3905
        }
×
3906

3907
        return isClosed, nil
4✔
3908
}
3909

3910
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3911
        updateIndex kvdb.RwBucket, node *models.LightningNode) error {
989✔
3912

989✔
3913
        var (
989✔
3914
                scratch [16]byte
989✔
3915
                b       bytes.Buffer
989✔
3916
        )
989✔
3917

989✔
3918
        pub, err := node.PubKey()
989✔
3919
        if err != nil {
989✔
3920
                return err
×
3921
        }
×
3922
        nodePub := pub.SerializeCompressed()
989✔
3923

989✔
3924
        // If the node has the update time set, write it, else write 0.
989✔
3925
        updateUnix := uint64(0)
989✔
3926
        if node.LastUpdate.Unix() > 0 {
1,854✔
3927
                updateUnix = uint64(node.LastUpdate.Unix())
865✔
3928
        }
865✔
3929

3930
        byteOrder.PutUint64(scratch[:8], updateUnix)
989✔
3931
        if _, err := b.Write(scratch[:8]); err != nil {
989✔
3932
                return err
×
3933
        }
×
3934

3935
        if _, err := b.Write(nodePub); err != nil {
989✔
3936
                return err
×
3937
        }
×
3938

3939
        // If we got a node announcement for this node, we will have the rest
3940
        // of the data available. If not we don't have more data to write.
3941
        if !node.HaveNodeAnnouncement {
1,062✔
3942
                // Write HaveNodeAnnouncement=0.
73✔
3943
                byteOrder.PutUint16(scratch[:2], 0)
73✔
3944
                if _, err := b.Write(scratch[:2]); err != nil {
73✔
3945
                        return err
×
3946
                }
×
3947

3948
                return nodeBucket.Put(nodePub, b.Bytes())
73✔
3949
        }
3950

3951
        // Write HaveNodeAnnouncement=1.
3952
        byteOrder.PutUint16(scratch[:2], 1)
918✔
3953
        if _, err := b.Write(scratch[:2]); err != nil {
918✔
3954
                return err
×
3955
        }
×
3956

3957
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
918✔
3958
                return err
×
3959
        }
×
3960
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
918✔
3961
                return err
×
3962
        }
×
3963
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
918✔
3964
                return err
×
3965
        }
×
3966

3967
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
918✔
3968
                return err
×
3969
        }
×
3970

3971
        if err := node.Features.Encode(&b); err != nil {
918✔
3972
                return err
×
3973
        }
×
3974

3975
        numAddresses := uint16(len(node.Addresses))
918✔
3976
        byteOrder.PutUint16(scratch[:2], numAddresses)
918✔
3977
        if _, err := b.Write(scratch[:2]); err != nil {
918✔
3978
                return err
×
3979
        }
×
3980

3981
        for _, address := range node.Addresses {
2,062✔
3982
                if err := SerializeAddr(&b, address); err != nil {
1,144✔
3983
                        return err
×
3984
                }
×
3985
        }
3986

3987
        sigLen := len(node.AuthSigBytes)
918✔
3988
        if sigLen > 80 {
918✔
3989
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
3990
                        sigLen)
×
3991
        }
×
3992

3993
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
918✔
3994
        if err != nil {
918✔
3995
                return err
×
3996
        }
×
3997

3998
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
918✔
3999
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4000
        }
×
4001
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
918✔
4002
        if err != nil {
918✔
4003
                return err
×
4004
        }
×
4005

4006
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
918✔
4007
                return err
×
4008
        }
×
4009

4010
        // With the alias bucket updated, we'll now update the index that
4011
        // tracks the time series of node updates.
4012
        var indexKey [8 + 33]byte
918✔
4013
        byteOrder.PutUint64(indexKey[:8], updateUnix)
918✔
4014
        copy(indexKey[8:], nodePub)
918✔
4015

918✔
4016
        // If there was already an old index entry for this node, then we'll
918✔
4017
        // delete the old one before we write the new entry.
918✔
4018
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
1,024✔
4019
                // Extract out the old update time to we can reconstruct the
106✔
4020
                // prior index key to delete it from the index.
106✔
4021
                oldUpdateTime := nodeBytes[:8]
106✔
4022

106✔
4023
                var oldIndexKey [8 + 33]byte
106✔
4024
                copy(oldIndexKey[:8], oldUpdateTime)
106✔
4025
                copy(oldIndexKey[8:], nodePub)
106✔
4026

106✔
4027
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
106✔
4028
                        return err
×
4029
                }
×
4030
        }
4031

4032
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
918✔
4033
                return err
×
4034
        }
×
4035

4036
        return nodeBucket.Put(nodePub, b.Bytes())
918✔
4037
}
4038

4039
func fetchLightningNode(nodeBucket kvdb.RBucket,
4040
        nodePub []byte) (models.LightningNode, error) {
3,601✔
4041

3,601✔
4042
        nodeBytes := nodeBucket.Get(nodePub)
3,601✔
4043
        if nodeBytes == nil {
3,673✔
4044
                return models.LightningNode{}, ErrGraphNodeNotFound
72✔
4045
        }
72✔
4046

4047
        nodeReader := bytes.NewReader(nodeBytes)
3,531✔
4048
        return deserializeLightningNode(nodeReader)
3,531✔
4049
}
4050

4051
func deserializeLightningNodeCacheable(r io.Reader) (*graphCacheNode, error) {
122✔
4052
        // Always populate a feature vector, even if we don't have a node
122✔
4053
        // announcement and short circuit below.
122✔
4054
        node := newGraphCacheNode(
122✔
4055
                route.Vertex{},
122✔
4056
                lnwire.EmptyFeatureVector(),
122✔
4057
        )
122✔
4058

122✔
4059
        var nodeScratch [8]byte
122✔
4060

122✔
4061
        // Skip ahead:
122✔
4062
        // - LastUpdate (8 bytes)
122✔
4063
        if _, err := r.Read(nodeScratch[:]); err != nil {
122✔
4064
                return nil, err
×
4065
        }
×
4066

4067
        if _, err := io.ReadFull(r, node.pubKeyBytes[:]); err != nil {
122✔
4068
                return nil, err
×
4069
        }
×
4070

4071
        // Read the node announcement flag.
4072
        if _, err := r.Read(nodeScratch[:2]); err != nil {
122✔
4073
                return nil, err
×
4074
        }
×
4075
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
122✔
4076

122✔
4077
        // The rest of the data is optional, and will only be there if we got a
122✔
4078
        // node announcement for this node.
122✔
4079
        if hasNodeAnn == 0 {
124✔
4080
                return node, nil
2✔
4081
        }
2✔
4082

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

4096
        if _, err := wire.ReadVarString(r, 0); err != nil {
122✔
4097
                return nil, err
×
4098
        }
×
4099

4100
        if err := node.features.Decode(r); err != nil {
122✔
4101
                return nil, err
×
4102
        }
×
4103

4104
        return node, nil
122✔
4105
}
4106

4107
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,489✔
4108
        var (
8,489✔
4109
                node    models.LightningNode
8,489✔
4110
                scratch [8]byte
8,489✔
4111
                err     error
8,489✔
4112
        )
8,489✔
4113

8,489✔
4114
        // Always populate a feature vector, even if we don't have a node
8,489✔
4115
        // announcement and short circuit below.
8,489✔
4116
        node.Features = lnwire.EmptyFeatureVector()
8,489✔
4117

8,489✔
4118
        if _, err := r.Read(scratch[:]); err != nil {
8,489✔
4119
                return models.LightningNode{}, err
×
4120
        }
×
4121

4122
        unix := int64(byteOrder.Uint64(scratch[:]))
8,489✔
4123
        node.LastUpdate = time.Unix(unix, 0)
8,489✔
4124

8,489✔
4125
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,489✔
4126
                return models.LightningNode{}, err
×
4127
        }
×
4128

4129
        if _, err := r.Read(scratch[:2]); err != nil {
8,489✔
4130
                return models.LightningNode{}, err
×
4131
        }
×
4132

4133
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,489✔
4134
        if hasNodeAnn == 1 {
16,847✔
4135
                node.HaveNodeAnnouncement = true
8,358✔
4136
        } else {
8,491✔
4137
                node.HaveNodeAnnouncement = false
133✔
4138
        }
133✔
4139

4140
        // The rest of the data is optional, and will only be there if we got a
4141
        // node announcement for this node.
4142
        if !node.HaveNodeAnnouncement {
8,622✔
4143
                return node, nil
133✔
4144
        }
133✔
4145

4146
        // We did get a node announcement for this node, so we'll have the rest
4147
        // of the data available.
4148
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,358✔
4149
                return models.LightningNode{}, err
×
4150
        }
×
4151
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,358✔
4152
                return models.LightningNode{}, err
×
4153
        }
×
4154
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,358✔
4155
                return models.LightningNode{}, err
×
4156
        }
×
4157

4158
        node.Alias, err = wire.ReadVarString(r, 0)
8,358✔
4159
        if err != nil {
8,358✔
4160
                return models.LightningNode{}, err
×
4161
        }
×
4162

4163
        err = node.Features.Decode(r)
8,358✔
4164
        if err != nil {
8,358✔
4165
                return models.LightningNode{}, err
×
4166
        }
×
4167

4168
        if _, err := r.Read(scratch[:2]); err != nil {
8,358✔
4169
                return models.LightningNode{}, err
×
4170
        }
×
4171
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,358✔
4172

8,358✔
4173
        var addresses []net.Addr
8,358✔
4174
        for i := 0; i < numAddresses; i++ {
18,939✔
4175
                address, err := DeserializeAddr(r)
10,581✔
4176
                if err != nil {
10,581✔
4177
                        return models.LightningNode{}, err
×
4178
                }
×
4179
                addresses = append(addresses, address)
10,581✔
4180
        }
4181
        node.Addresses = addresses
8,358✔
4182

8,358✔
4183
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,358✔
4184
        if err != nil {
8,358✔
4185
                return models.LightningNode{}, err
×
4186
        }
×
4187

4188
        // We'll try and see if there are any opaque bytes left, if not, then
4189
        // we'll ignore the EOF error and return the node as is.
4190
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
8,358✔
4191
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,358✔
4192
        )
8,358✔
4193
        switch {
8,358✔
4194
        case err == io.ErrUnexpectedEOF:
×
4195
        case err == io.EOF:
×
4196
        case err != nil:
×
4197
                return models.LightningNode{}, err
×
4198
        }
4199

4200
        return node, nil
8,358✔
4201
}
4202

4203
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4204
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,474✔
4205

1,474✔
4206
        var b bytes.Buffer
1,474✔
4207

1,474✔
4208
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,474✔
4209
                return err
×
4210
        }
×
4211
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,474✔
4212
                return err
×
4213
        }
×
4214
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,474✔
4215
                return err
×
4216
        }
×
4217
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,474✔
4218
                return err
×
4219
        }
×
4220

4221
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,474✔
4222
                return err
×
4223
        }
×
4224

4225
        authProof := edgeInfo.AuthProof
1,474✔
4226
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,474✔
4227
        if authProof != nil {
2,865✔
4228
                nodeSig1 = authProof.NodeSig1Bytes
1,391✔
4229
                nodeSig2 = authProof.NodeSig2Bytes
1,391✔
4230
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,391✔
4231
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,391✔
4232
        }
1,391✔
4233

4234
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,474✔
4235
                return err
×
4236
        }
×
4237
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,474✔
4238
                return err
×
4239
        }
×
4240
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,474✔
4241
                return err
×
4242
        }
×
4243
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,474✔
4244
                return err
×
4245
        }
×
4246

4247
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,474✔
4248
                return err
×
4249
        }
×
4250
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
1,474✔
4251
        if err != nil {
1,474✔
4252
                return err
×
4253
        }
×
4254
        if _, err := b.Write(chanID[:]); err != nil {
1,474✔
4255
                return err
×
4256
        }
×
4257
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,474✔
4258
                return err
×
4259
        }
×
4260

4261
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,474✔
4262
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4263
        }
×
4264
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,474✔
4265
        if err != nil {
1,474✔
4266
                return err
×
4267
        }
×
4268

4269
        return edgeIndex.Put(chanID[:], b.Bytes())
1,474✔
4270
}
4271

4272
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4273
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,182✔
4274

4,182✔
4275
        edgeInfoBytes := edgeIndex.Get(chanID)
4,182✔
4276
        if edgeInfoBytes == nil {
4,271✔
4277
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
89✔
4278
        }
89✔
4279

4280
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,095✔
4281
        return deserializeChanEdgeInfo(edgeInfoReader)
4,095✔
4282
}
4283

4284
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,720✔
4285
        var (
4,720✔
4286
                err      error
4,720✔
4287
                edgeInfo models.ChannelEdgeInfo
4,720✔
4288
        )
4,720✔
4289

4,720✔
4290
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,720✔
4291
                return models.ChannelEdgeInfo{}, err
×
4292
        }
×
4293
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,720✔
4294
                return models.ChannelEdgeInfo{}, err
×
4295
        }
×
4296
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,720✔
4297
                return models.ChannelEdgeInfo{}, err
×
4298
        }
×
4299
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,720✔
4300
                return models.ChannelEdgeInfo{}, err
×
4301
        }
×
4302

4303
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,720✔
4304
        if err != nil {
4,720✔
4305
                return models.ChannelEdgeInfo{}, err
×
4306
        }
×
4307

4308
        proof := &models.ChannelAuthProof{}
4,720✔
4309

4,720✔
4310
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,720✔
4311
        if err != nil {
4,720✔
4312
                return models.ChannelEdgeInfo{}, err
×
4313
        }
×
4314
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,720✔
4315
        if err != nil {
4,720✔
4316
                return models.ChannelEdgeInfo{}, err
×
4317
        }
×
4318
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,720✔
4319
        if err != nil {
4,720✔
4320
                return models.ChannelEdgeInfo{}, err
×
4321
        }
×
4322
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,720✔
4323
        if err != nil {
4,720✔
4324
                return models.ChannelEdgeInfo{}, err
×
4325
        }
×
4326

4327
        if !proof.IsEmpty() {
6,487✔
4328
                edgeInfo.AuthProof = proof
1,767✔
4329
        }
1,767✔
4330

4331
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,720✔
4332
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,720✔
4333
                return models.ChannelEdgeInfo{}, err
×
4334
        }
×
4335
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,720✔
4336
                return models.ChannelEdgeInfo{}, err
×
4337
        }
×
4338
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,720✔
4339
                return models.ChannelEdgeInfo{}, err
×
4340
        }
×
4341

4342
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,720✔
4343
                return models.ChannelEdgeInfo{}, err
×
4344
        }
×
4345

4346
        // We'll try and see if there are any opaque bytes left, if not, then
4347
        // we'll ignore the EOF error and return the edge as is.
4348
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
4,720✔
4349
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
4,720✔
4350
        )
4,720✔
4351
        switch {
4,720✔
4352
        case err == io.ErrUnexpectedEOF:
×
4353
        case err == io.EOF:
×
4354
        case err != nil:
×
4355
                return models.ChannelEdgeInfo{}, err
×
4356
        }
4357

4358
        return edgeInfo, nil
4,720✔
4359
}
4360

4361
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4362
        from, to []byte) error {
2,662✔
4363

2,662✔
4364
        var edgeKey [33 + 8]byte
2,662✔
4365
        copy(edgeKey[:], from)
2,662✔
4366
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,662✔
4367

2,662✔
4368
        var b bytes.Buffer
2,662✔
4369
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,662✔
4370
                return err
×
4371
        }
×
4372

4373
        // Before we write out the new edge, we'll create a new entry in the
4374
        // update index in order to keep it fresh.
4375
        updateUnix := uint64(edge.LastUpdate.Unix())
2,662✔
4376
        var indexKey [8 + 8]byte
2,662✔
4377
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,662✔
4378
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,662✔
4379

2,662✔
4380
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,662✔
4381
        if err != nil {
2,662✔
4382
                return err
×
4383
        }
×
4384

4385
        // If there was already an entry for this edge, then we'll need to
4386
        // delete the old one to ensure we don't leave around any after-images.
4387
        // An unknown policy value does not have a update time recorded, so
4388
        // it also does not need to be removed.
4389
        if edgeBytes := edges.Get(edgeKey[:]); edgeBytes != nil &&
2,662✔
4390
                !bytes.Equal(edgeBytes[:], unknownPolicy) {
2,688✔
4391

26✔
4392
                // In order to delete the old entry, we'll need to obtain the
26✔
4393
                // *prior* update time in order to delete it. To do this, we'll
26✔
4394
                // need to deserialize the existing policy within the database
26✔
4395
                // (now outdated by the new one), and delete its corresponding
26✔
4396
                // entry within the update index. We'll ignore any
26✔
4397
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
26✔
4398
                // the channel ID and update time to delete the entry.
26✔
4399
                // TODO(halseth): get rid of these invalid policies in a
26✔
4400
                // migration.
26✔
4401
                oldEdgePolicy, err := deserializeChanEdgePolicy(
26✔
4402
                        bytes.NewReader(edgeBytes),
26✔
4403
                )
26✔
4404
                if err != nil && err != ErrEdgePolicyOptionalFieldNotFound {
26✔
4405
                        return err
×
4406
                }
×
4407

4408
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
26✔
4409

26✔
4410
                var oldIndexKey [8 + 8]byte
26✔
4411
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
26✔
4412
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
26✔
4413

26✔
4414
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
26✔
4415
                        return err
×
4416
                }
×
4417
        }
4418

4419
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,662✔
4420
                return err
×
4421
        }
×
4422

4423
        err = updateEdgePolicyDisabledIndex(
2,662✔
4424
                edges, edge.ChannelID,
2,662✔
4425
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,662✔
4426
                edge.IsDisabled(),
2,662✔
4427
        )
2,662✔
4428
        if err != nil {
2,662✔
4429
                return err
×
4430
        }
×
4431

4432
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,662✔
4433
}
4434

4435
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4436
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4437
// one.
4438
// The direction represents the direction of the edge and disabled is used for
4439
// deciding whether to remove or add an entry to the bucket.
4440
// In general a channel is disabled if two entries for the same chanID exist
4441
// in this bucket.
4442
// Maintaining the bucket this way allows a fast retrieval of disabled
4443
// channels, for example when prune is needed.
4444
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4445
        direction bool, disabled bool) error {
2,922✔
4446

2,922✔
4447
        var disabledEdgeKey [8 + 1]byte
2,922✔
4448
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,922✔
4449
        if direction {
4,382✔
4450
                disabledEdgeKey[8] = 1
1,460✔
4451
        }
1,460✔
4452

4453
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,922✔
4454
                disabledEdgePolicyBucket,
2,922✔
4455
        )
2,922✔
4456
        if err != nil {
2,922✔
4457
                return err
×
4458
        }
×
4459

4460
        if disabled {
2,950✔
4461
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
28✔
4462
        }
28✔
4463

4464
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,896✔
4465
}
4466

4467
// putChanEdgePolicyUnknown marks the edge policy as unknown
4468
// in the edges bucket.
4469
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4470
        from []byte) error {
2,944✔
4471

2,944✔
4472
        var edgeKey [33 + 8]byte
2,944✔
4473
        copy(edgeKey[:], from)
2,944✔
4474
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,944✔
4475

2,944✔
4476
        if edges.Get(edgeKey[:]) != nil {
2,944✔
4477
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4478
                        " when there is already a policy present", channelID)
×
4479
        }
×
4480

4481
        return edges.Put(edgeKey[:], unknownPolicy)
2,944✔
4482
}
4483

4484
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4485
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,162✔
4486

8,162✔
4487
        var edgeKey [33 + 8]byte
8,162✔
4488
        copy(edgeKey[:], nodePub)
8,162✔
4489
        copy(edgeKey[33:], chanID[:])
8,162✔
4490

8,162✔
4491
        edgeBytes := edges.Get(edgeKey[:])
8,162✔
4492
        if edgeBytes == nil {
8,162✔
4493
                return nil, ErrEdgeNotFound
×
4494
        }
×
4495

4496
        // No need to deserialize unknown policy.
4497
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,521✔
4498
                return nil, nil
359✔
4499
        }
359✔
4500

4501
        edgeReader := bytes.NewReader(edgeBytes)
7,805✔
4502

7,805✔
4503
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,805✔
4504
        switch {
7,805✔
4505
        // If the db policy was missing an expected optional field, we return
4506
        // nil as if the policy was unknown.
4507
        case err == ErrEdgePolicyOptionalFieldNotFound:
1✔
4508
                return nil, nil
1✔
4509

4510
        case err != nil:
×
4511
                return nil, err
×
4512
        }
4513

4514
        return ep, nil
7,804✔
4515
}
4516

4517
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4518
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4519
        error) {
233✔
4520

233✔
4521
        edgeInfo := edgeIndex.Get(chanID)
233✔
4522
        if edgeInfo == nil {
233✔
4523
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4524
                        chanID)
×
4525
        }
×
4526

4527
        // The first node is contained within the first half of the edge
4528
        // information. We only propagate the error here and below if it's
4529
        // something other than edge non-existence.
4530
        node1Pub := edgeInfo[:33]
233✔
4531
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
233✔
4532
        if err != nil {
233✔
4533
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4534
                        node1Pub)
×
4535
        }
×
4536

4537
        // Similarly, the second node is contained within the latter
4538
        // half of the edge information.
4539
        node2Pub := edgeInfo[33:66]
233✔
4540
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
233✔
4541
        if err != nil {
233✔
4542
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4543
                        node2Pub)
×
4544
        }
×
4545

4546
        return edge1, edge2, nil
233✔
4547
}
4548

4549
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4550
        to []byte) error {
2,664✔
4551

2,664✔
4552
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,664✔
4553
        if err != nil {
2,664✔
4554
                return err
×
4555
        }
×
4556

4557
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,664✔
4558
                return err
×
4559
        }
×
4560

4561
        var scratch [8]byte
2,664✔
4562
        updateUnix := uint64(edge.LastUpdate.Unix())
2,664✔
4563
        byteOrder.PutUint64(scratch[:], updateUnix)
2,664✔
4564
        if _, err := w.Write(scratch[:]); err != nil {
2,664✔
4565
                return err
×
4566
        }
×
4567

4568
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,664✔
4569
                return err
×
4570
        }
×
4571
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,664✔
4572
                return err
×
4573
        }
×
4574
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,664✔
4575
                return err
×
4576
        }
×
4577
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,664✔
4578
                return err
×
4579
        }
×
4580
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
2,664✔
4581
        if err != nil {
2,664✔
4582
                return err
×
4583
        }
×
4584
        err = binary.Write(
2,664✔
4585
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
2,664✔
4586
        )
2,664✔
4587
        if err != nil {
2,664✔
4588
                return err
×
4589
        }
×
4590

4591
        if _, err := w.Write(to); err != nil {
2,664✔
4592
                return err
×
4593
        }
×
4594

4595
        // If the max_htlc field is present, we write it. To be compatible with
4596
        // older versions that wasn't aware of this field, we write it as part
4597
        // of the opaque data.
4598
        // TODO(halseth): clean up when moving to TLV.
4599
        var opaqueBuf bytes.Buffer
2,664✔
4600
        if edge.MessageFlags.HasMaxHtlc() {
4,944✔
4601
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,280✔
4602
                if err != nil {
2,280✔
4603
                        return err
×
4604
                }
×
4605
        }
4606

4607
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,664✔
4608
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4609
        }
×
4610
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,664✔
4611
                return err
×
4612
        }
×
4613

4614
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,664✔
4615
                return err
×
4616
        }
×
4617
        return nil
2,664✔
4618
}
4619

4620
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,830✔
4621
        // Deserialize the policy. Note that in case an optional field is not
7,830✔
4622
        // found, both an error and a populated policy object are returned.
7,830✔
4623
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,830✔
4624
        if deserializeErr != nil &&
7,830✔
4625
                deserializeErr != ErrEdgePolicyOptionalFieldNotFound {
7,830✔
4626

×
4627
                return nil, deserializeErr
×
4628
        }
×
4629

4630
        return edge, deserializeErr
7,830✔
4631
}
4632

4633
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4634
        error) {
8,837✔
4635

8,837✔
4636
        edge := &models.ChannelEdgePolicy{}
8,837✔
4637

8,837✔
4638
        var err error
8,837✔
4639
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,837✔
4640
        if err != nil {
8,837✔
4641
                return nil, err
×
4642
        }
×
4643

4644
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,837✔
4645
                return nil, err
×
4646
        }
×
4647

4648
        var scratch [8]byte
8,837✔
4649
        if _, err := r.Read(scratch[:]); err != nil {
8,837✔
4650
                return nil, err
×
4651
        }
×
4652
        unix := int64(byteOrder.Uint64(scratch[:]))
8,837✔
4653
        edge.LastUpdate = time.Unix(unix, 0)
8,837✔
4654

8,837✔
4655
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,837✔
4656
                return nil, err
×
4657
        }
×
4658
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,837✔
4659
                return nil, err
×
4660
        }
×
4661
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,837✔
4662
                return nil, err
×
4663
        }
×
4664

4665
        var n uint64
8,837✔
4666
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,837✔
4667
                return nil, err
×
4668
        }
×
4669
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,837✔
4670

8,837✔
4671
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,837✔
4672
                return nil, err
×
4673
        }
×
4674
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,837✔
4675

8,837✔
4676
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,837✔
4677
                return nil, err
×
4678
        }
×
4679
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,837✔
4680

8,837✔
4681
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,837✔
4682
                return nil, err
×
4683
        }
×
4684

4685
        // We'll try and see if there are any opaque bytes left, if not, then
4686
        // we'll ignore the EOF error and return the edge as is.
4687
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,837✔
4688
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,837✔
4689
        )
8,837✔
4690
        switch {
8,837✔
4691
        case err == io.ErrUnexpectedEOF:
×
4692
        case err == io.EOF:
3✔
4693
        case err != nil:
×
4694
                return nil, err
×
4695
        }
4696

4697
        // See if optional fields are present.
4698
        if edge.MessageFlags.HasMaxHtlc() {
17,294✔
4699
                // The max_htlc field should be at the beginning of the opaque
8,457✔
4700
                // bytes.
8,457✔
4701
                opq := edge.ExtraOpaqueData
8,457✔
4702

8,457✔
4703
                // If the max_htlc field is not present, it might be old data
8,457✔
4704
                // stored before this field was validated. We'll return the
8,457✔
4705
                // edge along with an error.
8,457✔
4706
                if len(opq) < 8 {
8,460✔
4707
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4708
                }
3✔
4709

4710
                maxHtlc := byteOrder.Uint64(opq[:8])
8,454✔
4711
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,454✔
4712

8,454✔
4713
                // Exclude the parsed field from the rest of the opaque data.
8,454✔
4714
                edge.ExtraOpaqueData = opq[8:]
8,454✔
4715
        }
4716

4717
        return edge, nil
8,834✔
4718
}
4719

4720
// MakeTestGraph creates a new instance of the ChannelGraph for testing
4721
// purposes.
4722
func MakeTestGraph(t testing.TB, modifiers ...OptionModifier) (*ChannelGraph,
4723
        error) {
39✔
4724

39✔
4725
        opts := DefaultOptions()
39✔
4726
        for _, modifier := range modifiers {
39✔
4727
                modifier(opts)
×
4728
        }
×
4729

4730
        // Next, create channelgraph for the first time.
4731
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
39✔
4732
        if err != nil {
39✔
4733
                backendCleanup()
×
4734
                return nil, err
×
4735
        }
×
4736

4737
        graph, err := NewChannelGraph(backend)
39✔
4738
        if err != nil {
39✔
4739
                backendCleanup()
×
4740
                return nil, err
×
4741
        }
×
4742

4743
        t.Cleanup(func() {
78✔
4744
                _ = backend.Close()
39✔
4745
                backendCleanup()
39✔
4746
        })
39✔
4747

4748
        return graph, nil
39✔
4749
}
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