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

lightningnetwork / lnd / 12375116696

17 Dec 2024 02:29PM UTC coverage: 58.366% (-0.2%) from 58.595%
12375116696

Pull #8777

github

ziggie1984
docs: add release-notes
Pull Request #8777: multi: make deletion of edge atomic.

132 of 177 new or added lines in 6 files covered. (74.58%)

670 existing lines in 37 files now uncovered.

133926 of 229458 relevant lines covered (58.37%)

19223.6 hits per line

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

77.26
/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 {
279✔
205
                o(opts)
104✔
206
        }
104✔
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 {
243✔
236
                                g.graphCache.AddNodeFeatures(node)
101✔
237

101✔
238
                                return nil
101✔
239
                        },
101✔
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 {
539✔
247

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

397✔
250
                        return nil
397✔
251
                })
397✔
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,722✔
278
                // Skip embedded buckets.
1,576✔
279
                if bytes.Equal(k, edgeIndexBucket) ||
1,576✔
280
                        bytes.Equal(k, edgeUpdateIndexBucket) ||
1,576✔
281
                        bytes.Equal(k, zombieBucket) ||
1,576✔
282
                        bytes.Equal(k, disabledEdgePolicyBucket) ||
1,576✔
283
                        bytes.Equal(k, channelPointBucket) {
2,162✔
284

586✔
285
                        return nil
586✔
286
                }
586✔
287

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

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

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

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

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

991✔
319
                return nil
991✔
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 {
872✔
362
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
697✔
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) {
134✔
409
        if c.graphCache != nil {
214✔
410
                return nil, nil
80✔
411
        }
80✔
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) {
2✔
423

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

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

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

439
        return true, node.Addresses, nil
2✔
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 {
642✔
476
                                var chanID [8]byte
496✔
477
                                copy(chanID[:], k)
496✔
478

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

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

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

496✔
497
                                return cb(&info, policy1, policy2)
496✔
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 {
704✔
511

704✔
512
        if c.graphCache != nil {
1,166✔
513
                return c.graphCache.ForEachChannel(node, cb)
462✔
514
        }
462✔
515

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

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

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

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

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

496✔
555
                if node == e.NodeKey2Bytes {
745✔
556
                        directedChannel.OtherNode = e.NodeKey1Bytes
249✔
557
                }
249✔
558

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

1,140✔
569
        if c.graphCache != nil {
1,594✔
570
                return c.graphCache.GetFeatures(node), nil
454✔
571
        }
454✔
572

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

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

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

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

754
        return kvdb.View(c.db, traversal, func() {})
260✔
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 {
548✔
773
                        // If this is the source key, then we skip this
405✔
774
                        // iteration as the value for this key is a pubKey
405✔
775
                        // rather than raw node information.
405✔
776
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
690✔
777
                                return nil
285✔
778
                        }
285✔
779

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

788
                        // Execute the callback, the transaction will abort if
789
                        // this returns an error.
790
                        return cb(tx, cacheableNode)
121✔
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) {
233✔
802
        var source *models.LightningNode
233✔
803
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
466✔
804
                // First grab the nodes bucket which stores the mapping from
233✔
805
                // pubKey to node information.
233✔
806
                nodes := tx.ReadBucket(nodeBucket)
233✔
807
                if nodes == nil {
233✔
808
                        return ErrGraphNotFound
×
809
                }
×
810

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

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

825
        return source, nil
232✔
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) {
498✔
834

498✔
835
        selfPub := nodes.Get(sourceKey)
498✔
836
        if selfPub == nil {
499✔
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)
497✔
843
        if err != nil {
497✔
844
                return nil, err
×
845
        }
×
846

847
        return &node, nil
497✔
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 {
119✔
854
        nodePubBytes := node.PubKeyBytes[:]
119✔
855

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1074
                f(r)
1✔
1075
        }
1076

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

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

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

1112
        if c.graphCache != nil {
2,774✔
1113
                c.graphCache.AddChannel(edge, nil, nil)
1,292✔
1114
        }
1,292✔
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,482✔
1121
        switch {
1,482✔
1122
        case node1Err == ErrGraphNodeNotFound:
19✔
1123
                node1Shell := models.LightningNode{
19✔
1124
                        PubKeyBytes:          edge.NodeKey1Bytes,
19✔
1125
                        HaveNodeAnnouncement: false,
19✔
1126
                }
19✔
1127
                err := addLightningNode(tx, &node1Shell)
19✔
1128
                if err != nil {
19✔
1129
                        return fmt.Errorf("unable to create shell node "+
×
1130
                                "for: %x", edge.NodeKey1Bytes)
×
1131
                }
×
1132
        case node1Err != nil:
×
1133
                return err
×
1134
        }
1135

1136
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
1,482✔
1137
        switch {
1,482✔
1138
        case node2Err == ErrGraphNodeNotFound:
56✔
1139
                node2Shell := models.LightningNode{
56✔
1140
                        PubKeyBytes:          edge.NodeKey2Bytes,
56✔
1141
                        HaveNodeAnnouncement: false,
56✔
1142
                }
56✔
1143
                err := addLightningNode(tx, &node2Shell)
56✔
1144
                if err != nil {
56✔
1145
                        return fmt.Errorf("unable to create shell node "+
×
1146
                                "for: %x", edge.NodeKey2Bytes)
×
1147
                }
×
1148
        case node2Err != nil:
×
1149
                return err
×
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,482✔
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,482✔
1162
                &edge.NodeKey1Bytes,
1,482✔
1163
                &edge.NodeKey2Bytes,
1,482✔
1164
        }
1,482✔
1165
        for _, key := range keys {
4,445✔
1166
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,963✔
1167
                if err != nil {
2,963✔
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,482✔
1175
        if err := WriteOutpoint(&b, &edge.ChannelPoint); err != nil {
1,482✔
1176
                return err
×
1177
        }
×
1178
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,482✔
1179
}
1180

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

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

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

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

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

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

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

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

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

2✔
1245
        return nil
2✔
1246
}
1247

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

216✔
1257
        var (
216✔
1258
                upd1Time time.Time
216✔
1259
                upd2Time time.Time
216✔
1260
                exists   bool
216✔
1261
                isZombie bool
216✔
1262
        )
216✔
1263

216✔
1264
        // We'll query the cache with the shared lock held to allow multiple
216✔
1265
        // readers to access values in the cache concurrently if they exist.
216✔
1266
        c.cacheMu.RLock()
216✔
1267
        if entry, ok := c.rejectCache.get(chanID); ok {
289✔
1268
                c.cacheMu.RUnlock()
73✔
1269
                upd1Time = time.Unix(entry.upd1Time, 0)
73✔
1270
                upd2Time = time.Unix(entry.upd2Time, 0)
73✔
1271
                exists, isZombie = entry.flags.unpack()
73✔
1272
                return upd1Time, upd2Time, exists, isZombie, nil
73✔
1273
        }
73✔
1274
        c.cacheMu.RUnlock()
144✔
1275

144✔
1276
        c.cacheMu.Lock()
144✔
1277
        defer c.cacheMu.Unlock()
144✔
1278

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

1289
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
272✔
1290
                edges := tx.ReadBucket(edgeBucket)
136✔
1291
                if edges == nil {
136✔
1292
                        return ErrGraphNoEdgesFound
×
1293
                }
×
1294
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
136✔
1295
                if edgeIndex == nil {
136✔
1296
                        return ErrGraphNoEdgesFound
×
1297
                }
×
1298

1299
                var channelID [8]byte
136✔
1300
                byteOrder.PutUint64(channelID[:], chanID)
136✔
1301

136✔
1302
                // If the edge doesn't exist, then we'll also check our zombie
136✔
1303
                // index.
136✔
1304
                if edgeIndex.Get(channelID[:]) == nil {
226✔
1305
                        exists = false
90✔
1306
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
90✔
1307
                        if zombieIndex != nil {
180✔
1308
                                isZombie, _, _ = isZombieEdge(
90✔
1309
                                        zombieIndex, chanID,
90✔
1310
                                )
90✔
1311
                        }
90✔
1312

1313
                        return nil
90✔
1314
                }
1315

1316
                exists = true
47✔
1317
                isZombie = false
47✔
1318

47✔
1319
                // If the channel has been found in the graph, then retrieve
47✔
1320
                // the edges itself so we can return the last updated
47✔
1321
                // timestamps.
47✔
1322
                nodes := tx.ReadBucket(nodeBucket)
47✔
1323
                if nodes == nil {
47✔
1324
                        return ErrGraphNodeNotFound
×
1325
                }
×
1326

1327
                e1, e2, err := fetchChanEdgePolicies(
47✔
1328
                        edgeIndex, edges, channelID[:],
47✔
1329
                )
47✔
1330
                if err != nil {
47✔
1331
                        return err
×
1332
                }
×
1333

1334
                // As we may have only one of the edges populated, only set the
1335
                // update time if the edge was found in the database.
1336
                if e1 != nil {
66✔
1337
                        upd1Time = e1.LastUpdate
19✔
1338
                }
19✔
1339
                if e2 != nil {
64✔
1340
                        upd2Time = e2.LastUpdate
17✔
1341
                }
17✔
1342

1343
                return nil
47✔
1344
        }, func() {}); err != nil {
136✔
1345
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1346
        }
×
1347

1348
        c.rejectCache.insert(chanID, rejectCacheEntry{
136✔
1349
                upd1Time: upd1Time.Unix(),
136✔
1350
                upd2Time: upd2Time.Unix(),
136✔
1351
                flags:    packRejectFlags(exists, isZombie),
136✔
1352
        })
136✔
1353

136✔
1354
        return upd1Time, upd2Time, exists, isZombie, nil
136✔
1355
}
1356

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

2✔
1367
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
4✔
1368
                edges := tx.ReadWriteBucket(edgeBucket)
2✔
1369
                if edge == nil {
2✔
1370
                        return ErrEdgeNotFound
×
1371
                }
×
1372

1373
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2✔
1374
                if edgeIndex == nil {
2✔
1375
                        return ErrEdgeNotFound
×
1376
                }
×
1377

1378
                if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo == nil {
2✔
1379
                        return ErrEdgeNotFound
×
1380
                }
×
1381

1382
                if c.graphCache != nil {
4✔
1383
                        c.graphCache.UpdateChannel(edge)
2✔
1384
                }
2✔
1385

1386
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
2✔
1387
        }, func() {})
2✔
1388
}
1389

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

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

242✔
1410
        c.cacheMu.Lock()
242✔
1411
        defer c.cacheMu.Unlock()
242✔
1412

242✔
1413
        var chansClosed []*models.ChannelEdgeInfo
242✔
1414

242✔
1415
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
484✔
1416
                // First grab the edges bucket which houses the information
242✔
1417
                // we'd like to delete
242✔
1418
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
242✔
1419
                if err != nil {
242✔
1420
                        return err
×
1421
                }
×
1422

1423
                // Next grab the two edge indexes which will also need to be
1424
                // updated.
1425
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
242✔
1426
                if err != nil {
242✔
1427
                        return err
×
1428
                }
×
1429
                chanIndex, err := edges.CreateBucketIfNotExists(
242✔
1430
                        channelPointBucket,
242✔
1431
                )
242✔
1432
                if err != nil {
242✔
1433
                        return err
×
1434
                }
×
1435
                nodes := tx.ReadWriteBucket(nodeBucket)
242✔
1436
                if nodes == nil {
242✔
1437
                        return ErrSourceNodeNotSet
×
1438
                }
×
1439
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
242✔
1440
                if err != nil {
242✔
1441
                        return err
×
1442
                }
×
1443

1444
                // For each of the outpoints that have been spent within the
1445
                // block, we attempt to delete them from the graph as if that
1446
                // outpoint was a channel, then it has now been closed.
1447
                for _, chanPoint := range spentOutputs {
390✔
1448
                        // TODO(roasbeef): load channel bloom filter, continue
148✔
1449
                        // if NOT if filter
148✔
1450

148✔
1451
                        var opBytes bytes.Buffer
148✔
1452
                        err := WriteOutpoint(&opBytes, chanPoint)
148✔
1453
                        if err != nil {
148✔
1454
                                return err
×
1455
                        }
×
1456

1457
                        // First attempt to see if the channel exists within
1458
                        // the database, if not, then we can exit early.
1459
                        chanID := chanIndex.Get(opBytes.Bytes())
148✔
1460
                        if chanID == nil {
276✔
1461
                                continue
128✔
1462
                        }
1463

1464
                        // However, if it does, then we'll read out the full
1465
                        // version so we can add it to the set of deleted
1466
                        // channels.
1467
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
21✔
1468
                        if err != nil {
21✔
1469
                                return err
×
1470
                        }
×
1471

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

1484
                        chansClosed = append(chansClosed, &edgeInfo)
21✔
1485
                }
1486

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

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

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

242✔
1505
                var newTip [pruneTipBytes]byte
242✔
1506
                copy(newTip[:], blockHash[:])
242✔
1507

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

1513
                // Now that the graph has been pruned, we'll also attempt to
1514
                // prune any nodes that have had a channel closed within the
1515
                // latest block.
1516
                return c.pruneGraphNodes(nodes, edgeIndex)
242✔
1517
        }, func() {
242✔
1518
                chansClosed = nil
242✔
1519
        })
242✔
1520
        if err != nil {
242✔
1521
                return nil, err
×
1522
        }
×
1523

1524
        for _, channel := range chansClosed {
263✔
1525
                c.rejectCache.remove(channel.ChannelID)
21✔
1526
                c.chanCache.remove(channel.ChannelID)
21✔
1527
        }
21✔
1528

1529
        if c.graphCache != nil {
484✔
1530
                log.Debugf("Pruned graph, cache now has %s",
242✔
1531
                        c.graphCache.Stats())
242✔
1532
        }
242✔
1533

1534
        return chansClosed, nil
242✔
1535
}
1536

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

1556
                return c.pruneGraphNodes(nodes, edgeIndex)
25✔
1557
        }, func() {})
25✔
1558
}
1559

1560
// pruneGraphNodes attempts to remove any nodes from the graph who have had a
1561
// channel closed within the current block. If the node still has existing
1562
// channels in the graph, this will act as a no-op.
1563
func (c *ChannelGraph) pruneGraphNodes(nodes kvdb.RwBucket,
1564
        edgeIndex kvdb.RwBucket) error {
266✔
1565

266✔
1566
        log.Trace("Pruning nodes from graph with no open channels")
266✔
1567

266✔
1568
        // We'll retrieve the graph's source node to ensure we don't remove it
266✔
1569
        // even if it no longer has any open channels.
266✔
1570
        sourceNode, err := c.sourceNode(nodes)
266✔
1571
        if err != nil {
266✔
1572
                return err
×
1573
        }
×
1574

1575
        // We'll use this map to keep count the number of references to a node
1576
        // in the graph. A node should only be removed once it has no more
1577
        // references in the graph.
1578
        nodeRefCounts := make(map[[33]byte]int)
266✔
1579
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,562✔
1580
                // If this is the source key, then we skip this
1,296✔
1581
                // iteration as the value for this key is a pubKey
1,296✔
1582
                // rather than raw node information.
1,296✔
1583
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
2,092✔
1584
                        return nil
796✔
1585
                }
796✔
1586

1587
                var nodePub [33]byte
501✔
1588
                copy(nodePub[:], pubKey)
501✔
1589
                nodeRefCounts[nodePub] = 0
501✔
1590

501✔
1591
                return nil
501✔
1592
        })
1593
        if err != nil {
266✔
1594
                return err
×
1595
        }
×
1596

1597
        // To ensure we never delete the source node, we'll start off by
1598
        // bumping its ref count to 1.
1599
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
266✔
1600

266✔
1601
        // Next, we'll run through the edgeIndex which maps a channel ID to the
266✔
1602
        // edge info. We'll use this scan to populate our reference count map
266✔
1603
        // above.
266✔
1604
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
458✔
1605
                // The first 66 bytes of the edge info contain the pubkeys of
192✔
1606
                // the nodes that this edge attaches. We'll extract them, and
192✔
1607
                // add them to the ref count map.
192✔
1608
                var node1, node2 [33]byte
192✔
1609
                copy(node1[:], edgeInfoBytes[:33])
192✔
1610
                copy(node2[:], edgeInfoBytes[33:])
192✔
1611

192✔
1612
                // With the nodes extracted, we'll increase the ref count of
192✔
1613
                // each of the nodes.
192✔
1614
                nodeRefCounts[node1]++
192✔
1615
                nodeRefCounts[node2]++
192✔
1616

192✔
1617
                return nil
192✔
1618
        })
192✔
1619
        if err != nil {
266✔
1620
                return err
×
1621
        }
×
1622

1623
        // Finally, we'll make a second pass over the set of nodes, and delete
1624
        // any nodes that have a ref count of zero.
1625
        var numNodesPruned int
266✔
1626
        for nodePubKey, refCount := range nodeRefCounts {
767✔
1627
                // If the ref count of the node isn't zero, then we can safely
501✔
1628
                // skip it as it still has edges to or from it within the
501✔
1629
                // graph.
501✔
1630
                if refCount != 0 {
939✔
1631
                        continue
438✔
1632
                }
1633

1634
                if c.graphCache != nil {
128✔
1635
                        c.graphCache.RemoveNode(nodePubKey)
64✔
1636
                }
64✔
1637

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

×
1645
                                log.Warnf("Unable to prune node %x from the "+
×
1646
                                        "graph: %v", nodePubKey, err)
×
1647
                                continue
×
1648
                        }
1649

1650
                        return err
×
1651
                }
1652

1653
                log.Infof("Pruned unconnected node %x from channel graph",
64✔
1654
                        nodePubKey[:])
64✔
1655

64✔
1656
                numNodesPruned++
64✔
1657
        }
1658

1659
        if numNodesPruned > 0 {
314✔
1660
                log.Infof("Pruned %v unconnected nodes from the channel graph",
48✔
1661
                        numNodesPruned)
48✔
1662
        }
48✔
1663

1664
        return nil
266✔
1665
}
1666

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

155✔
1677
        // Every channel having a ShortChannelID starting at 'height'
155✔
1678
        // will no longer be confirmed.
155✔
1679
        startShortChanID := lnwire.ShortChannelID{
155✔
1680
                BlockHeight: height,
155✔
1681
        }
155✔
1682

155✔
1683
        // Delete everything after this height from the db up until the
155✔
1684
        // SCID alias range.
155✔
1685
        endShortChanID := aliasmgr.StartingAlias
155✔
1686

155✔
1687
        // The block height will be the 3 first bytes of the channel IDs.
155✔
1688
        var chanIDStart [8]byte
155✔
1689
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
155✔
1690
        var chanIDEnd [8]byte
155✔
1691
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
155✔
1692

155✔
1693
        c.cacheMu.Lock()
155✔
1694
        defer c.cacheMu.Unlock()
155✔
1695

155✔
1696
        // Keep track of the channels that are removed from the graph.
155✔
1697
        var removedChans []*models.ChannelEdgeInfo
155✔
1698

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

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

155✔
1728
                //nolint:ll
155✔
1729
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
155✔
1730
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
249✔
1731
                        edgeInfoReader := bytes.NewReader(v)
94✔
1732
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
94✔
1733
                        if err != nil {
94✔
1734
                                return err
×
1735
                        }
×
1736

1737
                        keys = append(keys, k)
94✔
1738
                        removedChans = append(removedChans, &edgeInfo)
94✔
1739
                }
1740

1741
                for _, k := range keys {
249✔
1742
                        err = c.delChannelEdgeUnsafe(
94✔
1743
                                edges, edgeIndex, chanIndex, zombieIndex,
94✔
1744
                                k, false, false,
94✔
1745
                        )
94✔
1746
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
94✔
1747
                                return err
×
1748
                        }
×
1749
                }
1750

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

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

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

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

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

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

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

1794
        for _, channel := range removedChans {
249✔
1795
                c.rejectCache.remove(channel.ChannelID)
94✔
1796
                c.chanCache.remove(channel.ChannelID)
94✔
1797
        }
94✔
1798

1799
        return removedChans, nil
155✔
1800
}
1801

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

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

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

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

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

37✔
1836
                return nil
37✔
1837
        }, func() {})
56✔
1838
        if err != nil {
76✔
1839
                return nil, 0, err
20✔
1840
        }
20✔
1841

1842
        return &tipHash, tipHeight, nil
37✔
1843
}
1844

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

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

150✔
1860
        c.cacheMu.Lock()
150✔
1861
        defer c.cacheMu.Unlock()
150✔
1862

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

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

1897
                return nil
86✔
1898
        }, func() {})
150✔
1899
        if err != nil {
214✔
1900
                return err
64✔
1901
        }
64✔
1902

1903
        for _, chanID := range chanIDs {
112✔
1904
                c.rejectCache.remove(chanID)
26✔
1905
                c.chanCache.remove(chanID)
26✔
1906
        }
26✔
1907

1908
        return nil
86✔
1909
}
1910

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

1926
        return chanID, nil
2✔
1927
}
1928

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

1936
        edges := tx.ReadBucket(edgeBucket)
2✔
1937
        if edges == nil {
2✔
1938
                return 0, ErrGraphNoEdgesFound
×
1939
        }
×
1940
        chanIndex := edges.NestedReadBucket(channelPointBucket)
2✔
1941
        if chanIndex == nil {
2✔
1942
                return 0, ErrGraphNoEdgesFound
×
1943
        }
×
1944

1945
        chanIDBytes := chanIndex.Get(b.Bytes())
2✔
1946
        if chanIDBytes == nil {
3✔
1947
                return 0, ErrEdgeNotFound
1✔
1948
        }
1✔
1949

1950
        chanID := byteOrder.Uint64(chanIDBytes)
2✔
1951

2✔
1952
        return chanID, nil
2✔
1953
}
1954

1955
// TODO(roasbeef): allow updates to use Batch?
1956

1957
// HighestChanID returns the "highest" known channel ID in the channel graph.
1958
// This represents the "newest" channel from the PoV of the chain. This method
1959
// can be used by peers to quickly determine if they're graphs are in sync.
1960
func (c *ChannelGraph) HighestChanID() (uint64, error) {
4✔
1961
        var cid uint64
4✔
1962

4✔
1963
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
1964
                edges := tx.ReadBucket(edgeBucket)
4✔
1965
                if edges == nil {
4✔
1966
                        return ErrGraphNoEdgesFound
×
1967
                }
×
1968
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
4✔
1969
                if edgeIndex == nil {
4✔
1970
                        return ErrGraphNoEdgesFound
×
1971
                }
×
1972

1973
                // In order to find the highest chan ID, we'll fetch a cursor
1974
                // and use that to seek to the "end" of our known rage.
1975
                cidCursor := edgeIndex.ReadCursor()
4✔
1976

4✔
1977
                lastChanID, _ := cidCursor.Last()
4✔
1978

4✔
1979
                // If there's no key, then this means that we don't actually
4✔
1980
                // know of any channels, so we'll return a predicable error.
4✔
1981
                if lastChanID == nil {
6✔
1982
                        return ErrGraphNoEdgesFound
2✔
1983
                }
2✔
1984

1985
                // Otherwise, we'll de serialize the channel ID and return it
1986
                // to the caller.
1987
                cid = byteOrder.Uint64(lastChanID)
3✔
1988
                return nil
3✔
1989
        }, func() {
4✔
1990
                cid = 0
4✔
1991
        })
4✔
1992
        if err != nil && err != ErrGraphNoEdgesFound {
4✔
1993
                return 0, err
×
1994
        }
×
1995

1996
        return cid, nil
4✔
1997
}
1998

1999
// ChannelEdge represents the complete set of information for a channel edge in
2000
// the known channel graph. This struct couples the core information of the
2001
// edge as well as each of the known advertised edge policies.
2002
type ChannelEdge struct {
2003
        // Info contains all the static information describing the channel.
2004
        Info *models.ChannelEdgeInfo
2005

2006
        // Policy1 points to the "first" edge policy of the channel containing
2007
        // the dynamic information required to properly route through the edge.
2008
        Policy1 *models.ChannelEdgePolicy
2009

2010
        // Policy2 points to the "second" edge policy of the channel containing
2011
        // the dynamic information required to properly route through the edge.
2012
        Policy2 *models.ChannelEdgePolicy
2013

2014
        // Node1 is "node 1" in the channel. This is the node that would have
2015
        // produced Policy1 if it exists.
2016
        Node1 *models.LightningNode
2017

2018
        // Node2 is "node 2" in the channel. This is the node that would have
2019
        // produced Policy2 if it exists.
2020
        Node2 *models.LightningNode
2021
}
2022

2023
// ChanUpdatesInHorizon returns all the known channel edges which have at least
2024
// one edge that has an update timestamp within the specified horizon.
2025
func (c *ChannelGraph) ChanUpdatesInHorizon(startTime,
2026
        endTime time.Time) ([]ChannelEdge, error) {
149✔
2027

149✔
2028
        // To ensure we don't return duplicate ChannelEdges, we'll use an
149✔
2029
        // additional map to keep track of the edges already seen to prevent
149✔
2030
        // re-adding it.
149✔
2031
        var edgesSeen map[uint64]struct{}
149✔
2032
        var edgesToCache map[uint64]ChannelEdge
149✔
2033
        var edgesInHorizon []ChannelEdge
149✔
2034

149✔
2035
        c.cacheMu.Lock()
149✔
2036
        defer c.cacheMu.Unlock()
149✔
2037

149✔
2038
        var hits int
149✔
2039
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
298✔
2040
                edges := tx.ReadBucket(edgeBucket)
149✔
2041
                if edges == nil {
149✔
2042
                        return ErrGraphNoEdgesFound
×
2043
                }
×
2044
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
149✔
2045
                if edgeIndex == nil {
149✔
2046
                        return ErrGraphNoEdgesFound
×
2047
                }
×
2048
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
149✔
2049
                if edgeUpdateIndex == nil {
149✔
2050
                        return ErrGraphNoEdgesFound
×
2051
                }
×
2052

2053
                nodes := tx.ReadBucket(nodeBucket)
149✔
2054
                if nodes == nil {
149✔
2055
                        return ErrGraphNodesNotFound
×
2056
                }
×
2057

2058
                // We'll now obtain a cursor to perform a range query within
2059
                // the index to find all channels within the horizon.
2060
                updateCursor := edgeUpdateIndex.ReadCursor()
149✔
2061

149✔
2062
                var startTimeBytes, endTimeBytes [8 + 8]byte
149✔
2063
                byteOrder.PutUint64(
149✔
2064
                        startTimeBytes[:8], uint64(startTime.Unix()),
149✔
2065
                )
149✔
2066
                byteOrder.PutUint64(
149✔
2067
                        endTimeBytes[:8], uint64(endTime.Unix()),
149✔
2068
                )
149✔
2069

149✔
2070
                // With our start and end times constructed, we'll step through
149✔
2071
                // the index collecting the info and policy of each update of
149✔
2072
                // each channel that has a last update within the time range.
149✔
2073
                //
149✔
2074
                //nolint:ll
149✔
2075
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
149✔
2076
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
196✔
2077

47✔
2078
                        // We have a new eligible entry, so we'll slice of the
47✔
2079
                        // chan ID so we can query it in the DB.
47✔
2080
                        chanID := indexKey[8:]
47✔
2081

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

2090
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
38✔
2091
                                hits++
10✔
2092
                                edgesSeen[chanIDInt] = struct{}{}
10✔
2093
                                edgesInHorizon = append(edgesInHorizon, channel)
10✔
2094
                                continue
10✔
2095
                        }
2096

2097
                        // First, we'll fetch the static edge information.
2098
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
19✔
2099
                        if err != nil {
19✔
2100
                                chanID := byteOrder.Uint64(chanID)
×
2101
                                return fmt.Errorf("unable to fetch info for "+
×
2102
                                        "edge with chan_id=%v: %v", chanID, err)
×
2103
                        }
×
2104

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

2117
                        node1, err := fetchLightningNode(
19✔
2118
                                nodes, edgeInfo.NodeKey1Bytes[:],
19✔
2119
                        )
19✔
2120
                        if err != nil {
19✔
2121
                                return err
×
2122
                        }
×
2123

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

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

2145
                return nil
149✔
2146
        }, func() {
149✔
2147
                edgesSeen = make(map[uint64]struct{})
149✔
2148
                edgesToCache = make(map[uint64]ChannelEdge)
149✔
2149
                edgesInHorizon = nil
149✔
2150
        })
149✔
2151
        switch {
149✔
2152
        case err == ErrGraphNoEdgesFound:
×
2153
                fallthrough
×
2154
        case err == ErrGraphNodesNotFound:
×
2155
                break
×
2156

2157
        case err != nil:
×
2158
                return nil, err
×
2159
        }
2160

2161
        // Insert any edges loaded from disk into the cache.
2162
        for chanid, channel := range edgesToCache {
168✔
2163
                c.chanCache.insert(chanid, channel)
19✔
2164
        }
19✔
2165

2166
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
149✔
2167
                float64(hits)/float64(len(edgesInHorizon)), hits,
149✔
2168
                len(edgesInHorizon))
149✔
2169

149✔
2170
        return edgesInHorizon, nil
149✔
2171
}
2172

2173
// NodeUpdatesInHorizon returns all the known lightning node which have an
2174
// update timestamp within the passed range. This method can be used by two
2175
// nodes to quickly determine if they have the same set of up to date node
2176
// announcements.
2177
func (c *ChannelGraph) NodeUpdatesInHorizon(startTime,
2178
        endTime time.Time) ([]models.LightningNode, error) {
9✔
2179

9✔
2180
        var nodesInHorizon []models.LightningNode
9✔
2181

9✔
2182
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
18✔
2183
                nodes := tx.ReadBucket(nodeBucket)
9✔
2184
                if nodes == nil {
9✔
2185
                        return ErrGraphNodesNotFound
×
2186
                }
×
2187

2188
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
9✔
2189
                if nodeUpdateIndex == nil {
9✔
2190
                        return ErrGraphNodesNotFound
×
2191
                }
×
2192

2193
                // We'll now obtain a cursor to perform a range query within
2194
                // the index to find all node announcements within the horizon.
2195
                updateCursor := nodeUpdateIndex.ReadCursor()
9✔
2196

9✔
2197
                var startTimeBytes, endTimeBytes [8 + 33]byte
9✔
2198
                byteOrder.PutUint64(
9✔
2199
                        startTimeBytes[:8], uint64(startTime.Unix()),
9✔
2200
                )
9✔
2201
                byteOrder.PutUint64(
9✔
2202
                        endTimeBytes[:8], uint64(endTime.Unix()),
9✔
2203
                )
9✔
2204

9✔
2205
                // With our start and end times constructed, we'll step through
9✔
2206
                // the index collecting info for each node within the time
9✔
2207
                // range.
9✔
2208
                //
9✔
2209
                //nolint:ll
9✔
2210
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
9✔
2211
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
39✔
2212

30✔
2213
                        nodePub := indexKey[8:]
30✔
2214
                        node, err := fetchLightningNode(nodes, nodePub)
30✔
2215
                        if err != nil {
30✔
2216
                                return err
×
2217
                        }
×
2218

2219
                        nodesInHorizon = append(nodesInHorizon, node)
30✔
2220
                }
2221

2222
                return nil
9✔
2223
        }, func() {
9✔
2224
                nodesInHorizon = nil
9✔
2225
        })
9✔
2226
        switch {
9✔
2227
        case err == ErrGraphNoEdgesFound:
×
2228
                fallthrough
×
2229
        case err == ErrGraphNodesNotFound:
×
2230
                break
×
2231

2232
        case err != nil:
×
2233
                return nil, err
×
2234
        }
2235

2236
        return nodesInHorizon, nil
9✔
2237
}
2238

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

121✔
2247
        var newChanIDs []uint64
121✔
2248

121✔
2249
        c.cacheMu.Lock()
121✔
2250
        defer c.cacheMu.Unlock()
121✔
2251

121✔
2252
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
242✔
2253
                edges := tx.ReadBucket(edgeBucket)
121✔
2254
                if edges == nil {
121✔
2255
                        return ErrGraphNoEdgesFound
×
2256
                }
×
2257
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
121✔
2258
                if edgeIndex == nil {
121✔
2259
                        return ErrGraphNoEdgesFound
×
2260
                }
×
2261

2262
                // Fetch the zombie index, it may not exist if no edges have
2263
                // ever been marked as zombies. If the index has been
2264
                // initialized, we will use it later to skip known zombie edges.
2265
                zombieIndex := edges.NestedReadBucket(zombieBucket)
121✔
2266

121✔
2267
                // We'll run through the set of chanIDs and collate only the
121✔
2268
                // set of channel that are unable to be found within our db.
121✔
2269
                var cidBytes [8]byte
121✔
2270
                for _, info := range chansInfo {
231✔
2271
                        scid := info.ShortChannelID.ToUint64()
110✔
2272
                        byteOrder.PutUint64(cidBytes[:], scid)
110✔
2273

110✔
2274
                        // If the edge is already known, skip it.
110✔
2275
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
131✔
2276
                                continue
21✔
2277
                        }
2278

2279
                        // If the edge is a known zombie, skip it.
2280
                        if zombieIndex != nil {
180✔
2281
                                isZombie, _, _ := isZombieEdge(
90✔
2282
                                        zombieIndex, scid,
90✔
2283
                                )
90✔
2284

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

90✔
2305
                                switch {
90✔
2306
                                // If the edge is a known zombie and if we
2307
                                // would still consider it a zombie given the
2308
                                // latest update timestamps, then we skip this
2309
                                // channel.
2310
                                case isZombie && isStillZombie:
24✔
2311
                                        continue
24✔
2312

2313
                                // Otherwise, if we have marked it as a zombie
2314
                                // but the latest update timestamps could bring
2315
                                // it back from the dead, then we mark it alive,
2316
                                // and we let it be added to the set of IDs to
2317
                                // query our peer for.
2318
                                case isZombie && !isStillZombie:
19✔
2319
                                        err := c.markEdgeLiveUnsafe(tx, scid)
19✔
2320
                                        if err != nil {
19✔
2321
                                                return err
×
2322
                                        }
×
2323
                                }
2324
                        }
2325

2326
                        newChanIDs = append(newChanIDs, scid)
66✔
2327
                }
2328

2329
                return nil
121✔
2330
        }, func() {
121✔
2331
                newChanIDs = nil
121✔
2332
        })
121✔
2333
        switch {
121✔
2334
        // If we don't know of any edges yet, then we'll return the entire set
2335
        // of chan IDs specified.
2336
        case err == ErrGraphNoEdgesFound:
×
2337
                ogChanIDs := make([]uint64, len(chansInfo))
×
2338
                for i, info := range chansInfo {
×
2339
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2340
                }
×
2341

2342
                return ogChanIDs, nil
×
2343

2344
        case err != nil:
×
2345
                return nil, err
×
2346
        }
2347

2348
        return newChanIDs, nil
121✔
2349
}
2350

2351
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2352
// latest received channel updates for the channel.
2353
type ChannelUpdateInfo struct {
2354
        // ShortChannelID is the SCID identifier of the channel.
2355
        ShortChannelID lnwire.ShortChannelID
2356

2357
        // Node1UpdateTimestamp is the timestamp of the latest received update
2358
        // from the node 1 channel peer. This will be set to zero time if no
2359
        // update has yet been received from this node.
2360
        Node1UpdateTimestamp time.Time
2361

2362
        // Node2UpdateTimestamp is the timestamp of the latest received update
2363
        // from the node 2 channel peer. This will be set to zero time if no
2364
        // update has yet been received from this node.
2365
        Node2UpdateTimestamp time.Time
2366
}
2367

2368
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2369
// timestamps with zero seconds unix timestamp which equals
2370
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2371
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2372
        node2Timestamp time.Time) ChannelUpdateInfo {
219✔
2373

219✔
2374
        chanInfo := ChannelUpdateInfo{
219✔
2375
                ShortChannelID:       scid,
219✔
2376
                Node1UpdateTimestamp: node1Timestamp,
219✔
2377
                Node2UpdateTimestamp: node2Timestamp,
219✔
2378
        }
219✔
2379

219✔
2380
        if node1Timestamp.IsZero() {
428✔
2381
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
209✔
2382
        }
209✔
2383

2384
        if node2Timestamp.IsZero() {
428✔
2385
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
209✔
2386
        }
209✔
2387

2388
        return chanInfo
219✔
2389
}
2390

2391
// BlockChannelRange represents a range of channels for a given block height.
2392
type BlockChannelRange struct {
2393
        // Height is the height of the block all of the channels below were
2394
        // included in.
2395
        Height uint32
2396

2397
        // Channels is the list of channels identified by their short ID
2398
        // representation known to us that were included in the block height
2399
        // above. The list may include channel update timestamp information if
2400
        // requested.
2401
        Channels []ChannelUpdateInfo
2402
}
2403

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

12✔
2414
        startChanID := &lnwire.ShortChannelID{
12✔
2415
                BlockHeight: startHeight,
12✔
2416
        }
12✔
2417

12✔
2418
        endChanID := lnwire.ShortChannelID{
12✔
2419
                BlockHeight: endHeight,
12✔
2420
                TxIndex:     math.MaxUint32 & 0x00ffffff,
12✔
2421
                TxPosition:  math.MaxUint16,
12✔
2422
        }
12✔
2423

12✔
2424
        // As we need to perform a range scan, we'll convert the starting and
12✔
2425
        // ending height to their corresponding values when encoded using short
12✔
2426
        // channel ID's.
12✔
2427
        var chanIDStart, chanIDEnd [8]byte
12✔
2428
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
12✔
2429
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
12✔
2430

12✔
2431
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
12✔
2432
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
24✔
2433
                edges := tx.ReadBucket(edgeBucket)
12✔
2434
                if edges == nil {
12✔
2435
                        return ErrGraphNoEdgesFound
×
2436
                }
×
2437
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
12✔
2438
                if edgeIndex == nil {
12✔
2439
                        return ErrGraphNoEdgesFound
×
2440
                }
×
2441

2442
                cursor := edgeIndex.ReadCursor()
12✔
2443

12✔
2444
                // We'll now iterate through the database, and find each
12✔
2445
                // channel ID that resides within the specified range.
12✔
2446
                //
12✔
2447
                //nolint:ll
12✔
2448
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
12✔
2449
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
57✔
2450
                        // Don't send alias SCIDs during gossip sync.
45✔
2451
                        edgeReader := bytes.NewReader(v)
45✔
2452
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
45✔
2453
                        if err != nil {
45✔
2454
                                return err
×
2455
                        }
×
2456

2457
                        if edgeInfo.AuthProof == nil {
46✔
2458
                                continue
1✔
2459
                        }
2460

2461
                        // This channel ID rests within the target range, so
2462
                        // we'll add it to our returned set.
2463
                        rawCid := byteOrder.Uint64(k)
45✔
2464
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
45✔
2465

45✔
2466
                        chanInfo := NewChannelUpdateInfo(
45✔
2467
                                cid, time.Time{}, time.Time{},
45✔
2468
                        )
45✔
2469

45✔
2470
                        if !withTimestamps {
67✔
2471
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2472
                                        channelsPerBlock[cid.BlockHeight],
22✔
2473
                                        chanInfo,
22✔
2474
                                )
22✔
2475

22✔
2476
                                continue
22✔
2477
                        }
2478

2479
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
23✔
2480

23✔
2481
                        rawPolicy := edges.Get(node1Key)
23✔
2482
                        if len(rawPolicy) != 0 {
38✔
2483
                                r := bytes.NewReader(rawPolicy)
15✔
2484

15✔
2485
                                edge, err := deserializeChanEdgePolicyRaw(r)
15✔
2486
                                if err != nil && !errors.Is(
15✔
2487
                                        err, ErrEdgePolicyOptionalFieldNotFound,
15✔
2488
                                ) {
15✔
2489

×
2490
                                        return err
×
2491
                                }
×
2492

2493
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
15✔
2494
                        }
2495

2496
                        rawPolicy = edges.Get(node2Key)
23✔
2497
                        if len(rawPolicy) != 0 {
30✔
2498
                                r := bytes.NewReader(rawPolicy)
7✔
2499

7✔
2500
                                edge, err := deserializeChanEdgePolicyRaw(r)
7✔
2501
                                if err != nil && !errors.Is(
7✔
2502
                                        err, ErrEdgePolicyOptionalFieldNotFound,
7✔
2503
                                ) {
7✔
2504

×
2505
                                        return err
×
2506
                                }
×
2507

2508
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
7✔
2509
                        }
2510

2511
                        channelsPerBlock[cid.BlockHeight] = append(
23✔
2512
                                channelsPerBlock[cid.BlockHeight], chanInfo,
23✔
2513
                        )
23✔
2514
                }
2515

2516
                return nil
12✔
2517
        }, func() {
12✔
2518
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
12✔
2519
        })
12✔
2520

2521
        switch {
12✔
2522
        // If we don't know of any channels yet, then there's nothing to
2523
        // filter, so we'll return an empty slice.
2524
        case err == ErrGraphNoEdgesFound || len(channelsPerBlock) == 0:
4✔
2525
                return nil, nil
4✔
2526

2527
        case err != nil:
×
2528
                return nil, err
×
2529
        }
2530

2531
        // Return the channel ranges in ascending block height order.
2532
        blocks := make([]uint32, 0, len(channelsPerBlock))
9✔
2533
        for block := range channelsPerBlock {
32✔
2534
                blocks = append(blocks, block)
23✔
2535
        }
23✔
2536
        sort.Slice(blocks, func(i, j int) bool {
29✔
2537
                return blocks[i] < blocks[j]
20✔
2538
        })
20✔
2539

2540
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
9✔
2541
        for _, block := range blocks {
32✔
2542
                channelRanges = append(channelRanges, BlockChannelRange{
23✔
2543
                        Height:   block,
23✔
2544
                        Channels: channelsPerBlock[block],
23✔
2545
                })
23✔
2546
        }
23✔
2547

2548
        return channelRanges, nil
9✔
2549
}
2550

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

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

24✔
2572
        var (
24✔
2573
                chanEdges []ChannelEdge
24✔
2574
                cidBytes  [8]byte
24✔
2575
        )
24✔
2576

24✔
2577
        fetchChanInfos := func(tx kvdb.RTx) error {
48✔
2578
                edges := tx.ReadBucket(edgeBucket)
24✔
2579
                if edges == nil {
24✔
2580
                        return ErrGraphNoEdgesFound
×
2581
                }
×
2582
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
24✔
2583
                if edgeIndex == nil {
24✔
2584
                        return ErrGraphNoEdgesFound
×
2585
                }
×
2586
                nodes := tx.ReadBucket(nodeBucket)
24✔
2587
                if nodes == nil {
24✔
2588
                        return ErrGraphNotFound
×
2589
                }
×
2590

2591
                for _, cid := range chanIDs {
55✔
2592
                        byteOrder.PutUint64(cidBytes[:], cid)
31✔
2593

31✔
2594
                        // First, we'll fetch the static edge information. If
31✔
2595
                        // the edge is unknown, we will skip the edge and
31✔
2596
                        // continue gathering all known edges.
31✔
2597
                        edgeInfo, err := fetchChanEdgeInfo(
31✔
2598
                                edgeIndex, cidBytes[:],
31✔
2599
                        )
31✔
2600
                        switch {
31✔
2601
                        case errors.Is(err, ErrEdgeNotFound):
23✔
2602
                                continue
23✔
2603
                        case err != nil:
×
2604
                                return err
×
2605
                        }
2606

2607
                        // With the static information obtained, we'll now
2608
                        // fetch the dynamic policy info.
2609
                        edge1, edge2, err := fetchChanEdgePolicies(
9✔
2610
                                edgeIndex, edges, cidBytes[:],
9✔
2611
                        )
9✔
2612
                        if err != nil {
9✔
2613
                                return err
×
2614
                        }
×
2615

2616
                        node1, err := fetchLightningNode(
9✔
2617
                                nodes, edgeInfo.NodeKey1Bytes[:],
9✔
2618
                        )
9✔
2619
                        if err != nil {
9✔
2620
                                return err
×
2621
                        }
×
2622

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

2630
                        chanEdges = append(chanEdges, ChannelEdge{
9✔
2631
                                Info:    &edgeInfo,
9✔
2632
                                Policy1: edge1,
9✔
2633
                                Policy2: edge2,
9✔
2634
                                Node1:   &node1,
9✔
2635
                                Node2:   &node2,
9✔
2636
                        })
9✔
2637
                }
2638
                return nil
24✔
2639
        }
2640

2641
        if tx == nil {
29✔
2642
                err := kvdb.View(c.db, fetchChanInfos, func() {
10✔
2643
                        chanEdges = nil
5✔
2644
                })
5✔
2645
                if err != nil {
5✔
2646
                        return nil, err
×
2647
                }
×
2648

2649
                return chanEdges, nil
5✔
2650
        }
2651

2652
        err := fetchChanInfos(tx)
19✔
2653
        if err != nil {
19✔
2654
                return nil, err
×
2655
        }
×
2656

2657
        return chanEdges, nil
19✔
2658
}
2659

2660
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2661
        edge1, edge2 *models.ChannelEdgePolicy) error {
140✔
2662

140✔
2663
        // First, we'll fetch the edge update index bucket which currently
140✔
2664
        // stores an entry for the channel we're about to delete.
140✔
2665
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
140✔
2666
        if updateIndex == nil {
140✔
2667
                // No edges in bucket, return early.
×
2668
                return nil
×
2669
        }
×
2670

2671
        // Now that we have the bucket, we'll attempt to construct a template
2672
        // for the index key: updateTime || chanid.
2673
        var indexKey [8 + 8]byte
140✔
2674
        byteOrder.PutUint64(indexKey[8:], chanID)
140✔
2675

140✔
2676
        // With the template constructed, we'll attempt to delete an entry that
140✔
2677
        // would have been created by both edges: we'll alternate the update
140✔
2678
        // times, as one may had overridden the other.
140✔
2679
        if edge1 != nil {
152✔
2680
                byteOrder.PutUint64(
12✔
2681
                        indexKey[:8], uint64(edge1.LastUpdate.Unix()),
12✔
2682
                )
12✔
2683
                if err := updateIndex.Delete(indexKey[:]); err != nil {
12✔
2684
                        return err
×
2685
                }
×
2686
        }
2687

2688
        // We'll also attempt to delete the entry that may have been created by
2689
        // the second edge.
2690
        if edge2 != nil {
154✔
2691
                byteOrder.PutUint64(
14✔
2692
                        indexKey[:8], uint64(edge2.LastUpdate.Unix()),
14✔
2693
                )
14✔
2694
                if err := updateIndex.Delete(indexKey[:]); err != nil {
14✔
2695
                        return err
×
2696
                }
×
2697
        }
2698

2699
        return nil
140✔
2700
}
2701

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

204✔
2713
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
204✔
2714
        if err != nil {
268✔
2715
                return err
64✔
2716
        }
64✔
2717

2718
        if c.graphCache != nil {
280✔
2719
                c.graphCache.RemoveChannel(
140✔
2720
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
140✔
2721
                        edgeInfo.ChannelID,
140✔
2722
                )
140✔
2723
        }
140✔
2724

2725
        // We'll also remove the entry in the edge update index bucket before
2726
        // we delete the edges themselves so we can access their last update
2727
        // times.
2728
        cid := byteOrder.Uint64(chanID)
140✔
2729
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
140✔
2730
        if err != nil {
140✔
2731
                return err
×
2732
        }
×
2733
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
140✔
2734
        if err != nil {
140✔
2735
                return err
×
2736
        }
×
2737

2738
        // The edge key is of the format pubKey || chanID. First we construct
2739
        // the latter half, populating the channel ID.
2740
        var edgeKey [33 + 8]byte
140✔
2741
        copy(edgeKey[33:], chanID)
140✔
2742

140✔
2743
        // With the latter half constructed, copy over the first public key to
140✔
2744
        // delete the edge in this direction, then the second to delete the
140✔
2745
        // edge in the opposite direction.
140✔
2746
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
140✔
2747
        if edges.Get(edgeKey[:]) != nil {
280✔
2748
                if err := edges.Delete(edgeKey[:]); err != nil {
140✔
2749
                        return err
×
2750
                }
×
2751
        }
2752
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
140✔
2753
        if edges.Get(edgeKey[:]) != nil {
280✔
2754
                if err := edges.Delete(edgeKey[:]); err != nil {
140✔
2755
                        return err
×
2756
                }
×
2757
        }
2758

2759
        // As part of deleting the edge we also remove all disabled entries
2760
        // from the edgePolicyDisabledIndex bucket. We do that for both
2761
        // directions.
2762
        updateEdgePolicyDisabledIndex(edges, cid, false, false)
140✔
2763
        updateEdgePolicyDisabledIndex(edges, cid, true, false)
140✔
2764

140✔
2765
        // With the edge data deleted, we can purge the information from the two
140✔
2766
        // edge indexes.
140✔
2767
        if err := edgeIndex.Delete(chanID); err != nil {
140✔
2768
                return err
×
2769
        }
×
2770
        var b bytes.Buffer
140✔
2771
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
140✔
2772
                return err
×
2773
        }
×
2774
        if err := chanIndex.Delete(b.Bytes()); err != nil {
140✔
2775
                return err
×
2776
        }
×
2777

2778
        // Finally, we'll mark the edge as a zombie within our index if it's
2779
        // being removed due to the channel becoming a zombie. We do this to
2780
        // ensure we don't store unnecessary data for spent channels.
2781
        if !isZombie {
258✔
2782
                return nil
118✔
2783
        }
118✔
2784

2785
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
23✔
2786
        if strictZombie {
26✔
2787
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2788
        }
3✔
2789

2790
        return markEdgeZombie(
23✔
2791
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
23✔
2792
        )
23✔
2793
}
2794

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

3✔
2814
        switch {
3✔
2815
        // If we don't have either edge policy, we'll return both pubkeys so
2816
        // that the channel can be resurrected by either party.
UNCOV
2817
        case e1 == nil && e2 == nil:
×
UNCOV
2818
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2819

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

2827
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2828
        // return a blank pubkey for edge1. In this case, only an update from
2829
        // edge2 can resurect the channel.
2830
        default:
2✔
2831
                return [33]byte{}, info.NodeKey2Bytes
2✔
2832
        }
2833
}
2834

2835
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2836
// within the database for the referenced channel. The `flags` attribute within
2837
// the ChannelEdgePolicy determines which of the directed edges are being
2838
// updated. If the flag is 1, then the first node's information is being
2839
// updated, otherwise it's the second node's information. The node ordering is
2840
// determined by the lexicographical ordering of the identity public keys of the
2841
// nodes on either side of the channel.
2842
func (c *ChannelGraph) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2843
        op ...batch.SchedulerOption) error {
2,667✔
2844

2,667✔
2845
        var (
2,667✔
2846
                isUpdate1    bool
2,667✔
2847
                edgeNotFound bool
2,667✔
2848
        )
2,667✔
2849

2,667✔
2850
        r := &batch.Request{
2,667✔
2851
                Reset: func() {
5,334✔
2852
                        isUpdate1 = false
2,667✔
2853
                        edgeNotFound = false
2,667✔
2854
                },
2,667✔
2855
                Update: func(tx kvdb.RwTx) error {
2,667✔
2856
                        var err error
2,667✔
2857
                        isUpdate1, err = updateEdgePolicy(
2,667✔
2858
                                tx, edge, c.graphCache,
2,667✔
2859
                        )
2,667✔
2860

2,667✔
2861
                        // Silence ErrEdgeNotFound so that the batch can
2,667✔
2862
                        // succeed, but propagate the error via local state.
2,667✔
2863
                        if errors.Is(err, ErrEdgeNotFound) {
2,670✔
2864
                                edgeNotFound = true
3✔
2865
                                return nil
3✔
2866
                        }
3✔
2867

2868
                        return err
2,664✔
2869
                },
2870
                OnCommit: func(err error) error {
2,667✔
2871
                        switch {
2,667✔
2872
                        case err != nil:
×
2873
                                return err
×
2874
                        case edgeNotFound:
3✔
2875
                                return ErrEdgeNotFound
3✔
2876
                        default:
2,664✔
2877
                                c.updateEdgeCache(edge, isUpdate1)
2,664✔
2878
                                return nil
2,664✔
2879
                        }
2880
                },
2881
        }
2882

2883
        for _, f := range op {
2,668✔
2884
                f(r)
1✔
2885
        }
1✔
2886

2887
        return c.chanScheduler.Execute(r)
2,667✔
2888
}
2889

2890
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2891
        isUpdate1 bool) {
2,664✔
2892

2,664✔
2893
        // If an entry for this channel is found in reject cache, we'll modify
2,664✔
2894
        // the entry with the updated timestamp for the direction that was just
2,664✔
2895
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,664✔
2896
        // during the next query for this edge.
2,664✔
2897
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,670✔
2898
                if isUpdate1 {
10✔
2899
                        entry.upd1Time = e.LastUpdate.Unix()
4✔
2900
                } else {
7✔
2901
                        entry.upd2Time = e.LastUpdate.Unix()
3✔
2902
                }
3✔
2903
                c.rejectCache.insert(e.ChannelID, entry)
6✔
2904
        }
2905

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

2920
// updateEdgePolicy attempts to update an edge's policy within the relevant
2921
// buckets using an existing database transaction. The returned boolean will be
2922
// true if the updated policy belongs to node1, and false if the policy belonged
2923
// to node2.
2924
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy,
2925
        graphCache *GraphCache) (bool, error) {
2,668✔
2926

2,668✔
2927
        edges := tx.ReadWriteBucket(edgeBucket)
2,668✔
2928
        if edges == nil {
2,668✔
2929
                return false, ErrEdgeNotFound
×
2930
        }
×
2931
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,668✔
2932
        if edgeIndex == nil {
2,668✔
2933
                return false, ErrEdgeNotFound
×
2934
        }
×
2935

2936
        // Create the channelID key be converting the channel ID
2937
        // integer into a byte slice.
2938
        var chanID [8]byte
2,668✔
2939
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,668✔
2940

2,668✔
2941
        // With the channel ID, we then fetch the value storing the two
2,668✔
2942
        // nodes which connect this channel edge.
2,668✔
2943
        nodeInfo := edgeIndex.Get(chanID[:])
2,668✔
2944
        if nodeInfo == nil {
2,671✔
2945
                return false, ErrEdgeNotFound
3✔
2946
        }
3✔
2947

2948
        // Depending on the flags value passed above, either the first
2949
        // or second edge policy is being updated.
2950
        var fromNode, toNode []byte
2,665✔
2951
        var isUpdate1 bool
2,665✔
2952
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
4,005✔
2953
                fromNode = nodeInfo[:33]
1,340✔
2954
                toNode = nodeInfo[33:66]
1,340✔
2955
                isUpdate1 = true
1,340✔
2956
        } else {
2,666✔
2957
                fromNode = nodeInfo[33:66]
1,326✔
2958
                toNode = nodeInfo[:33]
1,326✔
2959
                isUpdate1 = false
1,326✔
2960
        }
1,326✔
2961

2962
        // Finally, with the direction of the edge being updated
2963
        // identified, we update the on-disk edge representation.
2964
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,665✔
2965
        if err != nil {
2,665✔
2966
                return false, err
×
2967
        }
×
2968

2969
        var (
2,665✔
2970
                fromNodePubKey route.Vertex
2,665✔
2971
                toNodePubKey   route.Vertex
2,665✔
2972
        )
2,665✔
2973
        copy(fromNodePubKey[:], fromNode)
2,665✔
2974
        copy(toNodePubKey[:], toNode)
2,665✔
2975

2,665✔
2976
        if graphCache != nil {
4,944✔
2977
                graphCache.UpdatePolicy(
2,279✔
2978
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,279✔
2979
                )
2,279✔
2980
        }
2,279✔
2981

2982
        return isUpdate1, nil
2,665✔
2983
}
2984

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

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

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

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

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

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

3026
        return nodeIsPublic, nil
14✔
3027
}
3028

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

2,944✔
3036
        return c.fetchLightningNode(tx, nodePub)
2,944✔
3037
}
2,944✔
3038

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

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

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

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

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

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

3079
                node = &n
3,768✔
3080

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

3084
        if tx == nil {
4,620✔
3085
                err := kvdb.View(
838✔
3086
                        c.db, fetch, func() {
1,676✔
3087
                                node = nil
838✔
3088
                        },
838✔
3089
                )
3090
                if err != nil {
853✔
3091
                        return nil, err
15✔
3092
                }
15✔
3093

3094
                return node, nil
824✔
3095
        }
3096

3097
        err := fetch(tx)
2,944✔
3098
        if err != nil {
2,944✔
3099
                return nil, err
×
3100
        }
×
3101

3102
        return node, nil
2,944✔
3103
}
3104

3105
// graphCacheNode is a struct that wraps a LightningNode in a way that it can be
3106
// cached in the graph cache.
3107
type graphCacheNode struct {
3108
        pubKeyBytes route.Vertex
3109
        features    *lnwire.FeatureVector
3110
}
3111

3112
// newGraphCacheNode returns a new cache optimized node.
3113
func newGraphCacheNode(pubKey route.Vertex,
3114
        features *lnwire.FeatureVector) *graphCacheNode {
735✔
3115

735✔
3116
        return &graphCacheNode{
735✔
3117
                pubKeyBytes: pubKey,
735✔
3118
                features:    features,
735✔
3119
        }
735✔
3120
}
735✔
3121

3122
// PubKey returns the node's public identity key.
3123
func (n *graphCacheNode) PubKey() route.Vertex {
735✔
3124
        return n.pubKeyBytes
735✔
3125
}
735✔
3126

3127
// Features returns the node's features.
3128
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
715✔
3129
        return n.features
715✔
3130
}
715✔
3131

3132
// ForEachChannel iterates through all channels of this node, executing the
3133
// passed callback with an edge info structure and the policies of each end
3134
// of the channel. The first edge policy is the outgoing edge *to* the
3135
// connecting node, while the second is the incoming edge *from* the
3136
// connecting node. If the callback returns an error, then the iteration is
3137
// halted with the error propagated back up to the caller.
3138
//
3139
// Unknown policies are passed into the callback as nil values.
3140
func (n *graphCacheNode) ForEachChannel(tx kvdb.RTx,
3141
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3142
                *models.ChannelEdgePolicy) error) error {
635✔
3143

635✔
3144
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
635✔
3145
}
635✔
3146

3147
var _ GraphCacheNode = (*graphCacheNode)(nil)
3148

3149
// HasLightningNode determines if the graph has a vertex identified by the
3150
// target node identity public key. If the node exists in the database, a
3151
// timestamp of when the data for the node was lasted updated is returned along
3152
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3153
// boolean.
3154
func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool,
3155
        error) {
17✔
3156

17✔
3157
        var (
17✔
3158
                updateTime time.Time
17✔
3159
                exists     bool
17✔
3160
        )
17✔
3161

17✔
3162
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
34✔
3163
                // First grab the nodes bucket which stores the mapping from
17✔
3164
                // pubKey to node information.
17✔
3165
                nodes := tx.ReadBucket(nodeBucket)
17✔
3166
                if nodes == nil {
17✔
3167
                        return ErrGraphNotFound
×
3168
                }
×
3169

3170
                // If a key for this serialized public key isn't found, we can
3171
                // exit early.
3172
                nodeBytes := nodes.Get(nodePub[:])
17✔
3173
                if nodeBytes == nil {
21✔
3174
                        exists = false
4✔
3175
                        return nil
4✔
3176
                }
4✔
3177

3178
                // Otherwise we continue on to obtain the time stamp
3179
                // representing the last time the data for this node was
3180
                // updated.
3181
                nodeReader := bytes.NewReader(nodeBytes)
14✔
3182
                node, err := deserializeLightningNode(nodeReader)
14✔
3183
                if err != nil {
14✔
3184
                        return err
×
3185
                }
×
3186

3187
                exists = true
14✔
3188
                updateTime = node.LastUpdate
14✔
3189
                return nil
14✔
3190
        }, func() {
17✔
3191
                updateTime = time.Time{}
17✔
3192
                exists = false
17✔
3193
        })
17✔
3194
        if err != nil {
17✔
3195
                return time.Time{}, exists, err
×
3196
        }
×
3197

3198
        return updateTime, exists, nil
17✔
3199
}
3200

3201
// nodeTraversal is used to traverse all channels of a node given by its
3202
// public key and passes channel information into the specified callback.
3203
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3204
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3205
                *models.ChannelEdgePolicy) error) error {
1,881✔
3206

1,881✔
3207
        traversal := func(tx kvdb.RTx) error {
3,762✔
3208
                edges := tx.ReadBucket(edgeBucket)
1,881✔
3209
                if edges == nil {
1,881✔
3210
                        return ErrGraphNotFound
×
3211
                }
×
3212
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,881✔
3213
                if edgeIndex == nil {
1,881✔
3214
                        return ErrGraphNoEdgesFound
×
3215
                }
×
3216

3217
                // In order to reach all the edges for this node, we take
3218
                // advantage of the construction of the key-space within the
3219
                // edge bucket. The keys are stored in the form: pubKey ||
3220
                // chanID. Therefore, starting from a chanID of zero, we can
3221
                // scan forward in the bucket, grabbing all the edges for the
3222
                // node. Once the prefix no longer matches, then we know we're
3223
                // done.
3224
                var nodeStart [33 + 8]byte
1,881✔
3225
                copy(nodeStart[:], nodePub)
1,881✔
3226
                copy(nodeStart[33:], chanStart[:])
1,881✔
3227

1,881✔
3228
                // Starting from the key pubKey || 0, we seek forward in the
1,881✔
3229
                // bucket until the retrieved key no longer has the public key
1,881✔
3230
                // as its prefix. This indicates that we've stepped over into
1,881✔
3231
                // another node's edges, so we can terminate our scan.
1,881✔
3232
                edgeCursor := edges.ReadCursor()
1,881✔
3233
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() { //nolint:ll
5,731✔
3234
                        // If the prefix still matches, the channel id is
3,850✔
3235
                        // returned in nodeEdge. Channel id is used to lookup
3,850✔
3236
                        // the node at the other end of the channel and both
3,850✔
3237
                        // edge policies.
3,850✔
3238
                        chanID := nodeEdge[33:]
3,850✔
3239
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3,850✔
3240
                        if err != nil {
3,850✔
3241
                                return err
×
3242
                        }
×
3243

3244
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,850✔
3245
                                edges, chanID, nodePub,
3,850✔
3246
                        )
3,850✔
3247
                        if err != nil {
3,850✔
3248
                                return err
×
3249
                        }
×
3250

3251
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,850✔
3252
                        if err != nil {
3,850✔
3253
                                return err
×
3254
                        }
×
3255

3256
                        incomingPolicy, err := fetchChanEdgePolicy(
3,850✔
3257
                                edges, chanID, otherNode[:],
3,850✔
3258
                        )
3,850✔
3259
                        if err != nil {
3,850✔
3260
                                return err
×
3261
                        }
×
3262

3263
                        // Finally, we execute the callback.
3264
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,850✔
3265
                        if err != nil {
3,860✔
3266
                                return err
10✔
3267
                        }
10✔
3268
                }
3269

3270
                return nil
1,872✔
3271
        }
3272

3273
        // If no transaction was provided, then we'll create a new transaction
3274
        // to execute the transaction within.
3275
        if tx == nil {
1,891✔
3276
                return kvdb.View(db, traversal, func() {})
20✔
3277
        }
3278

3279
        // Otherwise, we re-use the existing transaction to execute the graph
3280
        // traversal.
3281
        return traversal(tx)
1,872✔
3282
}
3283

3284
// ForEachNodeChannel iterates through all channels of the given node,
3285
// executing the passed callback with an edge info structure and the policies
3286
// of each end of the channel. The first edge policy is the outgoing edge *to*
3287
// the connecting node, while the second is the incoming edge *from* the
3288
// connecting node. If the callback returns an error, then the iteration is
3289
// halted with the error propagated back up to the caller.
3290
//
3291
// Unknown policies are passed into the callback as nil values.
3292
func (c *ChannelGraph) ForEachNodeChannel(nodePub route.Vertex,
3293
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3294
                *models.ChannelEdgePolicy) error) error {
7✔
3295

7✔
3296
        return nodeTraversal(nil, nodePub[:], c.db, cb)
7✔
3297
}
7✔
3298

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

999✔
3317
        return nodeTraversal(tx, nodePub[:], c.db, cb)
999✔
3318
}
999✔
3319

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

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

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

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

3353
                targetNode = &node
1✔
3354

1✔
3355
                return nil
1✔
3356
        }
3357

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

3369
        return targetNode, err
1✔
3370
}
3371

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

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

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

23✔
3387
        return node1Key[:], node2Key[:]
23✔
3388
}
23✔
3389

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

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

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

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

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

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

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

3456
                policy1 = e1
2✔
3457
                policy2 = e2
2✔
3458
                return nil
2✔
3459
        }, func() {
12✔
3460
                edgeInfo = nil
12✔
3461
                policy1 = nil
12✔
3462
                policy2 = nil
12✔
3463
        })
12✔
3464
        if err != nil {
23✔
3465
                return nil, nil, nil, err
11✔
3466
        }
11✔
3467

3468
        return edgeInfo, policy1, policy2, nil
2✔
3469
}
3470

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

28✔
3484
        var (
28✔
3485
                edgeInfo  *models.ChannelEdgeInfo
28✔
3486
                policy1   *models.ChannelEdgePolicy
28✔
3487
                policy2   *models.ChannelEdgePolicy
28✔
3488
                channelID [8]byte
28✔
3489
        )
28✔
3490

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

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

3511
                byteOrder.PutUint64(channelID[:], chanID)
28✔
3512

28✔
3513
                // Now, attempt to fetch edge.
28✔
3514
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
28✔
3515

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

3527
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3528
                                zombieIndex, chanID,
3✔
3529
                        )
3✔
3530
                        if !isZombie {
5✔
3531
                                return ErrEdgeNotFound
2✔
3532
                        }
2✔
3533

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

3545
                // Otherwise, we'll just return the error if any.
3546
                if err != nil {
26✔
3547
                        return err
×
3548
                }
×
3549

3550
                edgeInfo = &edge
26✔
3551

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

3561
                policy1 = e1
26✔
3562
                policy2 = e2
26✔
3563
                return nil
26✔
3564
        }, func() {
28✔
3565
                edgeInfo = nil
28✔
3566
                policy1 = nil
28✔
3567
                policy2 = nil
28✔
3568
        })
28✔
3569
        if err == ErrZombieEdge {
30✔
3570
                return edgeInfo, nil, nil, err
2✔
3571
        }
2✔
3572
        if err != nil {
29✔
3573
                return nil, nil, nil, err
2✔
3574
        }
2✔
3575

3576
        return edgeInfo, policy1, policy2, nil
26✔
3577
}
3578

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

3598
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
14✔
3599
                return err
14✔
3600
        }, func() {
14✔
3601
                nodeIsPublic = false
14✔
3602
        })
14✔
3603
        if err != nil {
14✔
3604
                return false, err
×
3605
        }
×
3606

3607
        return nodeIsPublic, nil
14✔
3608
}
3609

3610
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3611
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
47✔
3612
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
47✔
3613
        if err != nil {
47✔
3614
                return nil, err
×
3615
        }
×
3616

3617
        // With the witness script generated, we'll now turn it into a p2wsh
3618
        // script:
3619
        //  * OP_0 <sha256(script)>
3620
        bldr := txscript.NewScriptBuilder(
47✔
3621
                txscript.WithScriptAllocSize(input.P2WSHSize),
47✔
3622
        )
47✔
3623
        bldr.AddOp(txscript.OP_0)
47✔
3624
        scriptHash := sha256.Sum256(witnessScript)
47✔
3625
        bldr.AddData(scriptHash[:])
47✔
3626

47✔
3627
        return bldr.Script()
47✔
3628
}
3629

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

3638
        // OutPoint is the outpoint of the target channel.
3639
        OutPoint wire.OutPoint
3640
}
3641

3642
// String returns a human readable version of the target EdgePoint. We return
3643
// the outpoint directly as it is enough to uniquely identify the edge point.
3644
func (e *EdgePoint) String() string {
×
3645
        return e.OutPoint.String()
×
3646
}
×
3647

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

3671
                // Once we have the proper bucket, we'll range over each key
3672
                // (which is the channel point for the channel) and decode it,
3673
                // accumulating each entry.
3674
                return chanIndex.ForEach(
24✔
3675
                        func(chanPointBytes, chanID []byte) error {
67✔
3676
                                chanPointReader := bytes.NewReader(
43✔
3677
                                        chanPointBytes,
43✔
3678
                                )
43✔
3679

43✔
3680
                                var chanPoint wire.OutPoint
43✔
3681
                                err := ReadOutpoint(chanPointReader, &chanPoint)
43✔
3682
                                if err != nil {
43✔
3683
                                        return err
×
3684
                                }
×
3685

3686
                                edgeInfo, err := fetchChanEdgeInfo(
43✔
3687
                                        edgeIndex, chanID,
43✔
3688
                                )
43✔
3689
                                if err != nil {
43✔
3690
                                        return err
×
3691
                                }
×
3692

3693
                                pkScript, err := genMultiSigP2WSH(
43✔
3694
                                        edgeInfo.BitcoinKey1Bytes[:],
43✔
3695
                                        edgeInfo.BitcoinKey2Bytes[:],
43✔
3696
                                )
43✔
3697
                                if err != nil {
43✔
3698
                                        return err
×
3699
                                }
×
3700

3701
                                edgePoints = append(edgePoints, EdgePoint{
43✔
3702
                                        FundingPkScript: pkScript,
43✔
3703
                                        OutPoint:        chanPoint,
43✔
3704
                                })
43✔
3705

43✔
3706
                                return nil
43✔
3707
                        },
3708
                )
3709
        }, func() {
24✔
3710
                edgePoints = nil
24✔
3711
        }); err != nil {
24✔
3712
                return nil, err
×
3713
        }
×
3714

3715
        return edgePoints, nil
24✔
3716
}
3717

3718
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3719
// zombie. This method is used on an ad-hoc basis, when channels need to be
3720
// marked as zombies outside the normal pruning cycle.
3721
func (c *ChannelGraph) MarkEdgeZombie(chanID uint64,
3722
        pubKey1, pubKey2 [33]byte) error {
122✔
3723

122✔
3724
        c.cacheMu.Lock()
122✔
3725
        defer c.cacheMu.Unlock()
122✔
3726

122✔
3727
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
244✔
3728
                edges := tx.ReadWriteBucket(edgeBucket)
122✔
3729
                if edges == nil {
122✔
3730
                        return ErrGraphNoEdgesFound
×
3731
                }
×
3732
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
122✔
3733
                if err != nil {
122✔
3734
                        return fmt.Errorf("unable to create zombie "+
×
3735
                                "bucket: %w", err)
×
3736
                }
×
3737

3738
                if c.graphCache != nil {
244✔
3739
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
122✔
3740
                }
122✔
3741

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

3748
        c.rejectCache.remove(chanID)
122✔
3749
        c.chanCache.remove(chanID)
122✔
3750

122✔
3751
        return nil
122✔
3752
}
3753

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

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

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

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

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

3✔
3775
        return c.markEdgeLiveUnsafe(nil, chanID)
3✔
3776
}
3✔
3777

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

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

22✔
3798
                if len(zombieIndex.Get(k[:])) == 0 {
23✔
3799
                        return ErrZombieEdgeNotFound
1✔
3800
                }
1✔
3801

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

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

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

21✔
3820
        // We need to add the channel back into our graph cache, otherwise we
21✔
3821
        // won't use it for path finding.
21✔
3822
        if c.graphCache != nil {
42✔
3823
                edgeInfos, err := c.fetchChanInfos(tx, []uint64{chanID})
21✔
3824
                if err != nil {
21✔
3825
                        return err
×
3826
                }
×
3827

3828
                for _, edgeInfo := range edgeInfos {
21✔
3829
                        c.graphCache.AddChannel(
×
3830
                                edgeInfo.Info, edgeInfo.Policy1,
×
3831
                                edgeInfo.Policy2,
×
3832
                        )
×
3833
                }
×
3834
        }
3835

3836
        return nil
21✔
3837
}
3838

3839
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3840
// zombie, then the two node public keys corresponding to this edge are also
3841
// returned.
3842
func (c *ChannelGraph) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
5✔
3843
        var (
5✔
3844
                isZombie         bool
5✔
3845
                pubKey1, pubKey2 [33]byte
5✔
3846
        )
5✔
3847

5✔
3848
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3849
                edges := tx.ReadBucket(edgeBucket)
5✔
3850
                if edges == nil {
5✔
3851
                        return ErrGraphNoEdgesFound
×
3852
                }
×
3853
                zombieIndex := edges.NestedReadBucket(zombieBucket)
5✔
3854
                if zombieIndex == nil {
5✔
3855
                        return nil
×
3856
                }
×
3857

3858
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
5✔
3859
                return nil
5✔
3860
        }, func() {
5✔
3861
                isZombie = false
5✔
3862
                pubKey1 = [33]byte{}
5✔
3863
                pubKey2 = [33]byte{}
5✔
3864
        })
5✔
3865
        if err != nil {
5✔
3866
                return false, [33]byte{}, [33]byte{}
×
3867
        }
×
3868

3869
        return isZombie, pubKey1, pubKey2
5✔
3870
}
3871

3872
// isZombieEdge returns whether an entry exists for the given channel in the
3873
// zombie index. If an entry exists, then the two node public keys corresponding
3874
// to this edge are also returned.
3875
func isZombieEdge(zombieIndex kvdb.RBucket,
3876
        chanID uint64) (bool, [33]byte, [33]byte) {
186✔
3877

186✔
3878
        var k [8]byte
186✔
3879
        byteOrder.PutUint64(k[:], chanID)
186✔
3880

186✔
3881
        v := zombieIndex.Get(k[:])
186✔
3882
        if v == nil {
299✔
3883
                return false, [33]byte{}, [33]byte{}
113✔
3884
        }
113✔
3885

3886
        var pubKey1, pubKey2 [33]byte
74✔
3887
        copy(pubKey1[:], v[:33])
74✔
3888
        copy(pubKey2[:], v[33:])
74✔
3889

74✔
3890
        return true, pubKey1, pubKey2
74✔
3891
}
3892

3893
// NumZombies returns the current number of zombie channels in the graph.
3894
func (c *ChannelGraph) NumZombies() (uint64, error) {
4✔
3895
        var numZombies uint64
4✔
3896
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3897
                edges := tx.ReadBucket(edgeBucket)
4✔
3898
                if edges == nil {
4✔
3899
                        return nil
×
3900
                }
×
3901
                zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3902
                if zombieIndex == nil {
4✔
3903
                        return nil
×
3904
                }
×
3905

3906
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3907
                        numZombies++
2✔
3908
                        return nil
2✔
3909
                })
2✔
3910
        }, func() {
4✔
3911
                numZombies = 0
4✔
3912
        })
4✔
3913
        if err != nil {
4✔
3914
                return 0, err
×
3915
        }
×
3916

3917
        return numZombies, nil
4✔
3918
}
3919

3920
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3921
// that we can ignore channel announcements that we know to be closed without
3922
// having to validate them and fetch a block.
3923
func (c *ChannelGraph) PutClosedScid(scid lnwire.ShortChannelID) error {
1✔
3924
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
2✔
3925
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
1✔
3926
                if err != nil {
1✔
3927
                        return err
×
3928
                }
×
3929

3930
                var k [8]byte
1✔
3931
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3932

1✔
3933
                return closedScids.Put(k[:], []byte{})
1✔
3934
        }, func() {})
1✔
3935
}
3936

3937
// IsClosedScid checks whether a channel identified by the passed in scid is
3938
// closed. This helps avoid having to perform expensive validation checks.
3939
// TODO: Add an LRU cache to cut down on disc reads.
3940
func (c *ChannelGraph) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
3✔
3941
        var isClosed bool
3✔
3942
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3943
                closedScids := tx.ReadBucket(closedScidBucket)
3✔
3944
                if closedScids == nil {
3✔
3945
                        return ErrClosedScidsNotFound
×
3946
                }
×
3947

3948
                var k [8]byte
3✔
3949
                byteOrder.PutUint64(k[:], scid.ToUint64())
3✔
3950

3✔
3951
                if closedScids.Get(k[:]) != nil {
4✔
3952
                        isClosed = true
1✔
3953
                        return nil
1✔
3954
                }
1✔
3955

3956
                return nil
2✔
3957
        }, func() {
3✔
3958
                isClosed = false
3✔
3959
        })
3✔
3960
        if err != nil {
3✔
3961
                return false, err
×
3962
        }
×
3963

3964
        return isClosed, nil
3✔
3965
}
3966

3967
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3968
        updateIndex kvdb.RwBucket, node *models.LightningNode) error {
993✔
3969

993✔
3970
        var (
993✔
3971
                scratch [16]byte
993✔
3972
                b       bytes.Buffer
993✔
3973
        )
993✔
3974

993✔
3975
        pub, err := node.PubKey()
993✔
3976
        if err != nil {
993✔
3977
                return err
×
3978
        }
×
3979
        nodePub := pub.SerializeCompressed()
993✔
3980

993✔
3981
        // If the node has the update time set, write it, else write 0.
993✔
3982
        updateUnix := uint64(0)
993✔
3983
        if node.LastUpdate.Unix() > 0 {
1,859✔
3984
                updateUnix = uint64(node.LastUpdate.Unix())
866✔
3985
        }
866✔
3986

3987
        byteOrder.PutUint64(scratch[:8], updateUnix)
993✔
3988
        if _, err := b.Write(scratch[:8]); err != nil {
993✔
3989
                return err
×
3990
        }
×
3991

3992
        if _, err := b.Write(nodePub); err != nil {
993✔
3993
                return err
×
3994
        }
×
3995

3996
        // If we got a node announcement for this node, we will have the rest
3997
        // of the data available. If not we don't have more data to write.
3998
        if !node.HaveNodeAnnouncement {
1,068✔
3999
                // Write HaveNodeAnnouncement=0.
75✔
4000
                byteOrder.PutUint16(scratch[:2], 0)
75✔
4001
                if _, err := b.Write(scratch[:2]); err != nil {
75✔
4002
                        return err
×
4003
                }
×
4004

4005
                return nodeBucket.Put(nodePub, b.Bytes())
75✔
4006
        }
4007

4008
        // Write HaveNodeAnnouncement=1.
4009
        byteOrder.PutUint16(scratch[:2], 1)
919✔
4010
        if _, err := b.Write(scratch[:2]); err != nil {
919✔
4011
                return err
×
4012
        }
×
4013

4014
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
919✔
4015
                return err
×
4016
        }
×
4017
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
919✔
4018
                return err
×
4019
        }
×
4020
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
919✔
4021
                return err
×
4022
        }
×
4023

4024
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
919✔
4025
                return err
×
4026
        }
×
4027

4028
        if err := node.Features.Encode(&b); err != nil {
919✔
4029
                return err
×
4030
        }
×
4031

4032
        numAddresses := uint16(len(node.Addresses))
919✔
4033
        byteOrder.PutUint16(scratch[:2], numAddresses)
919✔
4034
        if _, err := b.Write(scratch[:2]); err != nil {
919✔
4035
                return err
×
4036
        }
×
4037

4038
        for _, address := range node.Addresses {
2,066✔
4039
                if err := SerializeAddr(&b, address); err != nil {
1,147✔
4040
                        return err
×
4041
                }
×
4042
        }
4043

4044
        sigLen := len(node.AuthSigBytes)
919✔
4045
        if sigLen > 80 {
919✔
4046
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4047
                        sigLen)
×
4048
        }
×
4049

4050
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
919✔
4051
        if err != nil {
919✔
4052
                return err
×
4053
        }
×
4054

4055
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
919✔
4056
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4057
        }
×
4058
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
919✔
4059
        if err != nil {
919✔
4060
                return err
×
4061
        }
×
4062

4063
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
919✔
4064
                return err
×
4065
        }
×
4066

4067
        // With the alias bucket updated, we'll now update the index that
4068
        // tracks the time series of node updates.
4069
        var indexKey [8 + 33]byte
919✔
4070
        byteOrder.PutUint64(indexKey[:8], updateUnix)
919✔
4071
        copy(indexKey[8:], nodePub)
919✔
4072

919✔
4073
        // If there was already an old index entry for this node, then we'll
919✔
4074
        // delete the old one before we write the new entry.
919✔
4075
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
1,024✔
4076
                // Extract out the old update time to we can reconstruct the
105✔
4077
                // prior index key to delete it from the index.
105✔
4078
                oldUpdateTime := nodeBytes[:8]
105✔
4079

105✔
4080
                var oldIndexKey [8 + 33]byte
105✔
4081
                copy(oldIndexKey[:8], oldUpdateTime)
105✔
4082
                copy(oldIndexKey[8:], nodePub)
105✔
4083

105✔
4084
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
105✔
4085
                        return err
×
4086
                }
×
4087
        }
4088

4089
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
919✔
4090
                return err
×
4091
        }
×
4092

4093
        return nodeBucket.Put(nodePub, b.Bytes())
919✔
4094
}
4095

4096
func fetchLightningNode(nodeBucket kvdb.RBucket,
4097
        nodePub []byte) (models.LightningNode, error) {
3,619✔
4098

3,619✔
4099
        nodeBytes := nodeBucket.Get(nodePub)
3,619✔
4100
        if nodeBytes == nil {
3,693✔
4101
                return models.LightningNode{}, ErrGraphNodeNotFound
74✔
4102
        }
74✔
4103

4104
        nodeReader := bytes.NewReader(nodeBytes)
3,546✔
4105
        return deserializeLightningNode(nodeReader)
3,546✔
4106
}
4107

4108
func deserializeLightningNodeCacheable(r io.Reader) (*graphCacheNode, error) {
121✔
4109
        // Always populate a feature vector, even if we don't have a node
121✔
4110
        // announcement and short circuit below.
121✔
4111
        node := newGraphCacheNode(
121✔
4112
                route.Vertex{},
121✔
4113
                lnwire.EmptyFeatureVector(),
121✔
4114
        )
121✔
4115

121✔
4116
        var nodeScratch [8]byte
121✔
4117

121✔
4118
        // Skip ahead:
121✔
4119
        // - LastUpdate (8 bytes)
121✔
4120
        if _, err := r.Read(nodeScratch[:]); err != nil {
121✔
4121
                return nil, err
×
4122
        }
×
4123

4124
        if _, err := io.ReadFull(r, node.pubKeyBytes[:]); err != nil {
121✔
4125
                return nil, err
×
4126
        }
×
4127

4128
        // Read the node announcement flag.
4129
        if _, err := r.Read(nodeScratch[:2]); err != nil {
121✔
4130
                return nil, err
×
4131
        }
×
4132
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
121✔
4133

121✔
4134
        // The rest of the data is optional, and will only be there if we got a
121✔
4135
        // node announcement for this node.
121✔
4136
        if hasNodeAnn == 0 {
122✔
4137
                return node, nil
1✔
4138
        }
1✔
4139

4140
        // We did get a node announcement for this node, so we'll have the rest
4141
        // of the data available.
4142
        var rgb uint8
121✔
4143
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
121✔
4144
                return nil, err
×
4145
        }
×
4146
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
121✔
4147
                return nil, err
×
4148
        }
×
4149
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
121✔
4150
                return nil, err
×
4151
        }
×
4152

4153
        if _, err := wire.ReadVarString(r, 0); err != nil {
121✔
4154
                return nil, err
×
4155
        }
×
4156

4157
        if err := node.features.Decode(r); err != nil {
121✔
4158
                return nil, err
×
4159
        }
×
4160

4161
        return node, nil
121✔
4162
}
4163

4164
func deserializeLightningNode(r io.Reader) (models.LightningNode, error) {
8,504✔
4165
        var (
8,504✔
4166
                node    models.LightningNode
8,504✔
4167
                scratch [8]byte
8,504✔
4168
                err     error
8,504✔
4169
        )
8,504✔
4170

8,504✔
4171
        // Always populate a feature vector, even if we don't have a node
8,504✔
4172
        // announcement and short circuit below.
8,504✔
4173
        node.Features = lnwire.EmptyFeatureVector()
8,504✔
4174

8,504✔
4175
        if _, err := r.Read(scratch[:]); err != nil {
8,504✔
4176
                return models.LightningNode{}, err
×
4177
        }
×
4178

4179
        unix := int64(byteOrder.Uint64(scratch[:]))
8,504✔
4180
        node.LastUpdate = time.Unix(unix, 0)
8,504✔
4181

8,504✔
4182
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,504✔
4183
                return models.LightningNode{}, err
×
4184
        }
×
4185

4186
        if _, err := r.Read(scratch[:2]); err != nil {
8,504✔
4187
                return models.LightningNode{}, err
×
4188
        }
×
4189

4190
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,504✔
4191
        if hasNodeAnn == 1 {
16,872✔
4192
                node.HaveNodeAnnouncement = true
8,368✔
4193
        } else {
8,505✔
4194
                node.HaveNodeAnnouncement = false
137✔
4195
        }
137✔
4196

4197
        // The rest of the data is optional, and will only be there if we got a
4198
        // node announcement for this node.
4199
        if !node.HaveNodeAnnouncement {
8,641✔
4200
                return node, nil
137✔
4201
        }
137✔
4202

4203
        // We did get a node announcement for this node, so we'll have the rest
4204
        // of the data available.
4205
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,368✔
4206
                return models.LightningNode{}, err
×
4207
        }
×
4208
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,368✔
4209
                return models.LightningNode{}, err
×
4210
        }
×
4211
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,368✔
4212
                return models.LightningNode{}, err
×
4213
        }
×
4214

4215
        node.Alias, err = wire.ReadVarString(r, 0)
8,368✔
4216
        if err != nil {
8,368✔
4217
                return models.LightningNode{}, err
×
4218
        }
×
4219

4220
        err = node.Features.Decode(r)
8,368✔
4221
        if err != nil {
8,368✔
4222
                return models.LightningNode{}, err
×
4223
        }
×
4224

4225
        if _, err := r.Read(scratch[:2]); err != nil {
8,368✔
4226
                return models.LightningNode{}, err
×
4227
        }
×
4228
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,368✔
4229

8,368✔
4230
        var addresses []net.Addr
8,368✔
4231
        for i := 0; i < numAddresses; i++ {
18,970✔
4232
                address, err := DeserializeAddr(r)
10,602✔
4233
                if err != nil {
10,602✔
4234
                        return models.LightningNode{}, err
×
4235
                }
×
4236
                addresses = append(addresses, address)
10,602✔
4237
        }
4238
        node.Addresses = addresses
8,368✔
4239

8,368✔
4240
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,368✔
4241
        if err != nil {
8,368✔
4242
                return models.LightningNode{}, err
×
4243
        }
×
4244

4245
        // We'll try and see if there are any opaque bytes left, if not, then
4246
        // we'll ignore the EOF error and return the node as is.
4247
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
8,368✔
4248
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,368✔
4249
        )
8,368✔
4250
        switch {
8,368✔
4251
        case err == io.ErrUnexpectedEOF:
×
4252
        case err == io.EOF:
×
4253
        case err != nil:
×
4254
                return models.LightningNode{}, err
×
4255
        }
4256

4257
        return node, nil
8,368✔
4258
}
4259

4260
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4261
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,483✔
4262

1,483✔
4263
        var b bytes.Buffer
1,483✔
4264

1,483✔
4265
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,483✔
4266
                return err
×
4267
        }
×
4268
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,483✔
4269
                return err
×
4270
        }
×
4271
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,483✔
4272
                return err
×
4273
        }
×
4274
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,483✔
4275
                return err
×
4276
        }
×
4277

4278
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,483✔
4279
                return err
×
4280
        }
×
4281

4282
        authProof := edgeInfo.AuthProof
1,483✔
4283
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,483✔
4284
        if authProof != nil {
2,883✔
4285
                nodeSig1 = authProof.NodeSig1Bytes
1,400✔
4286
                nodeSig2 = authProof.NodeSig2Bytes
1,400✔
4287
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,400✔
4288
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,400✔
4289
        }
1,400✔
4290

4291
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,483✔
4292
                return err
×
4293
        }
×
4294
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,483✔
4295
                return err
×
4296
        }
×
4297
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,483✔
4298
                return err
×
4299
        }
×
4300
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,483✔
4301
                return err
×
4302
        }
×
4303

4304
        if err := WriteOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,483✔
4305
                return err
×
4306
        }
×
4307
        err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity))
1,483✔
4308
        if err != nil {
1,483✔
4309
                return err
×
4310
        }
×
4311
        if _, err := b.Write(chanID[:]); err != nil {
1,483✔
4312
                return err
×
4313
        }
×
4314
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,483✔
4315
                return err
×
4316
        }
×
4317

4318
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,483✔
4319
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4320
        }
×
4321
        err = wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,483✔
4322
        if err != nil {
1,483✔
4323
                return err
×
4324
        }
×
4325

4326
        return edgeIndex.Put(chanID[:], b.Bytes())
1,483✔
4327
}
4328

4329
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4330
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,191✔
4331

4,191✔
4332
        edgeInfoBytes := edgeIndex.Get(chanID)
4,191✔
4333
        if edgeInfoBytes == nil {
4,280✔
4334
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
89✔
4335
        }
89✔
4336

4337
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,103✔
4338
        return deserializeChanEdgeInfo(edgeInfoReader)
4,103✔
4339
}
4340

4341
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,735✔
4342
        var (
4,735✔
4343
                err      error
4,735✔
4344
                edgeInfo models.ChannelEdgeInfo
4,735✔
4345
        )
4,735✔
4346

4,735✔
4347
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,735✔
4348
                return models.ChannelEdgeInfo{}, err
×
4349
        }
×
4350
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,735✔
4351
                return models.ChannelEdgeInfo{}, err
×
4352
        }
×
4353
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,735✔
4354
                return models.ChannelEdgeInfo{}, err
×
4355
        }
×
4356
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,735✔
4357
                return models.ChannelEdgeInfo{}, err
×
4358
        }
×
4359

4360
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,735✔
4361
        if err != nil {
4,735✔
4362
                return models.ChannelEdgeInfo{}, err
×
4363
        }
×
4364

4365
        proof := &models.ChannelAuthProof{}
4,735✔
4366

4,735✔
4367
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,735✔
4368
        if err != nil {
4,735✔
4369
                return models.ChannelEdgeInfo{}, err
×
4370
        }
×
4371
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,735✔
4372
        if err != nil {
4,735✔
4373
                return models.ChannelEdgeInfo{}, err
×
4374
        }
×
4375
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,735✔
4376
        if err != nil {
4,735✔
4377
                return models.ChannelEdgeInfo{}, err
×
4378
        }
×
4379
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,735✔
4380
        if err != nil {
4,735✔
4381
                return models.ChannelEdgeInfo{}, err
×
4382
        }
×
4383

4384
        if !proof.IsEmpty() {
6,517✔
4385
                edgeInfo.AuthProof = proof
1,782✔
4386
        }
1,782✔
4387

4388
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,735✔
4389
        if err := ReadOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,735✔
4390
                return models.ChannelEdgeInfo{}, err
×
4391
        }
×
4392
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,735✔
4393
                return models.ChannelEdgeInfo{}, err
×
4394
        }
×
4395
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,735✔
4396
                return models.ChannelEdgeInfo{}, err
×
4397
        }
×
4398

4399
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,735✔
4400
                return models.ChannelEdgeInfo{}, err
×
4401
        }
×
4402

4403
        // We'll try and see if there are any opaque bytes left, if not, then
4404
        // we'll ignore the EOF error and return the edge as is.
4405
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
4,735✔
4406
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
4,735✔
4407
        )
4,735✔
4408
        switch {
4,735✔
4409
        case err == io.ErrUnexpectedEOF:
×
4410
        case err == io.EOF:
×
4411
        case err != nil:
×
4412
                return models.ChannelEdgeInfo{}, err
×
4413
        }
4414

4415
        return edgeInfo, nil
4,735✔
4416
}
4417

4418
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4419
        from, to []byte) error {
2,665✔
4420

2,665✔
4421
        var edgeKey [33 + 8]byte
2,665✔
4422
        copy(edgeKey[:], from)
2,665✔
4423
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,665✔
4424

2,665✔
4425
        var b bytes.Buffer
2,665✔
4426
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,665✔
4427
                return err
×
4428
        }
×
4429

4430
        // Before we write out the new edge, we'll create a new entry in the
4431
        // update index in order to keep it fresh.
4432
        updateUnix := uint64(edge.LastUpdate.Unix())
2,665✔
4433
        var indexKey [8 + 8]byte
2,665✔
4434
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,665✔
4435
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,665✔
4436

2,665✔
4437
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,665✔
4438
        if err != nil {
2,665✔
4439
                return err
×
4440
        }
×
4441

4442
        // If there was already an entry for this edge, then we'll need to
4443
        // delete the old one to ensure we don't leave around any after-images.
4444
        // An unknown policy value does not have a update time recorded, so
4445
        // it also does not need to be removed.
4446
        if edgeBytes := edges.Get(edgeKey[:]); edgeBytes != nil &&
2,665✔
4447
                !bytes.Equal(edgeBytes[:], unknownPolicy) {
2,690✔
4448

25✔
4449
                // In order to delete the old entry, we'll need to obtain the
25✔
4450
                // *prior* update time in order to delete it. To do this, we'll
25✔
4451
                // need to deserialize the existing policy within the database
25✔
4452
                // (now outdated by the new one), and delete its corresponding
25✔
4453
                // entry within the update index. We'll ignore any
25✔
4454
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
25✔
4455
                // the channel ID and update time to delete the entry.
25✔
4456
                // TODO(halseth): get rid of these invalid policies in a
25✔
4457
                // migration.
25✔
4458
                oldEdgePolicy, err := deserializeChanEdgePolicy(
25✔
4459
                        bytes.NewReader(edgeBytes),
25✔
4460
                )
25✔
4461
                if err != nil && err != ErrEdgePolicyOptionalFieldNotFound {
25✔
4462
                        return err
×
4463
                }
×
4464

4465
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
25✔
4466

25✔
4467
                var oldIndexKey [8 + 8]byte
25✔
4468
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
25✔
4469
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
25✔
4470

25✔
4471
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
25✔
4472
                        return err
×
4473
                }
×
4474
        }
4475

4476
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,665✔
4477
                return err
×
4478
        }
×
4479

4480
        updateEdgePolicyDisabledIndex(
2,665✔
4481
                edges, edge.ChannelID,
2,665✔
4482
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,665✔
4483
                edge.IsDisabled(),
2,665✔
4484
        )
2,665✔
4485

2,665✔
4486
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,665✔
4487
}
4488

4489
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4490
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4491
// one.
4492
// The direction represents the direction of the edge and disabled is used for
4493
// deciding whether to remove or add an entry to the bucket.
4494
// In general a channel is disabled if two entries for the same chanID exist
4495
// in this bucket.
4496
// Maintaining the bucket this way allows a fast retrieval of disabled
4497
// channels, for example when prune is needed.
4498
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4499
        direction bool, disabled bool) error {
2,943✔
4500

2,943✔
4501
        var disabledEdgeKey [8 + 1]byte
2,943✔
4502
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,943✔
4503
        if direction {
4,408✔
4504
                disabledEdgeKey[8] = 1
1,465✔
4505
        }
1,465✔
4506

4507
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,943✔
4508
                disabledEdgePolicyBucket,
2,943✔
4509
        )
2,943✔
4510
        if err != nil {
2,943✔
4511
                return err
×
4512
        }
×
4513

4514
        if disabled {
2,970✔
4515
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
27✔
4516
        }
27✔
4517

4518
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,917✔
4519
}
4520

4521
// putChanEdgePolicyUnknown marks the edge policy as unknown
4522
// in the edges bucket.
4523
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4524
        from []byte) error {
2,963✔
4525

2,963✔
4526
        var edgeKey [33 + 8]byte
2,963✔
4527
        copy(edgeKey[:], from)
2,963✔
4528
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,963✔
4529

2,963✔
4530
        if edges.Get(edgeKey[:]) != nil {
2,963✔
4531
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4532
                        " when there is already a policy present", channelID)
×
4533
        }
×
4534

4535
        return edges.Put(edgeKey[:], unknownPolicy)
2,963✔
4536
}
4537

4538
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4539
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,173✔
4540

8,173✔
4541
        var edgeKey [33 + 8]byte
8,173✔
4542
        copy(edgeKey[:], nodePub)
8,173✔
4543
        copy(edgeKey[33:], chanID[:])
8,173✔
4544

8,173✔
4545
        edgeBytes := edges.Get(edgeKey[:])
8,173✔
4546
        if edgeBytes == nil {
8,173✔
4547
                return nil, ErrEdgeNotFound
×
4548
        }
×
4549

4550
        // No need to deserialize unknown policy.
4551
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,540✔
4552
                return nil, nil
367✔
4553
        }
367✔
4554

4555
        edgeReader := bytes.NewReader(edgeBytes)
7,807✔
4556

7,807✔
4557
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,807✔
4558
        switch {
7,807✔
4559
        // If the db policy was missing an expected optional field, we return
4560
        // nil as if the policy was unknown.
4561
        case err == ErrEdgePolicyOptionalFieldNotFound:
1✔
4562
                return nil, nil
1✔
4563

4564
        case err != nil:
×
4565
                return nil, err
×
4566
        }
4567

4568
        return ep, nil
7,806✔
4569
}
4570

4571
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4572
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4573
        error) {
238✔
4574

238✔
4575
        edgeInfo := edgeIndex.Get(chanID)
238✔
4576
        if edgeInfo == nil {
238✔
4577
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4578
                        chanID)
×
4579
        }
×
4580

4581
        // The first node is contained within the first half of the edge
4582
        // information. We only propagate the error here and below if it's
4583
        // something other than edge non-existence.
4584
        node1Pub := edgeInfo[:33]
238✔
4585
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
238✔
4586
        if err != nil {
238✔
4587
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4588
                        node1Pub)
×
4589
        }
×
4590

4591
        // Similarly, the second node is contained within the latter
4592
        // half of the edge information.
4593
        node2Pub := edgeInfo[33:66]
238✔
4594
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
238✔
4595
        if err != nil {
238✔
4596
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4597
                        node2Pub)
×
4598
        }
×
4599

4600
        return edge1, edge2, nil
238✔
4601
}
4602

4603
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4604
        to []byte) error {
2,667✔
4605

2,667✔
4606
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,667✔
4607
        if err != nil {
2,667✔
4608
                return err
×
4609
        }
×
4610

4611
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,667✔
4612
                return err
×
4613
        }
×
4614

4615
        var scratch [8]byte
2,667✔
4616
        updateUnix := uint64(edge.LastUpdate.Unix())
2,667✔
4617
        byteOrder.PutUint64(scratch[:], updateUnix)
2,667✔
4618
        if _, err := w.Write(scratch[:]); err != nil {
2,667✔
4619
                return err
×
4620
        }
×
4621

4622
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,667✔
4623
                return err
×
4624
        }
×
4625
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,667✔
4626
                return err
×
4627
        }
×
4628
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,667✔
4629
                return err
×
4630
        }
×
4631
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,667✔
4632
                return err
×
4633
        }
×
4634
        err = binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat))
2,667✔
4635
        if err != nil {
2,667✔
4636
                return err
×
4637
        }
×
4638
        err = binary.Write(
2,667✔
4639
                w, byteOrder, uint64(edge.FeeProportionalMillionths),
2,667✔
4640
        )
2,667✔
4641
        if err != nil {
2,667✔
4642
                return err
×
4643
        }
×
4644

4645
        if _, err := w.Write(to); err != nil {
2,667✔
4646
                return err
×
4647
        }
×
4648

4649
        // If the max_htlc field is present, we write it. To be compatible with
4650
        // older versions that wasn't aware of this field, we write it as part
4651
        // of the opaque data.
4652
        // TODO(halseth): clean up when moving to TLV.
4653
        var opaqueBuf bytes.Buffer
2,667✔
4654
        if edge.MessageFlags.HasMaxHtlc() {
4,949✔
4655
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,282✔
4656
                if err != nil {
2,282✔
4657
                        return err
×
4658
                }
×
4659
        }
4660

4661
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,667✔
4662
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4663
        }
×
4664
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,667✔
4665
                return err
×
4666
        }
×
4667

4668
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,667✔
4669
                return err
×
4670
        }
×
4671
        return nil
2,667✔
4672
}
4673

4674
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,832✔
4675
        // Deserialize the policy. Note that in case an optional field is not
7,832✔
4676
        // found, both an error and a populated policy object are returned.
7,832✔
4677
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,832✔
4678
        if deserializeErr != nil &&
7,832✔
4679
                deserializeErr != ErrEdgePolicyOptionalFieldNotFound {
7,832✔
4680

×
4681
                return nil, deserializeErr
×
4682
        }
×
4683

4684
        return edge, deserializeErr
7,832✔
4685
}
4686

4687
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4688
        error) {
8,842✔
4689

8,842✔
4690
        edge := &models.ChannelEdgePolicy{}
8,842✔
4691

8,842✔
4692
        var err error
8,842✔
4693
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,842✔
4694
        if err != nil {
8,842✔
4695
                return nil, err
×
4696
        }
×
4697

4698
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,842✔
4699
                return nil, err
×
4700
        }
×
4701

4702
        var scratch [8]byte
8,842✔
4703
        if _, err := r.Read(scratch[:]); err != nil {
8,842✔
4704
                return nil, err
×
4705
        }
×
4706
        unix := int64(byteOrder.Uint64(scratch[:]))
8,842✔
4707
        edge.LastUpdate = time.Unix(unix, 0)
8,842✔
4708

8,842✔
4709
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,842✔
4710
                return nil, err
×
4711
        }
×
4712
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,842✔
4713
                return nil, err
×
4714
        }
×
4715
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,842✔
4716
                return nil, err
×
4717
        }
×
4718

4719
        var n uint64
8,842✔
4720
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,842✔
4721
                return nil, err
×
4722
        }
×
4723
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,842✔
4724

8,842✔
4725
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,842✔
4726
                return nil, err
×
4727
        }
×
4728
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,842✔
4729

8,842✔
4730
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,842✔
4731
                return nil, err
×
4732
        }
×
4733
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,842✔
4734

8,842✔
4735
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,842✔
4736
                return nil, err
×
4737
        }
×
4738

4739
        // We'll try and see if there are any opaque bytes left, if not, then
4740
        // we'll ignore the EOF error and return the edge as is.
4741
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,842✔
4742
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,842✔
4743
        )
8,842✔
4744
        switch {
8,842✔
4745
        case err == io.ErrUnexpectedEOF:
×
4746
        case err == io.EOF:
3✔
4747
        case err != nil:
×
4748
                return nil, err
×
4749
        }
4750

4751
        // See if optional fields are present.
4752
        if edge.MessageFlags.HasMaxHtlc() {
17,301✔
4753
                // The max_htlc field should be at the beginning of the opaque
8,459✔
4754
                // bytes.
8,459✔
4755
                opq := edge.ExtraOpaqueData
8,459✔
4756

8,459✔
4757
                // If the max_htlc field is not present, it might be old data
8,459✔
4758
                // stored before this field was validated. We'll return the
8,459✔
4759
                // edge along with an error.
8,459✔
4760
                if len(opq) < 8 {
8,462✔
4761
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4762
                }
3✔
4763

4764
                maxHtlc := byteOrder.Uint64(opq[:8])
8,456✔
4765
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,456✔
4766

8,456✔
4767
                // Exclude the parsed field from the rest of the opaque data.
8,456✔
4768
                edge.ExtraOpaqueData = opq[8:]
8,456✔
4769
        }
4770

4771
        return edge, nil
8,839✔
4772
}
4773

4774
// MakeTestGraph creates a new instance of the ChannelGraph for testing
4775
// purposes.
4776
func MakeTestGraph(t testing.TB, modifiers ...OptionModifier) (*ChannelGraph,
4777
        error) {
40✔
4778

40✔
4779
        opts := DefaultOptions()
40✔
4780
        for _, modifier := range modifiers {
40✔
4781
                modifier(opts)
×
4782
        }
×
4783

4784
        // Next, create channelgraph for the first time.
4785
        backend, backendCleanup, err := kvdb.GetTestBackend(t.TempDir(), "cgr")
40✔
4786
        if err != nil {
40✔
4787
                backendCleanup()
×
4788
                return nil, err
×
4789
        }
×
4790

4791
        graph, err := NewChannelGraph(backend)
40✔
4792
        if err != nil {
40✔
4793
                backendCleanup()
×
4794
                return nil, err
×
4795
        }
×
4796

4797
        t.Cleanup(func() {
80✔
4798
                _ = backend.Close()
40✔
4799
                backendCleanup()
40✔
4800
        })
40✔
4801

4802
        return graph, nil
40✔
4803
}
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