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

lightningnetwork / lnd / 10418626636

16 Aug 2024 10:36AM UTC coverage: 58.722% (+0.2%) from 58.558%
10418626636

Pull #9011

github

ziggie1984
docs: update release-notes.
Pull Request #9011: Fix TimeStamp issue in the Gossip Syncer

58 of 70 new or added lines in 3 files covered. (82.86%)

117 existing lines in 15 files now uncovered.

126269 of 215030 relevant lines covered (58.72%)

28151.42 hits per line

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

76.99
/channeldb/graph.go
1
package channeldb
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

158
const (
159
        // MaxAllowedExtraOpaqueBytes is the largest amount of opaque bytes that
160
        // we'll permit to be written to disk. We limit this as otherwise, it
161
        // would be possible for a node to create a ton of updates and slowly
162
        // fill our disk, and also waste bandwidth due to relaying.
163
        MaxAllowedExtraOpaqueBytes = 10000
164

165
        // ChannelUpdateExpiryPeriod is the default duration used to determine
166
        // whether a channel update (edge policy) is either out dated or too
167
        // far in the future.
168
        ChannelUpdateExpiryPeriod = time.Hour * 24 * 14
169
)
170

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

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

192
        chanScheduler batch.Scheduler
193
        nodeScheduler batch.Scheduler
194
}
195

196
// NewChannelGraph allocates a new ChannelGraph backed by a DB instance. The
197
// returned instance has its own unique reject cache and channel cache.
198
func NewChannelGraph(db kvdb.Backend, rejectCacheSize, chanCacheSize int,
199
        batchCommitInterval time.Duration, preAllocCacheNumNodes int,
200
        useGraphCache, noMigrations bool) (*ChannelGraph, error) {
1,844✔
201

1,844✔
202
        if !noMigrations {
3,688✔
203
                if err := initChannelGraph(db); err != nil {
1,844✔
204
                        return nil, err
×
205
                }
×
206
        }
207

208
        g := &ChannelGraph{
1,844✔
209
                db:          db,
1,844✔
210
                rejectCache: newRejectCache(rejectCacheSize),
1,844✔
211
                chanCache:   newChannelCache(chanCacheSize),
1,844✔
212
        }
1,844✔
213
        g.chanScheduler = batch.NewTimeScheduler(
1,844✔
214
                db, &g.cacheMu, batchCommitInterval,
1,844✔
215
        )
1,844✔
216
        g.nodeScheduler = batch.NewTimeScheduler(
1,844✔
217
                db, nil, batchCommitInterval,
1,844✔
218
        )
1,844✔
219

1,844✔
220
        // The graph cache can be turned off (e.g. for mobile users) for a
1,844✔
221
        // speed/memory usage tradeoff.
1,844✔
222
        if useGraphCache {
3,656✔
223
                g.graphCache = NewGraphCache(preAllocCacheNumNodes)
1,812✔
224
                startTime := time.Now()
1,812✔
225
                log.Debugf("Populating in-memory channel graph, this might " +
1,812✔
226
                        "take a while...")
1,812✔
227

1,812✔
228
                err := g.ForEachNodeCacheable(
1,812✔
229
                        func(tx kvdb.RTx, node GraphCacheNode) error {
1,915✔
230
                                g.graphCache.AddNodeFeatures(node)
103✔
231

103✔
232
                                return nil
103✔
233
                        },
103✔
234
                )
235
                if err != nil {
1,812✔
236
                        return nil, err
×
237
                }
×
238

239
                err = g.ForEachChannel(func(info *models.ChannelEdgeInfo,
1,812✔
240
                        policy1, policy2 *models.ChannelEdgePolicy) error {
2,211✔
241

399✔
242
                        g.graphCache.AddChannel(info, policy1, policy2)
399✔
243

399✔
244
                        return nil
399✔
245
                })
399✔
246
                if err != nil {
1,812✔
247
                        return nil, err
×
248
                }
×
249

250
                log.Debugf("Finished populating in-memory channel graph (took "+
1,812✔
251
                        "%v, %s)", time.Since(startTime), g.graphCache.Stats())
1,812✔
252
        }
253

254
        return g, nil
1,844✔
255
}
256

257
// channelMapKey is the key structure used for storing channel edge policies.
258
type channelMapKey struct {
259
        nodeKey route.Vertex
260
        chanID  [8]byte
261
}
262

263
// getChannelMap loads all channel edge policies from the database and stores
264
// them in a map.
265
func (c *ChannelGraph) getChannelMap(edges kvdb.RBucket) (
266
        map[channelMapKey]*models.ChannelEdgePolicy, error) {
1,816✔
267

1,816✔
268
        // Create a map to store all channel edge policies.
1,816✔
269
        channelMap := make(map[channelMapKey]*models.ChannelEdgePolicy)
1,816✔
270

1,816✔
271
        err := kvdb.ForAll(edges, func(k, edgeBytes []byte) error {
10,066✔
272
                // Skip embedded buckets.
8,250✔
273
                if bytes.Equal(k, edgeIndexBucket) ||
8,250✔
274
                        bytes.Equal(k, edgeUpdateIndexBucket) ||
8,250✔
275
                        bytes.Equal(k, zombieBucket) ||
8,250✔
276
                        bytes.Equal(k, disabledEdgePolicyBucket) ||
8,250✔
277
                        bytes.Equal(k, channelPointBucket) {
15,510✔
278

7,260✔
279
                        return nil
7,260✔
280
                }
7,260✔
281

282
                // Validate key length.
283
                if len(k) != 33+8 {
993✔
284
                        return fmt.Errorf("invalid edge key %x encountered", k)
×
285
                }
×
286

287
                var key channelMapKey
993✔
288
                copy(key.nodeKey[:], k[:33])
993✔
289
                copy(key.chanID[:], k[33:])
993✔
290

993✔
291
                // No need to deserialize unknown policy.
993✔
292
                if bytes.Equal(edgeBytes, unknownPolicy) {
993✔
293
                        return nil
×
294
                }
×
295

296
                edgeReader := bytes.NewReader(edgeBytes)
993✔
297
                edge, err := deserializeChanEdgePolicyRaw(
993✔
298
                        edgeReader,
993✔
299
                )
993✔
300

993✔
301
                switch {
993✔
302
                // If the db policy was missing an expected optional field, we
303
                // return nil as if the policy was unknown.
304
                case err == ErrEdgePolicyOptionalFieldNotFound:
×
305
                        return nil
×
306

307
                case err != nil:
×
308
                        return err
×
309
                }
310

311
                channelMap[key] = edge
993✔
312

993✔
313
                return nil
993✔
314
        })
315
        if err != nil {
1,816✔
316
                return nil, err
×
317
        }
×
318

319
        return channelMap, nil
1,816✔
320
}
321

322
var graphTopLevelBuckets = [][]byte{
323
        nodeBucket,
324
        edgeBucket,
325
        graphMetaBucket,
326
}
327

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

345
        return initChannelGraph(c.db)
×
346
}
347

348
// createChannelDB creates and initializes a fresh version of channeldb. In
349
// the case that the target path has not yet been created or doesn't yet exist,
350
// then the path is created. Additionally, all required top-level buckets used
351
// within the database are created.
352
func initChannelGraph(db kvdb.Backend) error {
1,844✔
353
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
3,688✔
354
                for _, tlb := range graphTopLevelBuckets {
7,370✔
355
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
5,526✔
356
                                return err
×
357
                        }
×
358
                }
359

360
                nodes := tx.ReadWriteBucket(nodeBucket)
1,844✔
361
                _, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
1,844✔
362
                if err != nil {
1,844✔
363
                        return err
×
364
                }
×
365
                _, err = nodes.CreateBucketIfNotExists(nodeUpdateIndexBucket)
1,844✔
366
                if err != nil {
1,844✔
367
                        return err
×
368
                }
×
369

370
                edges := tx.ReadWriteBucket(edgeBucket)
1,844✔
371
                _, err = edges.CreateBucketIfNotExists(edgeIndexBucket)
1,844✔
372
                if err != nil {
1,844✔
373
                        return err
×
374
                }
×
375
                _, err = edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
1,844✔
376
                if err != nil {
1,844✔
377
                        return err
×
378
                }
×
379
                _, err = edges.CreateBucketIfNotExists(channelPointBucket)
1,844✔
380
                if err != nil {
1,844✔
381
                        return err
×
382
                }
×
383
                _, err = edges.CreateBucketIfNotExists(zombieBucket)
1,844✔
384
                if err != nil {
1,844✔
385
                        return err
×
386
                }
×
387

388
                graphMeta := tx.ReadWriteBucket(graphMetaBucket)
1,844✔
389
                _, err = graphMeta.CreateBucketIfNotExists(pruneLogBucket)
1,844✔
390
                return err
1,844✔
391
        }, func() {})
1,844✔
392
        if err != nil {
1,844✔
393
                return fmt.Errorf("unable to create new channel graph: %w", err)
×
394
        }
×
395

396
        return nil
1,844✔
397
}
398

399
// NewPathFindTx returns a new read transaction that can be used for a single
400
// path finding session. Will return nil if the graph cache is enabled.
401
func (c *ChannelGraph) NewPathFindTx() (kvdb.RTx, error) {
134✔
402
        if c.graphCache != nil {
215✔
403
                return nil, nil
81✔
404
        }
81✔
405

406
        return c.db.BeginReadTx()
53✔
407
}
408

409
// ForEachChannel iterates through all the channel edges stored within the
410
// graph and invokes the passed callback for each edge. The callback takes two
411
// edges as since this is a directed graph, both the in/out edges are visited.
412
// If the callback returns an error, then the transaction is aborted and the
413
// iteration stops early.
414
//
415
// NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer
416
// for that particular channel edge routing policy will be passed into the
417
// callback.
418
func (c *ChannelGraph) ForEachChannel(cb func(*models.ChannelEdgeInfo,
419
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
1,816✔
420

1,816✔
421
        return c.db.View(func(tx kvdb.RTx) error {
3,632✔
422
                edges := tx.ReadBucket(edgeBucket)
1,816✔
423
                if edges == nil {
1,816✔
424
                        return ErrGraphNoEdgesFound
×
425
                }
×
426

427
                // First, load all edges in memory indexed by node and channel
428
                // id.
429
                channelMap, err := c.getChannelMap(edges)
1,816✔
430
                if err != nil {
1,816✔
431
                        return err
×
432
                }
×
433

434
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,816✔
435
                if edgeIndex == nil {
1,816✔
436
                        return ErrGraphNoEdgesFound
×
437
                }
×
438

439
                // Load edge index, recombine each channel with the policies
440
                // loaded above and invoke the callback.
441
                return kvdb.ForAll(edgeIndex, func(k, edgeInfoBytes []byte) error {
2,314✔
442
                        var chanID [8]byte
498✔
443
                        copy(chanID[:], k)
498✔
444

498✔
445
                        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
498✔
446
                        info, err := deserializeChanEdgeInfo(edgeInfoReader)
498✔
447
                        if err != nil {
498✔
448
                                return err
×
449
                        }
×
450

451
                        policy1 := channelMap[channelMapKey{
498✔
452
                                nodeKey: info.NodeKey1Bytes,
498✔
453
                                chanID:  chanID,
498✔
454
                        }]
498✔
455

498✔
456
                        policy2 := channelMap[channelMapKey{
498✔
457
                                nodeKey: info.NodeKey2Bytes,
498✔
458
                                chanID:  chanID,
498✔
459
                        }]
498✔
460

498✔
461
                        return cb(&info, policy1, policy2)
498✔
462
                })
463
        }, func() {})
1,816✔
464
}
465

466
// ForEachNodeDirectedChannel iterates through all channels of a given node,
467
// executing the passed callback on the directed edge representing the channel
468
// and its incoming policy. If the callback returns an error, then the iteration
469
// is halted with the error propagated back up to the caller.
470
//
471
// Unknown policies are passed into the callback as nil values.
472
func (c *ChannelGraph) ForEachNodeDirectedChannel(tx kvdb.RTx,
473
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
696✔
474

696✔
475
        if c.graphCache != nil {
1,155✔
476
                return c.graphCache.ForEachChannel(node, cb)
459✔
477
        }
459✔
478

479
        // Fallback that uses the database.
480
        toNodeCallback := func() route.Vertex {
373✔
481
                return node
133✔
482
        }
133✔
483
        toNodeFeatures, err := c.FetchNodeFeatures(node)
240✔
484
        if err != nil {
240✔
485
                return err
×
486
        }
×
487

488
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
240✔
489
                p2 *models.ChannelEdgePolicy) error {
733✔
490

493✔
491
                var cachedInPolicy *models.CachedEdgePolicy
493✔
492
                if p2 != nil {
983✔
493
                        cachedInPolicy = models.NewCachedPolicy(p2)
490✔
494
                        cachedInPolicy.ToNodePubKey = toNodeCallback
490✔
495
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
490✔
496
                }
490✔
497

498
                var inboundFee lnwire.Fee
493✔
499
                if p1 != nil {
985✔
500
                        // Extract inbound fee. If there is a decoding error,
492✔
501
                        // skip this edge.
492✔
502
                        _, err := p1.ExtraOpaqueData.ExtractRecords(&inboundFee)
492✔
503
                        if err != nil {
493✔
504
                                return nil
1✔
505
                        }
1✔
506
                }
507

508
                directedChannel := &DirectedChannel{
492✔
509
                        ChannelID:    e.ChannelID,
492✔
510
                        IsNode1:      node == e.NodeKey1Bytes,
492✔
511
                        OtherNode:    e.NodeKey2Bytes,
492✔
512
                        Capacity:     e.Capacity,
492✔
513
                        OutPolicySet: p1 != nil,
492✔
514
                        InPolicy:     cachedInPolicy,
492✔
515
                        InboundFee:   inboundFee,
492✔
516
                }
492✔
517

492✔
518
                if node == e.NodeKey2Bytes {
742✔
519
                        directedChannel.OtherNode = e.NodeKey1Bytes
250✔
520
                }
250✔
521

522
                return cb(directedChannel)
492✔
523
        }
524
        return nodeTraversal(tx, node[:], c.db, dbCallback)
240✔
525
}
526

527
// FetchNodeFeatures returns the features of a given node. If no features are
528
// known for the node, an empty feature vector is returned.
529
func (c *ChannelGraph) FetchNodeFeatures(
530
        node route.Vertex) (*lnwire.FeatureVector, error) {
1,125✔
531

1,125✔
532
        if c.graphCache != nil {
1,575✔
533
                return c.graphCache.GetFeatures(node), nil
450✔
534
        }
450✔
535

536
        // Fallback that uses the database.
537
        targetNode, err := c.FetchLightningNode(node)
678✔
538
        switch err {
678✔
539
        // If the node exists and has features, return them directly.
540
        case nil:
673✔
541
                return targetNode.Features, nil
673✔
542

543
        // If we couldn't find a node announcement, populate a blank feature
544
        // vector.
545
        case ErrGraphNodeNotFound:
5✔
546
                return lnwire.EmptyFeatureVector(), nil
5✔
547

548
        // Otherwise, bubble the error up.
549
        default:
×
550
                return nil, err
×
551
        }
552
}
553

554
// ForEachNodeCached is similar to ForEachNode, but it utilizes the channel
555
// graph cache instead. Note that this doesn't return all the information the
556
// regular ForEachNode method does.
557
//
558
// NOTE: The callback contents MUST not be modified.
559
func (c *ChannelGraph) ForEachNodeCached(cb func(node route.Vertex,
560
        chans map[uint64]*DirectedChannel) error) error {
1✔
561

1✔
562
        if c.graphCache != nil {
1✔
563
                return c.graphCache.ForEachNode(cb)
×
564
        }
×
565

566
        // Otherwise call back to a version that uses the database directly.
567
        // We'll iterate over each node, then the set of channels for each
568
        // node, and construct a similar callback functiopn signature as the
569
        // main funcotin expects.
570
        return c.ForEachNode(func(tx kvdb.RTx, node *LightningNode) error {
21✔
571
                channels := make(map[uint64]*DirectedChannel)
20✔
572

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

190✔
578
                                toNodeCallback := func() route.Vertex {
190✔
579
                                        return node.PubKeyBytes
×
580
                                }
×
581
                                toNodeFeatures, err := c.FetchNodeFeatures(
190✔
582
                                        node.PubKeyBytes,
190✔
583
                                )
190✔
584
                                if err != nil {
190✔
585
                                        return err
×
586
                                }
×
587

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

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

190✔
608
                                if node.PubKeyBytes == e.NodeKey2Bytes {
285✔
609
                                        directedChannel.OtherNode =
95✔
610
                                                e.NodeKey1Bytes
95✔
611
                                }
95✔
612

613
                                channels[e.ChannelID] = directedChannel
190✔
614

190✔
615
                                return nil
190✔
616
                        })
617
                if err != nil {
20✔
618
                        return err
×
619
                }
×
620

621
                return cb(node.PubKeyBytes, channels)
20✔
622
        })
623
}
624

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

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

638
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
639
                        disabledEdgePolicyBucket,
6✔
640
                )
6✔
641
                if disabledEdgePolicyIndex == nil {
7✔
642
                        return nil
1✔
643
                }
1✔
644

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

656
                        chanEdgeFound[chanID] = struct{}{}
7✔
657
                        return nil
7✔
658
                })
659
        }, func() {
6✔
660
                disabledChanIDs = nil
6✔
661
                chanEdgeFound = make(map[uint64]struct{})
6✔
662
        })
6✔
663
        if err != nil {
6✔
664
                return nil, err
×
665
        }
×
666

667
        return disabledChanIDs, nil
6✔
668
}
669

670
// ForEachNode iterates through all the stored vertices/nodes in the graph,
671
// executing the passed callback with each node encountered. If the callback
672
// returns an error, then the transaction is aborted and the iteration stops
673
// early.
674
//
675
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
676
// traversal when graph gets mega
677
func (c *ChannelGraph) ForEachNode(
678
        cb func(kvdb.RTx, *LightningNode) error) error {
132✔
679

132✔
680
        traversal := func(tx kvdb.RTx) error {
264✔
681
                // First grab the nodes bucket which stores the mapping from
132✔
682
                // pubKey to node information.
132✔
683
                nodes := tx.ReadBucket(nodeBucket)
132✔
684
                if nodes == nil {
132✔
685
                        return ErrGraphNotFound
×
686
                }
×
687

688
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,574✔
689
                        // If this is the source key, then we skip this
1,442✔
690
                        // iteration as the value for this key is a pubKey
1,442✔
691
                        // rather than raw node information.
1,442✔
692
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
1,706✔
693
                                return nil
264✔
694
                        }
264✔
695

696
                        nodeReader := bytes.NewReader(nodeBytes)
1,181✔
697
                        node, err := deserializeLightningNode(nodeReader)
1,181✔
698
                        if err != nil {
1,181✔
699
                                return err
×
700
                        }
×
701

702
                        // Execute the callback, the transaction will abort if
703
                        // this returns an error.
704
                        return cb(tx, &node)
1,181✔
705
                })
706
        }
707

708
        return kvdb.View(c.db, traversal, func() {})
264✔
709
}
710

711
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
712
// graph, executing the passed callback with each node encountered. If the
713
// callback returns an error, then the transaction is aborted and the iteration
714
// stops early.
715
func (c *ChannelGraph) ForEachNodeCacheable(cb func(kvdb.RTx,
716
        GraphCacheNode) error) error {
1,813✔
717

1,813✔
718
        traversal := func(tx kvdb.RTx) error {
3,626✔
719
                // First grab the nodes bucket which stores the mapping from
1,813✔
720
                // pubKey to node information.
1,813✔
721
                nodes := tx.ReadBucket(nodeBucket)
1,813✔
722
                if nodes == nil {
1,813✔
723
                        return ErrGraphNotFound
×
724
                }
×
725

726
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
5,556✔
727
                        // If this is the source key, then we skip this
3,743✔
728
                        // iteration as the value for this key is a pubKey
3,743✔
729
                        // rather than raw node information.
3,743✔
730
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
7,366✔
731
                                return nil
3,623✔
732
                        }
3,623✔
733

734
                        nodeReader := bytes.NewReader(nodeBytes)
123✔
735
                        cacheableNode, err := deserializeLightningNodeCacheable(
123✔
736
                                nodeReader,
123✔
737
                        )
123✔
738
                        if err != nil {
123✔
739
                                return err
×
740
                        }
×
741

742
                        // Execute the callback, the transaction will abort if
743
                        // this returns an error.
744
                        return cb(tx, cacheableNode)
123✔
745
                })
746
        }
747

748
        return kvdb.View(c.db, traversal, func() {})
3,626✔
749
}
750

751
// SourceNode returns the source node of the graph. The source node is treated
752
// as the center node within a star-graph. This method may be used to kick off
753
// a path finding algorithm in order to explore the reachability of another
754
// node based off the source node.
755
func (c *ChannelGraph) SourceNode() (*LightningNode, error) {
231✔
756
        var source *LightningNode
231✔
757
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
462✔
758
                // First grab the nodes bucket which stores the mapping from
231✔
759
                // pubKey to node information.
231✔
760
                nodes := tx.ReadBucket(nodeBucket)
231✔
761
                if nodes == nil {
231✔
762
                        return ErrGraphNotFound
×
763
                }
×
764

765
                node, err := c.sourceNode(nodes)
231✔
766
                if err != nil {
232✔
767
                        return err
1✔
768
                }
1✔
769
                source = node
230✔
770

230✔
771
                return nil
230✔
772
        }, func() {
231✔
773
                source = nil
231✔
774
        })
231✔
775
        if err != nil {
232✔
776
                return nil, err
1✔
777
        }
1✔
778

779
        return source, nil
230✔
780
}
781

782
// sourceNode uses an existing database transaction and returns the source node
783
// of the graph. The source node is treated as the center node within a
784
// star-graph. This method may be used to kick off a path finding algorithm in
785
// order to explore the reachability of another node based off the source node.
786
func (c *ChannelGraph) sourceNode(nodes kvdb.RBucket) (*LightningNode, error) {
496✔
787
        selfPub := nodes.Get(sourceKey)
496✔
788
        if selfPub == nil {
497✔
789
                return nil, ErrSourceNodeNotSet
1✔
790
        }
1✔
791

792
        // With the pubKey of the source node retrieved, we're able to
793
        // fetch the full node information.
794
        node, err := fetchLightningNode(nodes, selfPub)
495✔
795
        if err != nil {
495✔
796
                return nil, err
×
797
        }
×
798

799
        return &node, nil
495✔
800
}
801

802
// SetSourceNode sets the source node within the graph database. The source
803
// node is to be used as the center of a star-graph within path finding
804
// algorithms.
805
func (c *ChannelGraph) SetSourceNode(node *LightningNode) error {
119✔
806
        nodePubBytes := node.PubKeyBytes[:]
119✔
807

119✔
808
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
238✔
809
                // First grab the nodes bucket which stores the mapping from
119✔
810
                // pubKey to node information.
119✔
811
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
119✔
812
                if err != nil {
119✔
813
                        return err
×
814
                }
×
815

816
                // Next we create the mapping from source to the targeted
817
                // public key.
818
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
119✔
819
                        return err
×
820
                }
×
821

822
                // Finally, we commit the information of the lightning node
823
                // itself.
824
                return addLightningNode(tx, node)
119✔
825
        }, func() {})
119✔
826
}
827

828
// AddLightningNode adds a vertex/node to the graph database. If the node is not
829
// in the database from before, this will add a new, unconnected one to the
830
// graph. If it is present from before, this will update that node's
831
// information. Note that this method is expected to only be called to update an
832
// already present node from a node announcement, or to insert a node found in a
833
// channel update.
834
//
835
// TODO(roasbeef): also need sig of announcement
836
func (c *ChannelGraph) AddLightningNode(node *LightningNode,
837
        op ...batch.SchedulerOption) error {
788✔
838

788✔
839
        r := &batch.Request{
788✔
840
                Update: func(tx kvdb.RwTx) error {
1,576✔
841
                        if c.graphCache != nil {
1,396✔
842
                                cNode := newGraphCacheNode(
608✔
843
                                        node.PubKeyBytes, node.Features,
608✔
844
                                )
608✔
845
                                err := c.graphCache.AddNode(tx, cNode)
608✔
846
                                if err != nil {
608✔
847
                                        return err
×
848
                                }
×
849
                        }
850

851
                        return addLightningNode(tx, node)
788✔
852
                },
853
        }
854

855
        for _, f := range op {
791✔
856
                f(r)
3✔
857
        }
3✔
858

859
        return c.nodeScheduler.Execute(r)
788✔
860
}
861

862
func addLightningNode(tx kvdb.RwTx, node *LightningNode) error {
979✔
863
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
979✔
864
        if err != nil {
979✔
865
                return err
×
866
        }
×
867

868
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
979✔
869
        if err != nil {
979✔
870
                return err
×
871
        }
×
872

873
        updateIndex, err := nodes.CreateBucketIfNotExists(
979✔
874
                nodeUpdateIndexBucket,
979✔
875
        )
979✔
876
        if err != nil {
979✔
877
                return err
×
878
        }
×
879

880
        return putLightningNode(nodes, aliases, updateIndex, node)
979✔
881
}
882

883
// LookupAlias attempts to return the alias as advertised by the target node.
884
// TODO(roasbeef): currently assumes that aliases are unique...
885
func (c *ChannelGraph) LookupAlias(pub *btcec.PublicKey) (string, error) {
5✔
886
        var alias string
5✔
887

5✔
888
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
889
                nodes := tx.ReadBucket(nodeBucket)
5✔
890
                if nodes == nil {
5✔
891
                        return ErrGraphNodesNotFound
×
892
                }
×
893

894
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
5✔
895
                if aliases == nil {
5✔
896
                        return ErrGraphNodesNotFound
×
897
                }
×
898

899
                nodePub := pub.SerializeCompressed()
5✔
900
                a := aliases.Get(nodePub)
5✔
901
                if a == nil {
6✔
902
                        return ErrNodeAliasNotFound
1✔
903
                }
1✔
904

905
                // TODO(roasbeef): should actually be using the utf-8
906
                // package...
907
                alias = string(a)
4✔
908
                return nil
4✔
909
        }, func() {
5✔
910
                alias = ""
5✔
911
        })
5✔
912
        if err != nil {
6✔
913
                return "", err
1✔
914
        }
1✔
915

916
        return alias, nil
4✔
917
}
918

919
// DeleteLightningNode starts a new database transaction to remove a vertex/node
920
// from the database according to the node's public key.
921
func (c *ChannelGraph) DeleteLightningNode(nodePub route.Vertex) error {
3✔
922
        // TODO(roasbeef): ensure dangling edges are removed...
3✔
923
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
924
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
925
                if nodes == nil {
3✔
926
                        return ErrGraphNodeNotFound
×
927
                }
×
928

929
                if c.graphCache != nil {
6✔
930
                        c.graphCache.RemoveNode(nodePub)
3✔
931
                }
3✔
932

933
                return c.deleteLightningNode(nodes, nodePub[:])
3✔
934
        }, func() {})
3✔
935
}
936

937
// deleteLightningNode uses an existing database transaction to remove a
938
// vertex/node from the database according to the node's public key.
939
func (c *ChannelGraph) deleteLightningNode(nodes kvdb.RwBucket,
940
        compressedPubKey []byte) error {
71✔
941

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

947
        if err := aliases.Delete(compressedPubKey); err != nil {
71✔
948
                return err
×
949
        }
×
950

951
        // Before we delete the node, we'll fetch its current state so we can
952
        // determine when its last update was to clear out the node update
953
        // index.
954
        node, err := fetchLightningNode(nodes, compressedPubKey)
71✔
955
        if err != nil {
71✔
956
                return err
×
957
        }
×
958

959
        if err := nodes.Delete(compressedPubKey); err != nil {
71✔
960
                return err
×
961
        }
×
962

963
        // Finally, we'll delete the index entry for the node within the
964
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
965
        // need to track its last update.
966
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
71✔
967
        if nodeUpdateIndex == nil {
71✔
968
                return ErrGraphNodesNotFound
×
969
        }
×
970

971
        // In order to delete the entry, we'll need to reconstruct the key for
972
        // its last update.
973
        updateUnix := uint64(node.LastUpdate.Unix())
71✔
974
        var indexKey [8 + 33]byte
71✔
975
        byteOrder.PutUint64(indexKey[:8], updateUnix)
71✔
976
        copy(indexKey[8:], compressedPubKey)
71✔
977

71✔
978
        return nodeUpdateIndex.Delete(indexKey[:])
71✔
979
}
980

981
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
982
// undirected edge from the two target nodes are created. The information stored
983
// denotes the static attributes of the channel, such as the channelID, the keys
984
// involved in creation of the channel, and the set of features that the channel
985
// supports. The chanPoint and chanID are used to uniquely identify the edge
986
// globally within the database.
987
func (c *ChannelGraph) AddChannelEdge(edge *models.ChannelEdgeInfo,
988
        op ...batch.SchedulerOption) error {
1,687✔
989

1,687✔
990
        var alreadyExists bool
1,687✔
991
        r := &batch.Request{
1,687✔
992
                Reset: func() {
3,374✔
993
                        alreadyExists = false
1,687✔
994
                },
1,687✔
995
                Update: func(tx kvdb.RwTx) error {
1,687✔
996
                        err := c.addChannelEdge(tx, edge)
1,687✔
997

1,687✔
998
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,687✔
999
                        // succeed, but propagate the error via local state.
1,687✔
1000
                        if err == ErrEdgeAlreadyExist {
1,905✔
1001
                                alreadyExists = true
218✔
1002
                                return nil
218✔
1003
                        }
218✔
1004

1005
                        return err
1,469✔
1006
                },
1007
                OnCommit: func(err error) error {
1,687✔
1008
                        switch {
1,687✔
1009
                        case err != nil:
×
1010
                                return err
×
1011
                        case alreadyExists:
218✔
1012
                                return ErrEdgeAlreadyExist
218✔
1013
                        default:
1,469✔
1014
                                c.rejectCache.remove(edge.ChannelID)
1,469✔
1015
                                c.chanCache.remove(edge.ChannelID)
1,469✔
1016
                                return nil
1,469✔
1017
                        }
1018
                },
1019
        }
1020

1021
        for _, f := range op {
1,690✔
1022
                f(r)
3✔
1023
        }
3✔
1024

1025
        return c.chanScheduler.Execute(r)
1,687✔
1026
}
1027

1028
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1029
// utilize an existing db transaction.
1030
func (c *ChannelGraph) addChannelEdge(tx kvdb.RwTx,
1031
        edge *models.ChannelEdgeInfo) error {
1,687✔
1032

1,687✔
1033
        // Construct the channel's primary key which is the 8-byte channel ID.
1,687✔
1034
        var chanKey [8]byte
1,687✔
1035
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,687✔
1036

1,687✔
1037
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,687✔
1038
        if err != nil {
1,687✔
1039
                return err
×
1040
        }
×
1041
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,687✔
1042
        if err != nil {
1,687✔
1043
                return err
×
1044
        }
×
1045
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,687✔
1046
        if err != nil {
1,687✔
1047
                return err
×
1048
        }
×
1049
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,687✔
1050
        if err != nil {
1,687✔
1051
                return err
×
1052
        }
×
1053

1054
        // First, attempt to check if this edge has already been created. If
1055
        // so, then we can exit early as this method is meant to be idempotent.
1056
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
1,905✔
1057
                return ErrEdgeAlreadyExist
218✔
1058
        }
218✔
1059

1060
        if c.graphCache != nil {
2,756✔
1061
                c.graphCache.AddChannel(edge, nil, nil)
1,287✔
1062
        }
1,287✔
1063

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

1084
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
1,469✔
1085
        switch {
1,469✔
1086
        case node2Err == ErrGraphNodeNotFound:
60✔
1087
                node2Shell := LightningNode{
60✔
1088
                        PubKeyBytes:          edge.NodeKey2Bytes,
60✔
1089
                        HaveNodeAnnouncement: false,
60✔
1090
                }
60✔
1091
                err := addLightningNode(tx, &node2Shell)
60✔
1092
                if err != nil {
60✔
1093
                        return fmt.Errorf("unable to create shell node "+
×
1094
                                "for: %x", edge.NodeKey2Bytes)
×
1095
                }
×
1096
        case node2Err != nil:
×
1097
                return err
×
1098
        }
1099

1100
        // If the edge hasn't been created yet, then we'll first add it to the
1101
        // edge index in order to associate the edge between two nodes and also
1102
        // store the static components of the channel.
1103
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
1,469✔
1104
                return err
×
1105
        }
×
1106

1107
        // Mark edge policies for both sides as unknown. This is to enable
1108
        // efficient incoming channel lookup for a node.
1109
        keys := []*[33]byte{
1,469✔
1110
                &edge.NodeKey1Bytes,
1,469✔
1111
                &edge.NodeKey2Bytes,
1,469✔
1112
        }
1,469✔
1113
        for _, key := range keys {
4,404✔
1114
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,935✔
1115
                if err != nil {
2,935✔
1116
                        return err
×
1117
                }
×
1118
        }
1119

1120
        // Finally we add it to the channel index which maps channel points
1121
        // (outpoints) to the shorter channel ID's.
1122
        var b bytes.Buffer
1,469✔
1123
        if err := writeOutpoint(&b, &edge.ChannelPoint); err != nil {
1,469✔
1124
                return err
×
1125
        }
×
1126
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,469✔
1127
}
1128

1129
// HasChannelEdge returns true if the database knows of a channel edge with the
1130
// passed channel ID, and false otherwise. If an edge with that ID is found
1131
// within the graph, then two time stamps representing the last time the edge
1132
// was updated for both directed edges are returned along with the boolean. If
1133
// it is not found, then the zombie index is checked and its result is returned
1134
// as the second boolean.
1135
func (c *ChannelGraph) HasChannelEdge(
1136
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
219✔
1137

219✔
1138
        var (
219✔
1139
                upd1Time time.Time
219✔
1140
                upd2Time time.Time
219✔
1141
                exists   bool
219✔
1142
                isZombie bool
219✔
1143
        )
219✔
1144

219✔
1145
        // We'll query the cache with the shared lock held to allow multiple
219✔
1146
        // readers to access values in the cache concurrently if they exist.
219✔
1147
        c.cacheMu.RLock()
219✔
1148
        if entry, ok := c.rejectCache.get(chanID); ok {
291✔
1149
                c.cacheMu.RUnlock()
72✔
1150
                upd1Time = time.Unix(entry.upd1Time, 0)
72✔
1151
                upd2Time = time.Unix(entry.upd2Time, 0)
72✔
1152
                exists, isZombie = entry.flags.unpack()
72✔
1153
                return upd1Time, upd2Time, exists, isZombie, nil
72✔
1154
        }
72✔
1155
        c.cacheMu.RUnlock()
150✔
1156

150✔
1157
        c.cacheMu.Lock()
150✔
1158
        defer c.cacheMu.Unlock()
150✔
1159

150✔
1160
        // The item was not found with the shared lock, so we'll acquire the
150✔
1161
        // exclusive lock and check the cache again in case another method added
150✔
1162
        // the entry to the cache while no lock was held.
150✔
1163
        if entry, ok := c.rejectCache.get(chanID); ok {
162✔
1164
                upd1Time = time.Unix(entry.upd1Time, 0)
12✔
1165
                upd2Time = time.Unix(entry.upd2Time, 0)
12✔
1166
                exists, isZombie = entry.flags.unpack()
12✔
1167
                return upd1Time, upd2Time, exists, isZombie, nil
12✔
1168
        }
12✔
1169

1170
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
282✔
1171
                edges := tx.ReadBucket(edgeBucket)
141✔
1172
                if edges == nil {
141✔
1173
                        return ErrGraphNoEdgesFound
×
1174
                }
×
1175
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
141✔
1176
                if edgeIndex == nil {
141✔
1177
                        return ErrGraphNoEdgesFound
×
1178
                }
×
1179

1180
                var channelID [8]byte
141✔
1181
                byteOrder.PutUint64(channelID[:], chanID)
141✔
1182

141✔
1183
                // If the edge doesn't exist, then we'll also check our zombie
141✔
1184
                // index.
141✔
1185
                if edgeIndex.Get(channelID[:]) == nil {
236✔
1186
                        exists = false
95✔
1187
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
95✔
1188
                        if zombieIndex != nil {
190✔
1189
                                isZombie, _, _ = isZombieEdge(
95✔
1190
                                        zombieIndex, chanID,
95✔
1191
                                )
95✔
1192
                        }
95✔
1193

1194
                        return nil
95✔
1195
                }
1196

1197
                exists = true
49✔
1198
                isZombie = false
49✔
1199

49✔
1200
                // If the channel has been found in the graph, then retrieve
49✔
1201
                // the edges itself so we can return the last updated
49✔
1202
                // timestamps.
49✔
1203
                nodes := tx.ReadBucket(nodeBucket)
49✔
1204
                if nodes == nil {
49✔
1205
                        return ErrGraphNodeNotFound
×
1206
                }
×
1207

1208
                e1, e2, err := fetchChanEdgePolicies(
49✔
1209
                        edgeIndex, edges, channelID[:],
49✔
1210
                )
49✔
1211
                if err != nil {
49✔
1212
                        return err
×
1213
                }
×
1214

1215
                // As we may have only one of the edges populated, only set the
1216
                // update time if the edge was found in the database.
1217
                if e1 != nil {
70✔
1218
                        upd1Time = e1.LastUpdate
21✔
1219
                }
21✔
1220
                if e2 != nil {
68✔
1221
                        upd2Time = e2.LastUpdate
19✔
1222
                }
19✔
1223

1224
                return nil
49✔
1225
        }, func() {}); err != nil {
141✔
1226
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1227
        }
×
1228

1229
        c.rejectCache.insert(chanID, rejectCacheEntry{
141✔
1230
                upd1Time: upd1Time.Unix(),
141✔
1231
                upd2Time: upd2Time.Unix(),
141✔
1232
                flags:    packRejectFlags(exists, isZombie),
141✔
1233
        })
141✔
1234

141✔
1235
        return upd1Time, upd2Time, exists, isZombie, nil
141✔
1236
}
1237

1238
// UpdateChannelEdge retrieves and update edge of the graph database. Method
1239
// only reserved for updating an edge info after its already been created.
1240
// In order to maintain this constraints, we return an error in the scenario
1241
// that an edge info hasn't yet been created yet, but someone attempts to update
1242
// it.
1243
func (c *ChannelGraph) UpdateChannelEdge(edge *models.ChannelEdgeInfo) error {
4✔
1244
        // Construct the channel's primary key which is the 8-byte channel ID.
4✔
1245
        var chanKey [8]byte
4✔
1246
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
4✔
1247

4✔
1248
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
8✔
1249
                edges := tx.ReadWriteBucket(edgeBucket)
4✔
1250
                if edge == nil {
4✔
1251
                        return ErrEdgeNotFound
×
1252
                }
×
1253

1254
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
4✔
1255
                if edgeIndex == nil {
4✔
1256
                        return ErrEdgeNotFound
×
1257
                }
×
1258

1259
                if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo == nil {
4✔
1260
                        return ErrEdgeNotFound
×
1261
                }
×
1262

1263
                if c.graphCache != nil {
8✔
1264
                        c.graphCache.UpdateChannel(edge)
4✔
1265
                }
4✔
1266

1267
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
4✔
1268
        }, func() {})
4✔
1269
}
1270

1271
const (
1272
        // pruneTipBytes is the total size of the value which stores a prune
1273
        // entry of the graph in the prune log. The "prune tip" is the last
1274
        // entry in the prune log, and indicates if the channel graph is in
1275
        // sync with the current UTXO state. The structure of the value
1276
        // is: blockHash, taking 32 bytes total.
1277
        pruneTipBytes = 32
1278
)
1279

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

244✔
1291
        c.cacheMu.Lock()
244✔
1292
        defer c.cacheMu.Unlock()
244✔
1293

244✔
1294
        var chansClosed []*models.ChannelEdgeInfo
244✔
1295

244✔
1296
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
488✔
1297
                // First grab the edges bucket which houses the information
244✔
1298
                // we'd like to delete
244✔
1299
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
244✔
1300
                if err != nil {
244✔
1301
                        return err
×
1302
                }
×
1303

1304
                // Next grab the two edge indexes which will also need to be updated.
1305
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
244✔
1306
                if err != nil {
244✔
1307
                        return err
×
1308
                }
×
1309
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
244✔
1310
                if err != nil {
244✔
1311
                        return err
×
1312
                }
×
1313
                nodes := tx.ReadWriteBucket(nodeBucket)
244✔
1314
                if nodes == nil {
244✔
1315
                        return ErrSourceNodeNotSet
×
1316
                }
×
1317
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
244✔
1318
                if err != nil {
244✔
1319
                        return err
×
1320
                }
×
1321

1322
                // For each of the outpoints that have been spent within the
1323
                // block, we attempt to delete them from the graph as if that
1324
                // outpoint was a channel, then it has now been closed.
1325
                for _, chanPoint := range spentOutputs {
373✔
1326
                        // TODO(roasbeef): load channel bloom filter, continue
129✔
1327
                        // if NOT if filter
129✔
1328

129✔
1329
                        var opBytes bytes.Buffer
129✔
1330
                        if err := writeOutpoint(&opBytes, chanPoint); err != nil {
129✔
1331
                                return err
×
1332
                        }
×
1333

1334
                        // First attempt to see if the channel exists within
1335
                        // the database, if not, then we can exit early.
1336
                        chanID := chanIndex.Get(opBytes.Bytes())
129✔
1337
                        if chanID == nil {
230✔
1338
                                continue
101✔
1339
                        }
1340

1341
                        // However, if it does, then we'll read out the full
1342
                        // version so we can add it to the set of deleted
1343
                        // channels.
1344
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
31✔
1345
                        if err != nil {
31✔
1346
                                return err
×
1347
                        }
×
1348

1349
                        // Attempt to delete the channel, an ErrEdgeNotFound
1350
                        // will be returned if that outpoint isn't known to be
1351
                        // a channel. If no error is returned, then a channel
1352
                        // was successfully pruned.
1353
                        err = c.delChannelEdgeUnsafe(
31✔
1354
                                edges, edgeIndex, chanIndex, zombieIndex,
31✔
1355
                                chanID, false, false,
31✔
1356
                        )
31✔
1357
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
31✔
1358
                                return err
×
1359
                        }
×
1360

1361
                        chansClosed = append(chansClosed, &edgeInfo)
31✔
1362
                }
1363

1364
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
244✔
1365
                if err != nil {
244✔
1366
                        return err
×
1367
                }
×
1368

1369
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
244✔
1370
                if err != nil {
244✔
1371
                        return err
×
1372
                }
×
1373

1374
                // With the graph pruned, add a new entry to the prune log,
1375
                // which can be used to check if the graph is fully synced with
1376
                // the current UTXO state.
1377
                var blockHeightBytes [4]byte
244✔
1378
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
244✔
1379

244✔
1380
                var newTip [pruneTipBytes]byte
244✔
1381
                copy(newTip[:], blockHash[:])
244✔
1382

244✔
1383
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
244✔
1384
                if err != nil {
244✔
1385
                        return err
×
1386
                }
×
1387

1388
                // Now that the graph has been pruned, we'll also attempt to
1389
                // prune any nodes that have had a channel closed within the
1390
                // latest block.
1391
                return c.pruneGraphNodes(nodes, edgeIndex)
244✔
1392
        }, func() {
244✔
1393
                chansClosed = nil
244✔
1394
        })
244✔
1395
        if err != nil {
244✔
1396
                return nil, err
×
1397
        }
×
1398

1399
        for _, channel := range chansClosed {
275✔
1400
                c.rejectCache.remove(channel.ChannelID)
31✔
1401
                c.chanCache.remove(channel.ChannelID)
31✔
1402
        }
31✔
1403

1404
        if c.graphCache != nil {
488✔
1405
                log.Debugf("Pruned graph, cache now has %s",
244✔
1406
                        c.graphCache.Stats())
244✔
1407
        }
244✔
1408

1409
        return chansClosed, nil
244✔
1410
}
1411

1412
// PruneGraphNodes is a garbage collection method which attempts to prune out
1413
// any nodes from the channel graph that are currently unconnected. This ensure
1414
// that we only maintain a graph of reachable nodes. In the event that a pruned
1415
// node gains more channels, it will be re-added back to the graph.
1416
func (c *ChannelGraph) PruneGraphNodes() error {
27✔
1417
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
54✔
1418
                nodes := tx.ReadWriteBucket(nodeBucket)
27✔
1419
                if nodes == nil {
27✔
1420
                        return ErrGraphNodesNotFound
×
1421
                }
×
1422
                edges := tx.ReadWriteBucket(edgeBucket)
27✔
1423
                if edges == nil {
27✔
1424
                        return ErrGraphNotFound
×
1425
                }
×
1426
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
27✔
1427
                if edgeIndex == nil {
27✔
1428
                        return ErrGraphNoEdgesFound
×
1429
                }
×
1430

1431
                return c.pruneGraphNodes(nodes, edgeIndex)
27✔
1432
        }, func() {})
27✔
1433
}
1434

1435
// pruneGraphNodes attempts to remove any nodes from the graph who have had a
1436
// channel closed within the current block. If the node still has existing
1437
// channels in the graph, this will act as a no-op.
1438
func (c *ChannelGraph) pruneGraphNodes(nodes kvdb.RwBucket,
1439
        edgeIndex kvdb.RwBucket) error {
268✔
1440

268✔
1441
        log.Trace("Pruning nodes from graph with no open channels")
268✔
1442

268✔
1443
        // We'll retrieve the graph's source node to ensure we don't remove it
268✔
1444
        // even if it no longer has any open channels.
268✔
1445
        sourceNode, err := c.sourceNode(nodes)
268✔
1446
        if err != nil {
268✔
1447
                return err
×
1448
        }
×
1449

1450
        // We'll use this map to keep count the number of references to a node
1451
        // in the graph. A node should only be removed once it has no more
1452
        // references in the graph.
1453
        nodeRefCounts := make(map[[33]byte]int)
268✔
1454
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,586✔
1455
                // If this is the source key, then we skip this
1,318✔
1456
                // iteration as the value for this key is a pubKey
1,318✔
1457
                // rather than raw node information.
1,318✔
1458
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
2,116✔
1459
                        return nil
798✔
1460
                }
798✔
1461

1462
                var nodePub [33]byte
523✔
1463
                copy(nodePub[:], pubKey)
523✔
1464
                nodeRefCounts[nodePub] = 0
523✔
1465

523✔
1466
                return nil
523✔
1467
        })
1468
        if err != nil {
268✔
1469
                return err
×
1470
        }
×
1471

1472
        // To ensure we never delete the source node, we'll start off by
1473
        // bumping its ref count to 1.
1474
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
268✔
1475

268✔
1476
        // Next, we'll run through the edgeIndex which maps a channel ID to the
268✔
1477
        // edge info. We'll use this scan to populate our reference count map
268✔
1478
        // above.
268✔
1479
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
483✔
1480
                // The first 66 bytes of the edge info contain the pubkeys of
215✔
1481
                // the nodes that this edge attaches. We'll extract them, and
215✔
1482
                // add them to the ref count map.
215✔
1483
                var node1, node2 [33]byte
215✔
1484
                copy(node1[:], edgeInfoBytes[:33])
215✔
1485
                copy(node2[:], edgeInfoBytes[33:])
215✔
1486

215✔
1487
                // With the nodes extracted, we'll increase the ref count of
215✔
1488
                // each of the nodes.
215✔
1489
                nodeRefCounts[node1]++
215✔
1490
                nodeRefCounts[node2]++
215✔
1491

215✔
1492
                return nil
215✔
1493
        })
215✔
1494
        if err != nil {
268✔
1495
                return err
×
1496
        }
×
1497

1498
        // Finally, we'll make a second pass over the set of nodes, and delete
1499
        // any nodes that have a ref count of zero.
1500
        var numNodesPruned int
268✔
1501
        for nodePubKey, refCount := range nodeRefCounts {
791✔
1502
                // If the ref count of the node isn't zero, then we can safely
523✔
1503
                // skip it as it still has edges to or from it within the
523✔
1504
                // graph.
523✔
1505
                if refCount != 0 {
981✔
1506
                        continue
458✔
1507
                }
1508

1509
                if c.graphCache != nil {
136✔
1510
                        c.graphCache.RemoveNode(nodePubKey)
68✔
1511
                }
68✔
1512

1513
                // If we reach this point, then there are no longer any edges
1514
                // that connect this node, so we can delete it.
1515
                if err := c.deleteLightningNode(nodes, nodePubKey[:]); err != nil {
68✔
1516
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1517
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1518

×
1519
                                log.Warnf("Unable to prune node %x from the "+
×
1520
                                        "graph: %v", nodePubKey, err)
×
1521
                                continue
×
1522
                        }
1523

1524
                        return err
×
1525
                }
1526

1527
                log.Infof("Pruned unconnected node %x from channel graph",
68✔
1528
                        nodePubKey[:])
68✔
1529

68✔
1530
                numNodesPruned++
68✔
1531
        }
1532

1533
        if numNodesPruned > 0 {
320✔
1534
                log.Infof("Pruned %v unconnected nodes from the channel graph",
52✔
1535
                        numNodesPruned)
52✔
1536
        }
52✔
1537

1538
        return nil
268✔
1539
}
1540

1541
// DisconnectBlockAtHeight is used to indicate that the block specified
1542
// by the passed height has been disconnected from the main chain. This
1543
// will "rewind" the graph back to the height below, deleting channels
1544
// that are no longer confirmed from the graph. The prune log will be
1545
// set to the last prune height valid for the remaining chain.
1546
// Channels that were removed from the graph resulting from the
1547
// disconnected block are returned.
1548
func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) (
1549
        []*models.ChannelEdgeInfo, error) {
158✔
1550

158✔
1551
        // Every channel having a ShortChannelID starting at 'height'
158✔
1552
        // will no longer be confirmed.
158✔
1553
        startShortChanID := lnwire.ShortChannelID{
158✔
1554
                BlockHeight: height,
158✔
1555
        }
158✔
1556

158✔
1557
        // Delete everything after this height from the db up until the
158✔
1558
        // SCID alias range.
158✔
1559
        endShortChanID := aliasmgr.StartingAlias
158✔
1560

158✔
1561
        // The block height will be the 3 first bytes of the channel IDs.
158✔
1562
        var chanIDStart [8]byte
158✔
1563
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
158✔
1564
        var chanIDEnd [8]byte
158✔
1565
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
158✔
1566

158✔
1567
        c.cacheMu.Lock()
158✔
1568
        defer c.cacheMu.Unlock()
158✔
1569

158✔
1570
        // Keep track of the channels that are removed from the graph.
158✔
1571
        var removedChans []*models.ChannelEdgeInfo
158✔
1572

158✔
1573
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
316✔
1574
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
158✔
1575
                if err != nil {
158✔
1576
                        return err
×
1577
                }
×
1578
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
158✔
1579
                if err != nil {
158✔
1580
                        return err
×
1581
                }
×
1582
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
158✔
1583
                if err != nil {
158✔
1584
                        return err
×
1585
                }
×
1586
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
158✔
1587
                if err != nil {
158✔
1588
                        return err
×
1589
                }
×
1590

1591
                // Scan from chanIDStart to chanIDEnd, deleting every
1592
                // found edge.
1593
                // NOTE: we must delete the edges after the cursor loop, since
1594
                // modifying the bucket while traversing is not safe.
1595
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1596
                // so that the StartingAlias itself isn't deleted.
1597
                var keys [][]byte
158✔
1598
                cursor := edgeIndex.ReadWriteCursor()
158✔
1599

158✔
1600
                //nolint:lll
158✔
1601
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
158✔
1602
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
247✔
1603
                        edgeInfoReader := bytes.NewReader(v)
89✔
1604
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
89✔
1605
                        if err != nil {
89✔
1606
                                return err
×
1607
                        }
×
1608

1609
                        keys = append(keys, k)
89✔
1610
                        removedChans = append(removedChans, &edgeInfo)
89✔
1611
                }
1612

1613
                for _, k := range keys {
247✔
1614
                        err = c.delChannelEdgeUnsafe(
89✔
1615
                                edges, edgeIndex, chanIndex, zombieIndex,
89✔
1616
                                k, false, false,
89✔
1617
                        )
89✔
1618
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
89✔
1619
                                return err
×
1620
                        }
×
1621
                }
1622

1623
                // Delete all the entries in the prune log having a height
1624
                // greater or equal to the block disconnected.
1625
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
158✔
1626
                if err != nil {
158✔
1627
                        return err
×
1628
                }
×
1629

1630
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
158✔
1631
                if err != nil {
158✔
1632
                        return err
×
1633
                }
×
1634

1635
                var pruneKeyStart [4]byte
158✔
1636
                byteOrder.PutUint32(pruneKeyStart[:], height)
158✔
1637

158✔
1638
                var pruneKeyEnd [4]byte
158✔
1639
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
158✔
1640

158✔
1641
                // To avoid modifying the bucket while traversing, we delete
158✔
1642
                // the keys in a second loop.
158✔
1643
                var pruneKeys [][]byte
158✔
1644
                pruneCursor := pruneBucket.ReadWriteCursor()
158✔
1645
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
158✔
1646
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
259✔
1647

101✔
1648
                        pruneKeys = append(pruneKeys, k)
101✔
1649
                }
101✔
1650

1651
                for _, k := range pruneKeys {
259✔
1652
                        if err := pruneBucket.Delete(k); err != nil {
101✔
1653
                                return err
×
1654
                        }
×
1655
                }
1656

1657
                return nil
158✔
1658
        }, func() {
158✔
1659
                removedChans = nil
158✔
1660
        }); err != nil {
158✔
1661
                return nil, err
×
1662
        }
×
1663

1664
        for _, channel := range removedChans {
247✔
1665
                c.rejectCache.remove(channel.ChannelID)
89✔
1666
                c.chanCache.remove(channel.ChannelID)
89✔
1667
        }
89✔
1668

1669
        return removedChans, nil
158✔
1670
}
1671

1672
// PruneTip returns the block height and hash of the latest block that has been
1673
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1674
// to tell if the graph is currently in sync with the current best known UTXO
1675
// state.
1676
func (c *ChannelGraph) PruneTip() (*chainhash.Hash, uint32, error) {
58✔
1677
        var (
58✔
1678
                tipHash   chainhash.Hash
58✔
1679
                tipHeight uint32
58✔
1680
        )
58✔
1681

58✔
1682
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
116✔
1683
                graphMeta := tx.ReadBucket(graphMetaBucket)
58✔
1684
                if graphMeta == nil {
58✔
1685
                        return ErrGraphNotFound
×
1686
                }
×
1687
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
58✔
1688
                if pruneBucket == nil {
58✔
1689
                        return ErrGraphNeverPruned
×
1690
                }
×
1691

1692
                pruneCursor := pruneBucket.ReadCursor()
58✔
1693

58✔
1694
                // The prune key with the largest block height will be our
58✔
1695
                // prune tip.
58✔
1696
                k, v := pruneCursor.Last()
58✔
1697
                if k == nil {
80✔
1698
                        return ErrGraphNeverPruned
22✔
1699
                }
22✔
1700

1701
                // Once we have the prune tip, the value will be the block hash,
1702
                // and the key the block height.
1703
                copy(tipHash[:], v[:])
39✔
1704
                tipHeight = byteOrder.Uint32(k[:])
39✔
1705

39✔
1706
                return nil
39✔
1707
        }, func() {})
58✔
1708
        if err != nil {
80✔
1709
                return nil, 0, err
22✔
1710
        }
22✔
1711

1712
        return &tipHash, tipHeight, nil
39✔
1713
}
1714

1715
// DeleteChannelEdges removes edges with the given channel IDs from the
1716
// database and marks them as zombies. This ensures that we're unable to re-add
1717
// it to our database once again. If an edge does not exist within the
1718
// database, then ErrEdgeNotFound will be returned. If strictZombiePruning is
1719
// true, then when we mark these edges as zombies, we'll set up the keys such
1720
// that we require the node that failed to send the fresh update to be the one
1721
// that resurrects the channel from its zombie state. The markZombie bool
1722
// denotes whether or not to mark the channel as a zombie.
1723
func (c *ChannelGraph) DeleteChannelEdges(strictZombiePruning, markZombie bool,
1724
        chanIDs ...uint64) error {
150✔
1725

150✔
1726
        // TODO(roasbeef): possibly delete from node bucket if node has no more
150✔
1727
        // channels
150✔
1728
        // TODO(roasbeef): don't delete both edges?
150✔
1729

150✔
1730
        c.cacheMu.Lock()
150✔
1731
        defer c.cacheMu.Unlock()
150✔
1732

150✔
1733
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
300✔
1734
                edges := tx.ReadWriteBucket(edgeBucket)
150✔
1735
                if edges == nil {
150✔
1736
                        return ErrEdgeNotFound
×
1737
                }
×
1738
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
150✔
1739
                if edgeIndex == nil {
150✔
1740
                        return ErrEdgeNotFound
×
1741
                }
×
1742
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
150✔
1743
                if chanIndex == nil {
150✔
1744
                        return ErrEdgeNotFound
×
1745
                }
×
1746
                nodes := tx.ReadWriteBucket(nodeBucket)
150✔
1747
                if nodes == nil {
150✔
1748
                        return ErrGraphNodeNotFound
×
1749
                }
×
1750
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
150✔
1751
                if err != nil {
150✔
1752
                        return err
×
1753
                }
×
1754

1755
                var rawChanID [8]byte
150✔
1756
                for _, chanID := range chanIDs {
243✔
1757
                        byteOrder.PutUint64(rawChanID[:], chanID)
93✔
1758
                        err := c.delChannelEdgeUnsafe(
93✔
1759
                                edges, edgeIndex, chanIndex, zombieIndex,
93✔
1760
                                rawChanID[:], markZombie, strictZombiePruning,
93✔
1761
                        )
93✔
1762
                        if err != nil {
157✔
1763
                                return err
64✔
1764
                        }
64✔
1765
                }
1766

1767
                return nil
86✔
1768
        }, func() {})
150✔
1769
        if err != nil {
214✔
1770
                return err
64✔
1771
        }
64✔
1772

1773
        for _, chanID := range chanIDs {
115✔
1774
                c.rejectCache.remove(chanID)
29✔
1775
                c.chanCache.remove(chanID)
29✔
1776
        }
29✔
1777

1778
        return nil
86✔
1779
}
1780

1781
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1782
// passed channel point (outpoint). If the passed channel doesn't exist within
1783
// the database, then ErrEdgeNotFound is returned.
1784
func (c *ChannelGraph) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
4✔
1785
        var chanID uint64
4✔
1786
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
1787
                var err error
4✔
1788
                chanID, err = getChanID(tx, chanPoint)
4✔
1789
                return err
4✔
1790
        }, func() {
8✔
1791
                chanID = 0
4✔
1792
        }); err != nil {
7✔
1793
                return 0, err
3✔
1794
        }
3✔
1795

1796
        return chanID, nil
4✔
1797
}
1798

1799
// getChanID returns the assigned channel ID for a given channel point.
1800
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
4✔
1801
        var b bytes.Buffer
4✔
1802
        if err := writeOutpoint(&b, chanPoint); err != nil {
4✔
1803
                return 0, err
×
1804
        }
×
1805

1806
        edges := tx.ReadBucket(edgeBucket)
4✔
1807
        if edges == nil {
4✔
1808
                return 0, ErrGraphNoEdgesFound
×
1809
        }
×
1810
        chanIndex := edges.NestedReadBucket(channelPointBucket)
4✔
1811
        if chanIndex == nil {
4✔
1812
                return 0, ErrGraphNoEdgesFound
×
1813
        }
×
1814

1815
        chanIDBytes := chanIndex.Get(b.Bytes())
4✔
1816
        if chanIDBytes == nil {
7✔
1817
                return 0, ErrEdgeNotFound
3✔
1818
        }
3✔
1819

1820
        chanID := byteOrder.Uint64(chanIDBytes)
4✔
1821

4✔
1822
        return chanID, nil
4✔
1823
}
1824

1825
// TODO(roasbeef): allow updates to use Batch?
1826

1827
// HighestChanID returns the "highest" known channel ID in the channel graph.
1828
// This represents the "newest" channel from the PoV of the chain. This method
1829
// can be used by peers to quickly determine if they're graphs are in sync.
1830
func (c *ChannelGraph) HighestChanID() (uint64, error) {
6✔
1831
        var cid uint64
6✔
1832

6✔
1833
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
1834
                edges := tx.ReadBucket(edgeBucket)
6✔
1835
                if edges == nil {
6✔
1836
                        return ErrGraphNoEdgesFound
×
1837
                }
×
1838
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
6✔
1839
                if edgeIndex == nil {
6✔
1840
                        return ErrGraphNoEdgesFound
×
1841
                }
×
1842

1843
                // In order to find the highest chan ID, we'll fetch a cursor
1844
                // and use that to seek to the "end" of our known rage.
1845
                cidCursor := edgeIndex.ReadCursor()
6✔
1846

6✔
1847
                lastChanID, _ := cidCursor.Last()
6✔
1848

6✔
1849
                // If there's no key, then this means that we don't actually
6✔
1850
                // know of any channels, so we'll return a predicable error.
6✔
1851
                if lastChanID == nil {
10✔
1852
                        return ErrGraphNoEdgesFound
4✔
1853
                }
4✔
1854

1855
                // Otherwise, we'll de serialize the channel ID and return it
1856
                // to the caller.
1857
                cid = byteOrder.Uint64(lastChanID)
5✔
1858
                return nil
5✔
1859
        }, func() {
6✔
1860
                cid = 0
6✔
1861
        })
6✔
1862
        if err != nil && err != ErrGraphNoEdgesFound {
6✔
1863
                return 0, err
×
1864
        }
×
1865

1866
        return cid, nil
6✔
1867
}
1868

1869
// ChannelEdge represents the complete set of information for a channel edge in
1870
// the known channel graph. This struct couples the core information of the
1871
// edge as well as each of the known advertised edge policies.
1872
type ChannelEdge struct {
1873
        // Info contains all the static information describing the channel.
1874
        Info *models.ChannelEdgeInfo
1875

1876
        // Policy1 points to the "first" edge policy of the channel containing
1877
        // the dynamic information required to properly route through the edge.
1878
        Policy1 *models.ChannelEdgePolicy
1879

1880
        // Policy2 points to the "second" edge policy of the channel containing
1881
        // the dynamic information required to properly route through the edge.
1882
        Policy2 *models.ChannelEdgePolicy
1883

1884
        // Node1 is "node 1" in the channel. This is the node that would have
1885
        // produced Policy1 if it exists.
1886
        Node1 *LightningNode
1887

1888
        // Node2 is "node 2" in the channel. This is the node that would have
1889
        // produced Policy2 if it exists.
1890
        Node2 *LightningNode
1891
}
1892

1893
// ChanUpdatesInHorizon returns all the known channel edges which have at least
1894
// one edge that has an update timestamp within the specified horizon.
1895
func (c *ChannelGraph) ChanUpdatesInHorizon(startTime,
1896
        endTime time.Time) ([]ChannelEdge, error) {
139✔
1897

139✔
1898
        // To ensure we don't return duplicate ChannelEdges, we'll use an
139✔
1899
        // additional map to keep track of the edges already seen to prevent
139✔
1900
        // re-adding it.
139✔
1901
        var edgesSeen map[uint64]struct{}
139✔
1902
        var edgesToCache map[uint64]ChannelEdge
139✔
1903
        var edgesInHorizon []ChannelEdge
139✔
1904

139✔
1905
        c.cacheMu.Lock()
139✔
1906
        defer c.cacheMu.Unlock()
139✔
1907

139✔
1908
        var hits int
139✔
1909
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
278✔
1910
                edges := tx.ReadBucket(edgeBucket)
139✔
1911
                if edges == nil {
139✔
1912
                        return ErrGraphNoEdgesFound
×
1913
                }
×
1914
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
139✔
1915
                if edgeIndex == nil {
139✔
1916
                        return ErrGraphNoEdgesFound
×
1917
                }
×
1918
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
139✔
1919
                if edgeUpdateIndex == nil {
139✔
1920
                        return ErrGraphNoEdgesFound
×
1921
                }
×
1922

1923
                nodes := tx.ReadBucket(nodeBucket)
139✔
1924
                if nodes == nil {
139✔
1925
                        return ErrGraphNodesNotFound
×
1926
                }
×
1927

1928
                // We'll now obtain a cursor to perform a range query within
1929
                // the index to find all channels within the horizon.
1930
                updateCursor := edgeUpdateIndex.ReadCursor()
139✔
1931

139✔
1932
                var startTimeBytes, endTimeBytes [8 + 8]byte
139✔
1933
                byteOrder.PutUint64(
139✔
1934
                        startTimeBytes[:8], uint64(startTime.Unix()),
139✔
1935
                )
139✔
1936
                byteOrder.PutUint64(
139✔
1937
                        endTimeBytes[:8], uint64(endTime.Unix()),
139✔
1938
                )
139✔
1939

139✔
1940
                // With our start and end times constructed, we'll step through
139✔
1941
                // the index collecting the info and policy of each update of
139✔
1942
                // each channel that has a last update within the time range.
139✔
1943
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
139✔
1944
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
188✔
1945

49✔
1946
                        // We have a new eligible entry, so we'll slice of the
49✔
1947
                        // chan ID so we can query it in the DB.
49✔
1948
                        chanID := indexKey[8:]
49✔
1949

49✔
1950
                        // If we've already retrieved the info and policies for
49✔
1951
                        // this edge, then we can skip it as we don't need to do
49✔
1952
                        // so again.
49✔
1953
                        chanIDInt := byteOrder.Uint64(chanID)
49✔
1954
                        if _, ok := edgesSeen[chanIDInt]; ok {
68✔
1955
                                continue
19✔
1956
                        }
1957

1958
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
42✔
1959
                                hits++
12✔
1960
                                edgesSeen[chanIDInt] = struct{}{}
12✔
1961
                                edgesInHorizon = append(edgesInHorizon, channel)
12✔
1962
                                continue
12✔
1963
                        }
1964

1965
                        // First, we'll fetch the static edge information.
1966
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
21✔
1967
                        if err != nil {
21✔
1968
                                chanID := byteOrder.Uint64(chanID)
×
1969
                                return fmt.Errorf("unable to fetch info for "+
×
1970
                                        "edge with chan_id=%v: %v", chanID, err)
×
1971
                        }
×
1972

1973
                        // With the static information obtained, we'll now
1974
                        // fetch the dynamic policy info.
1975
                        edge1, edge2, err := fetchChanEdgePolicies(
21✔
1976
                                edgeIndex, edges, chanID,
21✔
1977
                        )
21✔
1978
                        if err != nil {
21✔
1979
                                chanID := byteOrder.Uint64(chanID)
×
1980
                                return fmt.Errorf("unable to fetch policies "+
×
1981
                                        "for edge with chan_id=%v: %v", chanID,
×
1982
                                        err)
×
1983
                        }
×
1984

1985
                        node1, err := fetchLightningNode(
21✔
1986
                                nodes, edgeInfo.NodeKey1Bytes[:],
21✔
1987
                        )
21✔
1988
                        if err != nil {
21✔
1989
                                return err
×
1990
                        }
×
1991

1992
                        node2, err := fetchLightningNode(
21✔
1993
                                nodes, edgeInfo.NodeKey2Bytes[:],
21✔
1994
                        )
21✔
1995
                        if err != nil {
21✔
1996
                                return err
×
1997
                        }
×
1998

1999
                        // Finally, we'll collate this edge with the rest of
2000
                        // edges to be returned.
2001
                        edgesSeen[chanIDInt] = struct{}{}
21✔
2002
                        channel := ChannelEdge{
21✔
2003
                                Info:    &edgeInfo,
21✔
2004
                                Policy1: edge1,
21✔
2005
                                Policy2: edge2,
21✔
2006
                                Node1:   &node1,
21✔
2007
                                Node2:   &node2,
21✔
2008
                        }
21✔
2009
                        edgesInHorizon = append(edgesInHorizon, channel)
21✔
2010
                        edgesToCache[chanIDInt] = channel
21✔
2011
                }
2012

2013
                return nil
139✔
2014
        }, func() {
139✔
2015
                edgesSeen = make(map[uint64]struct{})
139✔
2016
                edgesToCache = make(map[uint64]ChannelEdge)
139✔
2017
                edgesInHorizon = nil
139✔
2018
        })
139✔
2019
        switch {
139✔
2020
        case err == ErrGraphNoEdgesFound:
×
2021
                fallthrough
×
2022
        case err == ErrGraphNodesNotFound:
×
2023
                break
×
2024

2025
        case err != nil:
×
2026
                return nil, err
×
2027
        }
2028

2029
        // Insert any edges loaded from disk into the cache.
2030
        for chanid, channel := range edgesToCache {
160✔
2031
                c.chanCache.insert(chanid, channel)
21✔
2032
        }
21✔
2033

2034
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
139✔
2035
                float64(hits)/float64(len(edgesInHorizon)), hits,
139✔
2036
                len(edgesInHorizon))
139✔
2037

139✔
2038
        return edgesInHorizon, nil
139✔
2039
}
2040

2041
// NodeUpdatesInHorizon returns all the known lightning node which have an
2042
// update timestamp within the passed range. This method can be used by two
2043
// nodes to quickly determine if they have the same set of up to date node
2044
// announcements.
2045
func (c *ChannelGraph) NodeUpdatesInHorizon(startTime,
2046
        endTime time.Time) ([]LightningNode, error) {
11✔
2047

11✔
2048
        var nodesInHorizon []LightningNode
11✔
2049

11✔
2050
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
22✔
2051
                nodes := tx.ReadBucket(nodeBucket)
11✔
2052
                if nodes == nil {
11✔
2053
                        return ErrGraphNodesNotFound
×
2054
                }
×
2055

2056
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
11✔
2057
                if nodeUpdateIndex == nil {
11✔
2058
                        return ErrGraphNodesNotFound
×
2059
                }
×
2060

2061
                // We'll now obtain a cursor to perform a range query within
2062
                // the index to find all node announcements within the horizon.
2063
                updateCursor := nodeUpdateIndex.ReadCursor()
11✔
2064

11✔
2065
                var startTimeBytes, endTimeBytes [8 + 33]byte
11✔
2066
                byteOrder.PutUint64(
11✔
2067
                        startTimeBytes[:8], uint64(startTime.Unix()),
11✔
2068
                )
11✔
2069
                byteOrder.PutUint64(
11✔
2070
                        endTimeBytes[:8], uint64(endTime.Unix()),
11✔
2071
                )
11✔
2072

11✔
2073
                // With our start and end times constructed, we'll step through
11✔
2074
                // the index collecting info for each node within the time
11✔
2075
                // range.
11✔
2076
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
11✔
2077
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
43✔
2078

32✔
2079
                        nodePub := indexKey[8:]
32✔
2080
                        node, err := fetchLightningNode(nodes, nodePub)
32✔
2081
                        if err != nil {
32✔
2082
                                return err
×
2083
                        }
×
2084

2085
                        nodesInHorizon = append(nodesInHorizon, node)
32✔
2086
                }
2087

2088
                return nil
11✔
2089
        }, func() {
11✔
2090
                nodesInHorizon = nil
11✔
2091
        })
11✔
2092
        switch {
11✔
2093
        case err == ErrGraphNoEdgesFound:
×
2094
                fallthrough
×
2095
        case err == ErrGraphNodesNotFound:
×
2096
                break
×
2097

2098
        case err != nil:
×
2099
                return nil, err
×
2100
        }
2101

2102
        return nodesInHorizon, nil
11✔
2103
}
2104

2105
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2106
// ID's that we don't know and are not known zombies of the passed set. In other
2107
// words, we perform a set difference of our set of chan ID's and the ones
2108
// passed in. This method can be used by callers to determine the set of
2109
// channels another peer knows of that we don't.
2110
func (c *ChannelGraph) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo,
2111
        isZombieChan func(time.Time, time.Time) bool) ([]uint64, error) {
122✔
2112

122✔
2113
        var newChanIDs []uint64
122✔
2114

122✔
2115
        // isStale returns whether the timestamp is too far into the past.
122✔
2116
        isStale := func(timestamp time.Time) bool {
345✔
2117
                return time.Since(timestamp) > ChannelUpdateExpiryPeriod
223✔
2118
        }
223✔
2119

2120
        // isSkewed returns whether the timestamp is too far into the future.
2121
        isSkewed := func(timestamp time.Time) bool {
149✔
2122
                return time.Until(timestamp) > ChannelUpdateExpiryPeriod
27✔
2123
        }
27✔
2124

2125
        // Sort out all channels with outdated or skewed timestamps. Both
2126
        // update msges need to be out of boundaries for us to skip it.
2127
        var cleanedChansInfo []ChannelUpdateInfo
122✔
2128
        for _, info := range chansInfo {
226✔
2129
                switch {
104✔
2130
                case isStale(info.Node1UpdateTimestamp) &&
2131
                        isStale(info.Node2UpdateTimestamp):
81✔
2132

81✔
2133
                        continue
81✔
2134

2135
                case isSkewed(info.Node1UpdateTimestamp) &&
2136
                        isSkewed(info.Node2UpdateTimestamp):
1✔
2137

1✔
2138
                        continue
1✔
2139

2140
                case isStale(info.Node1UpdateTimestamp) &&
2141
                        isSkewed(info.Node2UpdateTimestamp):
1✔
2142

1✔
2143
                        continue
1✔
2144

2145
                case isStale(info.Node2UpdateTimestamp) &&
2146
                        isSkewed(info.Node1UpdateTimestamp):
1✔
2147

1✔
2148
                        continue
1✔
2149
                }
2150

2151
                cleanedChansInfo = append(cleanedChansInfo, info)
20✔
2152
        }
2153

2154
        c.cacheMu.Lock()
122✔
2155
        defer c.cacheMu.Unlock()
122✔
2156

122✔
2157
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
244✔
2158
                edges := tx.ReadBucket(edgeBucket)
122✔
2159
                if edges == nil {
122✔
2160
                        return ErrGraphNoEdgesFound
×
2161
                }
×
2162
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
122✔
2163
                if edgeIndex == nil {
122✔
2164
                        return ErrGraphNoEdgesFound
×
2165
                }
×
2166

2167
                // Fetch the zombie index, it may not exist if no edges have
2168
                // ever been marked as zombies. If the index has been
2169
                // initialized, we will use it later to skip known zombie edges.
2170
                zombieIndex := edges.NestedReadBucket(zombieBucket)
122✔
2171

122✔
2172
                // We'll run through the set of chanIDs and collate only the
122✔
2173
                // set of channel that are unable to be found within our db.
122✔
2174
                var cidBytes [8]byte
122✔
2175
                for _, info := range cleanedChansInfo {
142✔
2176
                        scid := info.ShortChannelID.ToUint64()
20✔
2177
                        byteOrder.PutUint64(cidBytes[:], scid)
20✔
2178

20✔
2179
                        // If the edge is already known, skip it.
20✔
2180
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
33✔
2181
                                continue
13✔
2182
                        }
2183

2184
                        // If the edge is a known zombie, skip it.
2185
                        if zombieIndex != nil {
20✔
2186
                                isZombie, _, _ := isZombieEdge(
10✔
2187
                                        zombieIndex, scid,
10✔
2188
                                )
10✔
2189

10✔
2190
                                // TODO(ziggie): Make sure that for the strict
10✔
2191
                                // pruning case we compare the pubkeys and
10✔
2192
                                // whether the right timestamp is not older than
10✔
2193
                                // the `ChannelPruneExpiry`.
10✔
2194
                                //
10✔
2195
                                // NOTE: The timestamp data has no verification
10✔
2196
                                // attached to it in the `ReplyChannelRange` msg
10✔
2197
                                // so we are trusting this data at this point.
10✔
2198
                                // However it is not critical because we are
10✔
2199
                                // just removing the channel from the db when
10✔
2200
                                // the timestamps are more recent. During the
10✔
2201
                                // querying of the gossip msg verification
10✔
2202
                                // happens as usual.
10✔
2203
                                // However we should start punishing peers when
10✔
2204
                                // they don't provide us honest data ?
10✔
2205
                                isStillZombie := isZombieChan(
10✔
2206
                                        info.Node1UpdateTimestamp,
10✔
2207
                                        info.Node2UpdateTimestamp,
10✔
2208
                                )
10✔
2209

10✔
2210
                                switch {
10✔
2211
                                // If the edge is a known zombie and if we
2212
                                // would still consider it a zombie given the
2213
                                // latest update timestamps, then we skip this
2214
                                // channel.
UNCOV
2215
                                case isZombie && isStillZombie:
×
UNCOV
2216
                                        continue
×
2217

2218
                                // Otherwise, if we have marked it as a zombie
2219
                                // but the latest update timestamps could bring
2220
                                // it back from the dead, then we mark it alive,
2221
                                // and we let it be added to the set of IDs to
2222
                                // query our peer for.
UNCOV
2223
                                case isZombie && !isStillZombie:
×
UNCOV
2224
                                        err := c.markEdgeLiveUnsafe(tx, scid)
×
UNCOV
2225
                                        if err != nil {
×
2226
                                                return err
×
2227
                                        }
×
2228
                                }
2229
                        }
2230

2231
                        newChanIDs = append(newChanIDs, scid)
10✔
2232
                }
2233

2234
                return nil
122✔
2235
        }, func() {
122✔
2236
                newChanIDs = nil
122✔
2237
        })
122✔
2238
        switch {
122✔
2239
        // If we don't know of any edges yet, then we'll return the entire set
2240
        // of chan IDs specified.
2241
        case err == ErrGraphNoEdgesFound:
×
2242
                ogChanIDs := make([]uint64, len(chansInfo))
×
2243
                for i, info := range chansInfo {
×
2244
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2245
                }
×
2246

2247
                return ogChanIDs, nil
×
2248

2249
        case err != nil:
×
2250
                return nil, err
×
2251
        }
2252

2253
        return newChanIDs, nil
122✔
2254
}
2255

2256
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2257
// latest received channel updates for the channel.
2258
type ChannelUpdateInfo struct {
2259
        // ShortChannelID is the SCID identifier of the channel.
2260
        ShortChannelID lnwire.ShortChannelID
2261

2262
        // Node1UpdateTimestamp is the timestamp of the latest received update
2263
        // from the node 1 channel peer. This will be set to zero time if no
2264
        // update has yet been received from this node.
2265
        Node1UpdateTimestamp time.Time
2266

2267
        // Node2UpdateTimestamp is the timestamp of the latest received update
2268
        // from the node 2 channel peer. This will be set to zero time if no
2269
        // update has yet been received from this node.
2270
        Node2UpdateTimestamp time.Time
2271
}
2272

2273
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2274
// timestamps with zero seconds unix timestamp which equals
2275
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2276
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2277
        node2Timestamp time.Time) ChannelUpdateInfo {
47✔
2278

47✔
2279
        chanInfo := ChannelUpdateInfo{
47✔
2280
                ShortChannelID:       scid,
47✔
2281
                Node1UpdateTimestamp: node1Timestamp,
47✔
2282
                Node2UpdateTimestamp: node2Timestamp,
47✔
2283
        }
47✔
2284

47✔
2285
        if node1Timestamp.IsZero() {
94✔
2286
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
47✔
2287
        }
47✔
2288

2289
        if node2Timestamp.IsZero() {
94✔
2290
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
47✔
2291
        }
47✔
2292

2293
        return chanInfo
47✔
2294
}
2295

2296
// BlockChannelRange represents a range of channels for a given block height.
2297
type BlockChannelRange struct {
2298
        // Height is the height of the block all of the channels below were
2299
        // included in.
2300
        Height uint32
2301

2302
        // Channels is the list of channels identified by their short ID
2303
        // representation known to us that were included in the block height
2304
        // above. The list may include channel update timestamp information if
2305
        // requested.
2306
        Channels []ChannelUpdateInfo
2307
}
2308

2309
// FilterChannelRange returns the channel ID's of all known channels which were
2310
// mined in a block height within the passed range. The channel IDs are grouped
2311
// by their common block height. This method can be used to quickly share with a
2312
// peer the set of channels we know of within a particular range to catch them
2313
// up after a period of time offline. If withTimestamps is true then the
2314
// timestamp info of the latest received channel update messages of the channel
2315
// will be included in the response.
2316
func (c *ChannelGraph) FilterChannelRange(startHeight,
2317
        endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error) {
14✔
2318

14✔
2319
        startChanID := &lnwire.ShortChannelID{
14✔
2320
                BlockHeight: startHeight,
14✔
2321
        }
14✔
2322

14✔
2323
        endChanID := lnwire.ShortChannelID{
14✔
2324
                BlockHeight: endHeight,
14✔
2325
                TxIndex:     math.MaxUint32 & 0x00ffffff,
14✔
2326
                TxPosition:  math.MaxUint16,
14✔
2327
        }
14✔
2328

14✔
2329
        // As we need to perform a range scan, we'll convert the starting and
14✔
2330
        // ending height to their corresponding values when encoded using short
14✔
2331
        // channel ID's.
14✔
2332
        var chanIDStart, chanIDEnd [8]byte
14✔
2333
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
14✔
2334
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
14✔
2335

14✔
2336
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
14✔
2337
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
2338
                edges := tx.ReadBucket(edgeBucket)
14✔
2339
                if edges == nil {
14✔
2340
                        return ErrGraphNoEdgesFound
×
2341
                }
×
2342
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
2343
                if edgeIndex == nil {
14✔
2344
                        return ErrGraphNoEdgesFound
×
2345
                }
×
2346

2347
                cursor := edgeIndex.ReadCursor()
14✔
2348

14✔
2349
                // We'll now iterate through the database, and find each
14✔
2350
                // channel ID that resides within the specified range.
14✔
2351
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
14✔
2352
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
61✔
2353
                        // Don't send alias SCIDs during gossip sync.
47✔
2354
                        edgeReader := bytes.NewReader(v)
47✔
2355
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
47✔
2356
                        if err != nil {
47✔
2357
                                return err
×
2358
                        }
×
2359

2360
                        if edgeInfo.AuthProof == nil {
50✔
2361
                                continue
3✔
2362
                        }
2363

2364
                        // This channel ID rests within the target range, so
2365
                        // we'll add it to our returned set.
2366
                        rawCid := byteOrder.Uint64(k)
47✔
2367
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
47✔
2368

47✔
2369
                        chanInfo := NewChannelUpdateInfo(cid, time.Time{},
47✔
2370
                                time.Time{})
47✔
2371

47✔
2372
                        if !withTimestamps {
69✔
2373
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2374
                                        channelsPerBlock[cid.BlockHeight],
22✔
2375
                                        chanInfo,
22✔
2376
                                )
22✔
2377

22✔
2378
                                continue
22✔
2379
                        }
2380

2381
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
25✔
2382

25✔
2383
                        rawPolicy := edges.Get(node1Key)
25✔
2384
                        if len(rawPolicy) != 0 {
34✔
2385
                                r := bytes.NewReader(rawPolicy)
9✔
2386

9✔
2387
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2388
                                if err != nil && !errors.Is(
9✔
2389
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2390
                                ) {
9✔
2391

×
2392
                                        return err
×
2393
                                }
×
2394

2395
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2396
                        }
2397

2398
                        rawPolicy = edges.Get(node2Key)
25✔
2399
                        if len(rawPolicy) != 0 {
39✔
2400
                                r := bytes.NewReader(rawPolicy)
14✔
2401

14✔
2402
                                edge, err := deserializeChanEdgePolicyRaw(r)
14✔
2403
                                if err != nil && !errors.Is(
14✔
2404
                                        err, ErrEdgePolicyOptionalFieldNotFound,
14✔
2405
                                ) {
14✔
2406

×
2407
                                        return err
×
2408
                                }
×
2409

2410
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
14✔
2411
                        }
2412

2413
                        channelsPerBlock[cid.BlockHeight] = append(
25✔
2414
                                channelsPerBlock[cid.BlockHeight], chanInfo,
25✔
2415
                        )
25✔
2416
                }
2417

2418
                return nil
14✔
2419
        }, func() {
14✔
2420
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
14✔
2421
        })
14✔
2422

2423
        switch {
14✔
2424
        // If we don't know of any channels yet, then there's nothing to
2425
        // filter, so we'll return an empty slice.
2426
        case err == ErrGraphNoEdgesFound || len(channelsPerBlock) == 0:
6✔
2427
                return nil, nil
6✔
2428

2429
        case err != nil:
×
2430
                return nil, err
×
2431
        }
2432

2433
        // Return the channel ranges in ascending block height order.
2434
        blocks := make([]uint32, 0, len(channelsPerBlock))
11✔
2435
        for block := range channelsPerBlock {
36✔
2436
                blocks = append(blocks, block)
25✔
2437
        }
25✔
2438
        sort.Slice(blocks, func(i, j int) bool {
33✔
2439
                return blocks[i] < blocks[j]
22✔
2440
        })
22✔
2441

2442
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
11✔
2443
        for _, block := range blocks {
36✔
2444
                channelRanges = append(channelRanges, BlockChannelRange{
25✔
2445
                        Height:   block,
25✔
2446
                        Channels: channelsPerBlock[block],
25✔
2447
                })
25✔
2448
        }
25✔
2449

2450
        return channelRanges, nil
11✔
2451
}
2452

2453
// FetchChanInfos returns the set of channel edges that correspond to the passed
2454
// channel ID's. If an edge is the query is unknown to the database, it will
2455
// skipped and the result will contain only those edges that exist at the time
2456
// of the query. This can be used to respond to peer queries that are seeking to
2457
// fill in gaps in their view of the channel graph.
2458
func (c *ChannelGraph) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
6✔
2459
        return c.fetchChanInfos(nil, chanIDs)
6✔
2460
}
6✔
2461

2462
// fetchChanInfos returns the set of channel edges that correspond to the passed
2463
// channel ID's. If an edge is the query is unknown to the database, it will
2464
// skipped and the result will contain only those edges that exist at the time
2465
// of the query. This can be used to respond to peer queries that are seeking to
2466
// fill in gaps in their view of the channel graph.
2467
//
2468
// NOTE: An optional transaction may be provided. If none is provided, then a
2469
// new one will be created.
2470
func (c *ChannelGraph) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2471
        []ChannelEdge, error) {
7✔
2472
        // TODO(roasbeef): sort cids?
7✔
2473

7✔
2474
        var (
7✔
2475
                chanEdges []ChannelEdge
7✔
2476
                cidBytes  [8]byte
7✔
2477
        )
7✔
2478

7✔
2479
        fetchChanInfos := func(tx kvdb.RTx) error {
14✔
2480
                edges := tx.ReadBucket(edgeBucket)
7✔
2481
                if edges == nil {
7✔
2482
                        return ErrGraphNoEdgesFound
×
2483
                }
×
2484
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
7✔
2485
                if edgeIndex == nil {
7✔
2486
                        return ErrGraphNoEdgesFound
×
2487
                }
×
2488
                nodes := tx.ReadBucket(nodeBucket)
7✔
2489
                if nodes == nil {
7✔
2490
                        return ErrGraphNotFound
×
2491
                }
×
2492

2493
                for _, cid := range chanIDs {
21✔
2494
                        byteOrder.PutUint64(cidBytes[:], cid)
14✔
2495

14✔
2496
                        // First, we'll fetch the static edge information. If
14✔
2497
                        // the edge is unknown, we will skip the edge and
14✔
2498
                        // continue gathering all known edges.
14✔
2499
                        edgeInfo, err := fetchChanEdgeInfo(
14✔
2500
                                edgeIndex, cidBytes[:],
14✔
2501
                        )
14✔
2502
                        switch {
14✔
2503
                        case errors.Is(err, ErrEdgeNotFound):
6✔
2504
                                continue
6✔
2505
                        case err != nil:
×
2506
                                return err
×
2507
                        }
2508

2509
                        // With the static information obtained, we'll now
2510
                        // fetch the dynamic policy info.
2511
                        edge1, edge2, err := fetchChanEdgePolicies(
11✔
2512
                                edgeIndex, edges, cidBytes[:],
11✔
2513
                        )
11✔
2514
                        if err != nil {
11✔
2515
                                return err
×
2516
                        }
×
2517

2518
                        node1, err := fetchLightningNode(
11✔
2519
                                nodes, edgeInfo.NodeKey1Bytes[:],
11✔
2520
                        )
11✔
2521
                        if err != nil {
11✔
2522
                                return err
×
2523
                        }
×
2524

2525
                        node2, err := fetchLightningNode(
11✔
2526
                                nodes, edgeInfo.NodeKey2Bytes[:],
11✔
2527
                        )
11✔
2528
                        if err != nil {
11✔
2529
                                return err
×
2530
                        }
×
2531

2532
                        chanEdges = append(chanEdges, ChannelEdge{
11✔
2533
                                Info:    &edgeInfo,
11✔
2534
                                Policy1: edge1,
11✔
2535
                                Policy2: edge2,
11✔
2536
                                Node1:   &node1,
11✔
2537
                                Node2:   &node2,
11✔
2538
                        })
11✔
2539
                }
2540
                return nil
7✔
2541
        }
2542

2543
        if tx == nil {
14✔
2544
                err := kvdb.View(c.db, fetchChanInfos, func() {
14✔
2545
                        chanEdges = nil
7✔
2546
                })
7✔
2547
                if err != nil {
7✔
2548
                        return nil, err
×
2549
                }
×
2550

2551
                return chanEdges, nil
7✔
2552
        }
2553

UNCOV
2554
        err := fetchChanInfos(tx)
×
UNCOV
2555
        if err != nil {
×
2556
                return nil, err
×
2557
        }
×
2558

UNCOV
2559
        return chanEdges, nil
×
2560
}
2561

2562
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2563
        edge1, edge2 *models.ChannelEdgePolicy) error {
144✔
2564

144✔
2565
        // First, we'll fetch the edge update index bucket which currently
144✔
2566
        // stores an entry for the channel we're about to delete.
144✔
2567
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
144✔
2568
        if updateIndex == nil {
144✔
2569
                // No edges in bucket, return early.
×
2570
                return nil
×
2571
        }
×
2572

2573
        // Now that we have the bucket, we'll attempt to construct a template
2574
        // for the index key: updateTime || chanid.
2575
        var indexKey [8 + 8]byte
144✔
2576
        byteOrder.PutUint64(indexKey[8:], chanID)
144✔
2577

144✔
2578
        // With the template constructed, we'll attempt to delete an entry that
144✔
2579
        // would have been created by both edges: we'll alternate the update
144✔
2580
        // times, as one may had overridden the other.
144✔
2581
        if edge1 != nil {
157✔
2582
                byteOrder.PutUint64(indexKey[:8], uint64(edge1.LastUpdate.Unix()))
13✔
2583
                if err := updateIndex.Delete(indexKey[:]); err != nil {
13✔
2584
                        return err
×
2585
                }
×
2586
        }
2587

2588
        // We'll also attempt to delete the entry that may have been created by
2589
        // the second edge.
2590
        if edge2 != nil {
159✔
2591
                byteOrder.PutUint64(indexKey[:8], uint64(edge2.LastUpdate.Unix()))
15✔
2592
                if err := updateIndex.Delete(indexKey[:]); err != nil {
15✔
2593
                        return err
×
2594
                }
×
2595
        }
2596

2597
        return nil
144✔
2598
}
2599

2600
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2601
// cache. It then goes on to delete any policy info and edge info for this
2602
// channel from the DB and finally, if isZombie is true, it will add an entry
2603
// for this channel in the zombie index.
2604
//
2605
// NOTE: this method MUST only be called if the cacheMu has already been
2606
// acquired.
2607
func (c *ChannelGraph) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2608
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2609
        strictZombie bool) error {
208✔
2610

208✔
2611
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
208✔
2612
        if err != nil {
272✔
2613
                return err
64✔
2614
        }
64✔
2615

2616
        if c.graphCache != nil {
288✔
2617
                c.graphCache.RemoveChannel(
144✔
2618
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
144✔
2619
                        edgeInfo.ChannelID,
144✔
2620
                )
144✔
2621
        }
144✔
2622

2623
        // We'll also remove the entry in the edge update index bucket before
2624
        // we delete the edges themselves so we can access their last update
2625
        // times.
2626
        cid := byteOrder.Uint64(chanID)
144✔
2627
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
144✔
2628
        if err != nil {
144✔
2629
                return err
×
2630
        }
×
2631
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
144✔
2632
        if err != nil {
144✔
2633
                return err
×
2634
        }
×
2635

2636
        // The edge key is of the format pubKey || chanID. First we construct
2637
        // the latter half, populating the channel ID.
2638
        var edgeKey [33 + 8]byte
144✔
2639
        copy(edgeKey[33:], chanID)
144✔
2640

144✔
2641
        // With the latter half constructed, copy over the first public key to
144✔
2642
        // delete the edge in this direction, then the second to delete the
144✔
2643
        // edge in the opposite direction.
144✔
2644
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
144✔
2645
        if edges.Get(edgeKey[:]) != nil {
288✔
2646
                if err := edges.Delete(edgeKey[:]); err != nil {
144✔
2647
                        return err
×
2648
                }
×
2649
        }
2650
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
144✔
2651
        if edges.Get(edgeKey[:]) != nil {
288✔
2652
                if err := edges.Delete(edgeKey[:]); err != nil {
144✔
2653
                        return err
×
2654
                }
×
2655
        }
2656

2657
        // As part of deleting the edge we also remove all disabled entries
2658
        // from the edgePolicyDisabledIndex bucket. We do that for both directions.
2659
        updateEdgePolicyDisabledIndex(edges, cid, false, false)
144✔
2660
        updateEdgePolicyDisabledIndex(edges, cid, true, false)
144✔
2661

144✔
2662
        // With the edge data deleted, we can purge the information from the two
144✔
2663
        // edge indexes.
144✔
2664
        if err := edgeIndex.Delete(chanID); err != nil {
144✔
2665
                return err
×
2666
        }
×
2667
        var b bytes.Buffer
144✔
2668
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
144✔
2669
                return err
×
2670
        }
×
2671
        if err := chanIndex.Delete(b.Bytes()); err != nil {
144✔
2672
                return err
×
2673
        }
×
2674

2675
        // Finally, we'll mark the edge as a zombie within our index if it's
2676
        // being removed due to the channel becoming a zombie. We do this to
2677
        // ensure we don't store unnecessary data for spent channels.
2678
        if !isZombie {
264✔
2679
                return nil
120✔
2680
        }
120✔
2681

2682
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
27✔
2683
        if strictZombie {
30✔
2684
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2685
        }
3✔
2686

2687
        return markEdgeZombie(
27✔
2688
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
27✔
2689
        )
27✔
2690
}
2691

2692
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2693
// particular pair of channel policies. The return values are one of:
2694
//  1. (pubkey1, pubkey2)
2695
//  2. (pubkey1, blank)
2696
//  3. (blank, pubkey2)
2697
//
2698
// A blank pubkey means that corresponding node will be unable to resurrect a
2699
// channel on its own. For example, node1 may continue to publish recent
2700
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2701
// we don't want another fresh update from node1 to resurrect, as the edge can
2702
// only become live once node2 finally sends something recent.
2703
//
2704
// In the case where we have neither update, we allow either party to resurrect
2705
// the channel. If the channel were to be marked zombie again, it would be
2706
// marked with the correct lagging channel since we received an update from only
2707
// one side.
2708
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
2709
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
3✔
2710

3✔
2711
        switch {
3✔
2712
        // If we don't have either edge policy, we'll return both pubkeys so
2713
        // that the channel can be resurrected by either party.
2714
        case e1 == nil && e2 == nil:
×
2715
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2716

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

2724
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2725
        // return a blank pubkey for edge1. In this case, only an update from
2726
        // edge2 can resurect the channel.
2727
        default:
2✔
2728
                return [33]byte{}, info.NodeKey2Bytes
2✔
2729
        }
2730
}
2731

2732
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2733
// within the database for the referenced channel. The `flags` attribute within
2734
// the ChannelEdgePolicy determines which of the directed edges are being
2735
// updated. If the flag is 1, then the first node's information is being
2736
// updated, otherwise it's the second node's information. The node ordering is
2737
// determined by the lexicographical ordering of the identity public keys of the
2738
// nodes on either side of the channel.
2739
func (c *ChannelGraph) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2740
        op ...batch.SchedulerOption) error {
2,634✔
2741

2,634✔
2742
        var (
2,634✔
2743
                isUpdate1    bool
2,634✔
2744
                edgeNotFound bool
2,634✔
2745
        )
2,634✔
2746

2,634✔
2747
        r := &batch.Request{
2,634✔
2748
                Reset: func() {
5,268✔
2749
                        isUpdate1 = false
2,634✔
2750
                        edgeNotFound = false
2,634✔
2751
                },
2,634✔
2752
                Update: func(tx kvdb.RwTx) error {
2,634✔
2753
                        var err error
2,634✔
2754
                        isUpdate1, err = updateEdgePolicy(
2,634✔
2755
                                tx, edge, c.graphCache,
2,634✔
2756
                        )
2,634✔
2757

2,634✔
2758
                        // Silence ErrEdgeNotFound so that the batch can
2,634✔
2759
                        // succeed, but propagate the error via local state.
2,634✔
2760
                        if errors.Is(err, ErrEdgeNotFound) {
2,637✔
2761
                                edgeNotFound = true
3✔
2762
                                return nil
3✔
2763
                        }
3✔
2764

2765
                        return err
2,631✔
2766
                },
2767
                OnCommit: func(err error) error {
2,634✔
2768
                        switch {
2,634✔
2769
                        case err != nil:
×
2770
                                return err
×
2771
                        case edgeNotFound:
3✔
2772
                                return ErrEdgeNotFound
3✔
2773
                        default:
2,631✔
2774
                                c.updateEdgeCache(edge, isUpdate1)
2,631✔
2775
                                return nil
2,631✔
2776
                        }
2777
                },
2778
        }
2779

2780
        for _, f := range op {
2,637✔
2781
                f(r)
3✔
2782
        }
3✔
2783

2784
        return c.chanScheduler.Execute(r)
2,634✔
2785
}
2786

2787
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2788
        isUpdate1 bool) {
2,631✔
2789

2,631✔
2790
        // If an entry for this channel is found in reject cache, we'll modify
2,631✔
2791
        // the entry with the updated timestamp for the direction that was just
2,631✔
2792
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,631✔
2793
        // during the next query for this edge.
2,631✔
2794
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,639✔
2795
                if isUpdate1 {
14✔
2796
                        entry.upd1Time = e.LastUpdate.Unix()
6✔
2797
                } else {
11✔
2798
                        entry.upd2Time = e.LastUpdate.Unix()
5✔
2799
                }
5✔
2800
                c.rejectCache.insert(e.ChannelID, entry)
8✔
2801
        }
2802

2803
        // If an entry for this channel is found in channel cache, we'll modify
2804
        // the entry with the updated policy for the direction that was just
2805
        // written. If the edge doesn't exist, we'll defer loading the info and
2806
        // policies and lazily read from disk during the next query.
2807
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
2,634✔
2808
                if isUpdate1 {
6✔
2809
                        channel.Policy1 = e
3✔
2810
                } else {
6✔
2811
                        channel.Policy2 = e
3✔
2812
                }
3✔
2813
                c.chanCache.insert(e.ChannelID, channel)
3✔
2814
        }
2815
}
2816

2817
// updateEdgePolicy attempts to update an edge's policy within the relevant
2818
// buckets using an existing database transaction. The returned boolean will be
2819
// true if the updated policy belongs to node1, and false if the policy belonged
2820
// to node2.
2821
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy,
2822
        graphCache *GraphCache) (bool, error) {
2,634✔
2823

2,634✔
2824
        edges := tx.ReadWriteBucket(edgeBucket)
2,634✔
2825
        if edges == nil {
2,634✔
2826
                return false, ErrEdgeNotFound
×
2827
        }
×
2828
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,634✔
2829
        if edgeIndex == nil {
2,634✔
2830
                return false, ErrEdgeNotFound
×
2831
        }
×
2832

2833
        // Create the channelID key be converting the channel ID
2834
        // integer into a byte slice.
2835
        var chanID [8]byte
2,634✔
2836
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,634✔
2837

2,634✔
2838
        // With the channel ID, we then fetch the value storing the two
2,634✔
2839
        // nodes which connect this channel edge.
2,634✔
2840
        nodeInfo := edgeIndex.Get(chanID[:])
2,634✔
2841
        if nodeInfo == nil {
2,637✔
2842
                return false, ErrEdgeNotFound
3✔
2843
        }
3✔
2844

2845
        // Depending on the flags value passed above, either the first
2846
        // or second edge policy is being updated.
2847
        var fromNode, toNode []byte
2,631✔
2848
        var isUpdate1 bool
2,631✔
2849
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3,950✔
2850
                fromNode = nodeInfo[:33]
1,319✔
2851
                toNode = nodeInfo[33:66]
1,319✔
2852
                isUpdate1 = true
1,319✔
2853
        } else {
2,634✔
2854
                fromNode = nodeInfo[33:66]
1,315✔
2855
                toNode = nodeInfo[:33]
1,315✔
2856
                isUpdate1 = false
1,315✔
2857
        }
1,315✔
2858

2859
        // Finally, with the direction of the edge being updated
2860
        // identified, we update the on-disk edge representation.
2861
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,631✔
2862
        if err != nil {
2,631✔
2863
                return false, err
×
2864
        }
×
2865

2866
        var (
2,631✔
2867
                fromNodePubKey route.Vertex
2,631✔
2868
                toNodePubKey   route.Vertex
2,631✔
2869
        )
2,631✔
2870
        copy(fromNodePubKey[:], fromNode)
2,631✔
2871
        copy(toNodePubKey[:], toNode)
2,631✔
2872

2,631✔
2873
        if graphCache != nil {
4,892✔
2874
                graphCache.UpdatePolicy(
2,261✔
2875
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,261✔
2876
                )
2,261✔
2877
        }
2,261✔
2878

2879
        return isUpdate1, nil
2,631✔
2880
}
2881

2882
// LightningNode represents an individual vertex/node within the channel graph.
2883
// A node is connected to other nodes by one or more channel edges emanating
2884
// from it. As the graph is directed, a node will also have an incoming edge
2885
// attached to it for each outgoing edge.
2886
type LightningNode struct {
2887
        // PubKeyBytes is the raw bytes of the public key of the target node.
2888
        PubKeyBytes [33]byte
2889
        pubKey      *btcec.PublicKey
2890

2891
        // HaveNodeAnnouncement indicates whether we received a node
2892
        // announcement for this particular node. If true, the remaining fields
2893
        // will be set, if false only the PubKey is known for this node.
2894
        HaveNodeAnnouncement bool
2895

2896
        // LastUpdate is the last time the vertex information for this node has
2897
        // been updated.
2898
        LastUpdate time.Time
2899

2900
        // Address is the TCP address this node is reachable over.
2901
        Addresses []net.Addr
2902

2903
        // Color is the selected color for the node.
2904
        Color color.RGBA
2905

2906
        // Alias is a nick-name for the node. The alias can be used to confirm
2907
        // a node's identity or to serve as a short ID for an address book.
2908
        Alias string
2909

2910
        // AuthSigBytes is the raw signature under the advertised public key
2911
        // which serves to authenticate the attributes announced by this node.
2912
        AuthSigBytes []byte
2913

2914
        // Features is the list of protocol features supported by this node.
2915
        Features *lnwire.FeatureVector
2916

2917
        // ExtraOpaqueData is the set of data that was appended to this
2918
        // message, some of which we may not actually know how to iterate or
2919
        // parse. By holding onto this data, we ensure that we're able to
2920
        // properly validate the set of signatures that cover these new fields,
2921
        // and ensure we're able to make upgrades to the network in a forwards
2922
        // compatible manner.
2923
        ExtraOpaqueData []byte
2924

2925
        // TODO(roasbeef): discovery will need storage to keep it's last IP
2926
        // address and re-announce if interface changes?
2927

2928
        // TODO(roasbeef): add update method and fetch?
2929
}
2930

2931
// PubKey is the node's long-term identity public key. This key will be used to
2932
// authenticated any advertisements/updates sent by the node.
2933
//
2934
// NOTE: By having this method to access an attribute, we ensure we only need
2935
// to fully deserialize the pubkey if absolutely necessary.
2936
func (l *LightningNode) PubKey() (*btcec.PublicKey, error) {
1,465✔
2937
        if l.pubKey != nil {
1,953✔
2938
                return l.pubKey, nil
488✔
2939
        }
488✔
2940

2941
        key, err := btcec.ParsePubKey(l.PubKeyBytes[:])
980✔
2942
        if err != nil {
980✔
2943
                return nil, err
×
2944
        }
×
2945
        l.pubKey = key
980✔
2946

980✔
2947
        return key, nil
980✔
2948
}
2949

2950
// AuthSig is a signature under the advertised public key which serves to
2951
// authenticate the attributes announced by this node.
2952
//
2953
// NOTE: By having this method to access an attribute, we ensure we only need
2954
// to fully deserialize the signature if absolutely necessary.
2955
func (l *LightningNode) AuthSig() (*ecdsa.Signature, error) {
×
2956
        return ecdsa.ParseSignature(l.AuthSigBytes)
×
2957
}
×
2958

2959
// AddPubKey is a setter-link method that can be used to swap out the public
2960
// key for a node.
2961
func (l *LightningNode) AddPubKey(key *btcec.PublicKey) {
63✔
2962
        l.pubKey = key
63✔
2963
        copy(l.PubKeyBytes[:], key.SerializeCompressed())
63✔
2964
}
63✔
2965

2966
// NodeAnnouncement retrieves the latest node announcement of the node.
2967
func (l *LightningNode) NodeAnnouncement(signed bool) (*lnwire.NodeAnnouncement,
2968
        error) {
17✔
2969

17✔
2970
        if !l.HaveNodeAnnouncement {
20✔
2971
                return nil, fmt.Errorf("node does not have node announcement")
3✔
2972
        }
3✔
2973

2974
        alias, err := lnwire.NewNodeAlias(l.Alias)
17✔
2975
        if err != nil {
17✔
2976
                return nil, err
×
2977
        }
×
2978

2979
        nodeAnn := &lnwire.NodeAnnouncement{
17✔
2980
                Features:        l.Features.RawFeatureVector,
17✔
2981
                NodeID:          l.PubKeyBytes,
17✔
2982
                RGBColor:        l.Color,
17✔
2983
                Alias:           alias,
17✔
2984
                Addresses:       l.Addresses,
17✔
2985
                Timestamp:       uint32(l.LastUpdate.Unix()),
17✔
2986
                ExtraOpaqueData: l.ExtraOpaqueData,
17✔
2987
        }
17✔
2988

17✔
2989
        if !signed {
20✔
2990
                return nodeAnn, nil
3✔
2991
        }
3✔
2992

2993
        sig, err := lnwire.NewSigFromECDSARawSignature(l.AuthSigBytes)
17✔
2994
        if err != nil {
17✔
2995
                return nil, err
×
2996
        }
×
2997

2998
        nodeAnn.Signature = sig
17✔
2999

17✔
3000
        return nodeAnn, nil
17✔
3001
}
3002

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

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

13✔
3019
                // If this edge doesn't extend to the source node, we'll
13✔
3020
                // terminate our search as we can now conclude that the node is
13✔
3021
                // publicly advertised within the graph due to the local node
13✔
3022
                // knowing of the current edge.
13✔
3023
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
13✔
3024
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
19✔
3025

6✔
3026
                        nodeIsPublic = true
6✔
3027
                        return errDone
6✔
3028
                }
6✔
3029

3030
                // Since the edge _does_ extend to the source node, we'll also
3031
                // need to ensure that this is a public edge.
3032
                if info.AuthProof != nil {
19✔
3033
                        nodeIsPublic = true
9✔
3034
                        return errDone
9✔
3035
                }
9✔
3036

3037
                // Otherwise, we'll continue our search.
3038
                return nil
4✔
3039
        })
3040
        if err != nil && err != errDone {
16✔
3041
                return false, err
×
3042
        }
×
3043

3044
        return nodeIsPublic, nil
16✔
3045
}
3046

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

2,944✔
3054
        return c.fetchLightningNode(tx, nodePub)
2,944✔
3055
}
2,944✔
3056

3057
// FetchLightningNode attempts to look up a target node by its identity public
3058
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3059
// returned.
3060
func (c *ChannelGraph) FetchLightningNode(nodePub route.Vertex) (*LightningNode,
3061
        error) {
829✔
3062

829✔
3063
        return c.fetchLightningNode(nil, nodePub)
829✔
3064
}
829✔
3065

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

3,773✔
3073
        var node *LightningNode
3,773✔
3074
        fetch := func(tx kvdb.RTx) error {
7,546✔
3075
                // First grab the nodes bucket which stores the mapping from
3,773✔
3076
                // pubKey to node information.
3,773✔
3077
                nodes := tx.ReadBucket(nodeBucket)
3,773✔
3078
                if nodes == nil {
3,773✔
3079
                        return ErrGraphNotFound
×
3080
                }
×
3081

3082
                // If a key for this serialized public key isn't found, then
3083
                // the target node doesn't exist within the database.
3084
                nodeBytes := nodes.Get(nodePub[:])
3,773✔
3085
                if nodeBytes == nil {
3,784✔
3086
                        return ErrGraphNodeNotFound
11✔
3087
                }
11✔
3088

3089
                // If the node is found, then we can de deserialize the node
3090
                // information to return to the user.
3091
                nodeReader := bytes.NewReader(nodeBytes)
3,765✔
3092
                n, err := deserializeLightningNode(nodeReader)
3,765✔
3093
                if err != nil {
3,765✔
3094
                        return err
×
3095
                }
×
3096

3097
                node = &n
3,765✔
3098

3,765✔
3099
                return nil
3,765✔
3100
        }
3101

3102
        if tx == nil {
4,602✔
3103
                err := kvdb.View(
829✔
3104
                        c.db, fetch, func() {
1,658✔
3105
                                node = nil
829✔
3106
                        },
829✔
3107
                )
3108
                if err != nil {
840✔
3109
                        return nil, err
11✔
3110
                }
11✔
3111

3112
                return node, nil
821✔
3113
        }
3114

3115
        err := fetch(tx)
2,944✔
3116
        if err != nil {
2,944✔
3117
                return nil, err
×
3118
        }
×
3119

3120
        return node, nil
2,944✔
3121
}
3122

3123
// graphCacheNode is a struct that wraps a LightningNode in a way that it can be
3124
// cached in the graph cache.
3125
type graphCacheNode struct {
3126
        pubKeyBytes route.Vertex
3127
        features    *lnwire.FeatureVector
3128
}
3129

3130
// newGraphCacheNode returns a new cache optimized node.
3131
func newGraphCacheNode(pubKey route.Vertex,
3132
        features *lnwire.FeatureVector) *graphCacheNode {
728✔
3133

728✔
3134
        return &graphCacheNode{
728✔
3135
                pubKeyBytes: pubKey,
728✔
3136
                features:    features,
728✔
3137
        }
728✔
3138
}
728✔
3139

3140
// PubKey returns the node's public identity key.
3141
func (n *graphCacheNode) PubKey() route.Vertex {
728✔
3142
        return n.pubKeyBytes
728✔
3143
}
728✔
3144

3145
// Features returns the node's features.
3146
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
708✔
3147
        return n.features
708✔
3148
}
708✔
3149

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

628✔
3162
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
628✔
3163
}
628✔
3164

3165
var _ GraphCacheNode = (*graphCacheNode)(nil)
3166

3167
// HasLightningNode determines if the graph has a vertex identified by the
3168
// target node identity public key. If the node exists in the database, a
3169
// timestamp of when the data for the node was lasted updated is returned along
3170
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3171
// boolean.
3172
func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool, error) {
19✔
3173
        var (
19✔
3174
                updateTime time.Time
19✔
3175
                exists     bool
19✔
3176
        )
19✔
3177

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

3186
                // If a key for this serialized public key isn't found, we can
3187
                // exit early.
3188
                nodeBytes := nodes.Get(nodePub[:])
19✔
3189
                if nodeBytes == nil {
25✔
3190
                        exists = false
6✔
3191
                        return nil
6✔
3192
                }
6✔
3193

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

3203
                exists = true
16✔
3204
                updateTime = node.LastUpdate
16✔
3205
                return nil
16✔
3206
        }, func() {
19✔
3207
                updateTime = time.Time{}
19✔
3208
                exists = false
19✔
3209
        })
19✔
3210
        if err != nil {
19✔
3211
                return time.Time{}, exists, err
×
3212
        }
×
3213

3214
        return updateTime, exists, nil
19✔
3215
}
3216

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

1,869✔
3223
        traversal := func(tx kvdb.RTx) error {
3,738✔
3224
                edges := tx.ReadBucket(edgeBucket)
1,869✔
3225
                if edges == nil {
1,869✔
3226
                        return ErrGraphNotFound
×
3227
                }
×
3228
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,869✔
3229
                if edgeIndex == nil {
1,869✔
3230
                        return ErrGraphNoEdgesFound
×
3231
                }
×
3232

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

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

3260
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,846✔
3261
                                edges, chanID, nodePub,
3,846✔
3262
                        )
3,846✔
3263
                        if err != nil {
3,846✔
3264
                                return err
×
3265
                        }
×
3266

3267
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,846✔
3268
                        if err != nil {
3,846✔
3269
                                return err
×
3270
                        }
×
3271

3272
                        incomingPolicy, err := fetchChanEdgePolicy(
3,846✔
3273
                                edges, chanID, otherNode[:],
3,846✔
3274
                        )
3,846✔
3275
                        if err != nil {
3,846✔
3276
                                return err
×
3277
                        }
×
3278

3279
                        // Finally, we execute the callback.
3280
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,846✔
3281
                        if err != nil {
3,858✔
3282
                                return err
12✔
3283
                        }
12✔
3284
                }
3285

3286
                return nil
1,860✔
3287
        }
3288

3289
        // If no transaction was provided, then we'll create a new transaction
3290
        // to execute the transaction within.
3291
        if tx == nil {
1,881✔
3292
                return kvdb.View(db, traversal, func() {})
24✔
3293
        }
3294

3295
        // Otherwise, we re-use the existing transaction to execute the graph
3296
        // traversal.
3297
        return traversal(tx)
1,860✔
3298
}
3299

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

9✔
3312
        return nodeTraversal(nil, nodePub[:], c.db, cb)
9✔
3313
}
9✔
3314

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

1,001✔
3333
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,001✔
3334
}
1,001✔
3335

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

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

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

3364
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3365
                if err != nil {
3✔
3366
                        return err
×
3367
                }
×
3368

3369
                targetNode = &node
3✔
3370

3✔
3371
                return nil
3✔
3372
        }
3373

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

3383
        return targetNode, err
3✔
3384
}
3385

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

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

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

25✔
3401
        return node1Key[:], node2Key[:]
25✔
3402
}
25✔
3403

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

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

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

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

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

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

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

3470
                policy1 = e1
4✔
3471
                policy2 = e2
4✔
3472
                return nil
4✔
3473
        }, func() {
14✔
3474
                edgeInfo = nil
14✔
3475
                policy1 = nil
14✔
3476
                policy2 = nil
14✔
3477
        })
14✔
3478
        if err != nil {
27✔
3479
                return nil, nil, nil, err
13✔
3480
        }
13✔
3481

3482
        return edgeInfo, policy1, policy2, nil
4✔
3483
}
3484

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

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

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

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

3525
                byteOrder.PutUint64(channelID[:], chanID)
28✔
3526

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

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

3541
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
4✔
3542
                                zombieIndex, chanID,
4✔
3543
                        )
4✔
3544
                        if !isZombie {
7✔
3545
                                return ErrEdgeNotFound
3✔
3546
                        }
3✔
3547

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

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

3564
                edgeInfo = &edge
27✔
3565

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

3575
                policy1 = e1
27✔
3576
                policy2 = e2
27✔
3577
                return nil
27✔
3578
        }, func() {
28✔
3579
                edgeInfo = nil
28✔
3580
                policy1 = nil
28✔
3581
                policy2 = nil
28✔
3582
        })
28✔
3583
        if err == ErrZombieEdge {
32✔
3584
                return edgeInfo, nil, nil, err
4✔
3585
        }
4✔
3586
        if err != nil {
30✔
3587
                return nil, nil, nil, err
3✔
3588
        }
3✔
3589

3590
        return edgeInfo, policy1, policy2, nil
27✔
3591
}
3592

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

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

3621
        return nodeIsPublic, nil
16✔
3622
}
3623

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

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

49✔
3641
        return bldr.Script()
49✔
3642
}
3643

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

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

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

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

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

45✔
3691
                        var chanPoint wire.OutPoint
45✔
3692
                        err := readOutpoint(chanPointReader, &chanPoint)
45✔
3693
                        if err != nil {
45✔
3694
                                return err
×
3695
                        }
×
3696

3697
                        edgeInfo, err := fetchChanEdgeInfo(
45✔
3698
                                edgeIndex, chanID,
45✔
3699
                        )
45✔
3700
                        if err != nil {
45✔
3701
                                return err
×
3702
                        }
×
3703

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

3712
                        edgePoints = append(edgePoints, EdgePoint{
45✔
3713
                                FundingPkScript: pkScript,
45✔
3714
                                OutPoint:        chanPoint,
45✔
3715
                        })
45✔
3716

45✔
3717
                        return nil
45✔
3718
                })
3719
        }, func() {
26✔
3720
                edgePoints = nil
26✔
3721
        }); err != nil {
26✔
3722
                return nil, err
×
3723
        }
×
3724

3725
        return edgePoints, nil
26✔
3726
}
3727

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

134✔
3734
        c.cacheMu.Lock()
134✔
3735
        defer c.cacheMu.Unlock()
134✔
3736

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

3748
                if c.graphCache != nil {
268✔
3749
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
134✔
3750
                }
134✔
3751

3752
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
134✔
3753
        })
3754
        if err != nil {
134✔
3755
                return err
×
3756
        }
×
3757

3758
        c.rejectCache.remove(chanID)
134✔
3759
        c.chanCache.remove(chanID)
134✔
3760

134✔
3761
        return nil
134✔
3762
}
3763

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

161✔
3770
        var k [8]byte
161✔
3771
        byteOrder.PutUint64(k[:], chanID)
161✔
3772

161✔
3773
        var v [66]byte
161✔
3774
        copy(v[:33], pubKey1[:])
161✔
3775
        copy(v[33:], pubKey2[:])
161✔
3776

161✔
3777
        return zombieIndex.Put(k[:], v[:])
161✔
3778
}
161✔
3779

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

5✔
3785
        return c.markEdgeLiveUnsafe(nil, chanID)
5✔
3786
}
5✔
3787

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

3805
                var k [8]byte
5✔
3806
                byteOrder.PutUint64(k[:], chanID)
5✔
3807

5✔
3808
                if len(zombieIndex.Get(k[:])) == 0 {
6✔
3809
                        return ErrZombieEdgeNotFound
1✔
3810
                }
1✔
3811

3812
                return zombieIndex.Delete(k[:])
4✔
3813
        }
3814

3815
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3816
        // the existing transaction
3817
        var err error
5✔
3818
        if tx == nil {
10✔
3819
                err = kvdb.Update(c.db, dbFn, func() {})
10✔
UNCOV
3820
        } else {
×
UNCOV
3821
                err = dbFn(tx)
×
UNCOV
3822
        }
×
3823
        if err != nil {
6✔
3824
                return err
1✔
3825
        }
1✔
3826

3827
        c.rejectCache.remove(chanID)
4✔
3828
        c.chanCache.remove(chanID)
4✔
3829

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

3838
                for _, edgeInfo := range edgeInfos {
4✔
3839
                        c.graphCache.AddChannel(
×
3840
                                edgeInfo.Info, edgeInfo.Policy1,
×
3841
                                edgeInfo.Policy2,
×
3842
                        )
×
3843
                }
×
3844
        }
3845

3846
        return nil
4✔
3847
}
3848

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

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

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

3879
        return isZombie, pubKey1, pubKey2
5✔
3880
}
3881

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

108✔
3888
        var k [8]byte
108✔
3889
        byteOrder.PutUint64(k[:], chanID)
108✔
3890

108✔
3891
        v := zombieIndex.Get(k[:])
108✔
3892
        if v == nil {
177✔
3893
                return false, [33]byte{}, [33]byte{}
69✔
3894
        }
69✔
3895

3896
        var pubKey1, pubKey2 [33]byte
42✔
3897
        copy(pubKey1[:], v[:33])
42✔
3898
        copy(pubKey2[:], v[33:])
42✔
3899

42✔
3900
        return true, pubKey1, pubKey2
42✔
3901
}
3902

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

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

3927
        return numZombies, nil
4✔
3928
}
3929

3930
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3931
        updateIndex kvdb.RwBucket, node *LightningNode) error {
979✔
3932

979✔
3933
        var (
979✔
3934
                scratch [16]byte
979✔
3935
                b       bytes.Buffer
979✔
3936
        )
979✔
3937

979✔
3938
        pub, err := node.PubKey()
979✔
3939
        if err != nil {
979✔
3940
                return err
×
3941
        }
×
3942
        nodePub := pub.SerializeCompressed()
979✔
3943

979✔
3944
        // If the node has the update time set, write it, else write 0.
979✔
3945
        updateUnix := uint64(0)
979✔
3946
        if node.LastUpdate.Unix() > 0 {
1,829✔
3947
                updateUnix = uint64(node.LastUpdate.Unix())
850✔
3948
        }
850✔
3949

3950
        byteOrder.PutUint64(scratch[:8], updateUnix)
979✔
3951
        if _, err := b.Write(scratch[:8]); err != nil {
979✔
3952
                return err
×
3953
        }
×
3954

3955
        if _, err := b.Write(nodePub); err != nil {
979✔
3956
                return err
×
3957
        }
×
3958

3959
        // If we got a node announcement for this node, we will have the rest
3960
        // of the data available. If not we don't have more data to write.
3961
        if !node.HaveNodeAnnouncement {
1,058✔
3962
                // Write HaveNodeAnnouncement=0.
79✔
3963
                byteOrder.PutUint16(scratch[:2], 0)
79✔
3964
                if _, err := b.Write(scratch[:2]); err != nil {
79✔
3965
                        return err
×
3966
                }
×
3967

3968
                return nodeBucket.Put(nodePub, b.Bytes())
79✔
3969
        }
3970

3971
        // Write HaveNodeAnnouncement=1.
3972
        byteOrder.PutUint16(scratch[:2], 1)
903✔
3973
        if _, err := b.Write(scratch[:2]); err != nil {
903✔
3974
                return err
×
3975
        }
×
3976

3977
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
903✔
3978
                return err
×
3979
        }
×
3980
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
903✔
3981
                return err
×
3982
        }
×
3983
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
903✔
3984
                return err
×
3985
        }
×
3986

3987
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
903✔
3988
                return err
×
3989
        }
×
3990

3991
        if err := node.Features.Encode(&b); err != nil {
903✔
3992
                return err
×
3993
        }
×
3994

3995
        numAddresses := uint16(len(node.Addresses))
903✔
3996
        byteOrder.PutUint16(scratch[:2], numAddresses)
903✔
3997
        if _, err := b.Write(scratch[:2]); err != nil {
903✔
3998
                return err
×
3999
        }
×
4000

4001
        for _, address := range node.Addresses {
2,036✔
4002
                if err := serializeAddr(&b, address); err != nil {
1,133✔
4003
                        return err
×
4004
                }
×
4005
        }
4006

4007
        sigLen := len(node.AuthSigBytes)
903✔
4008
        if sigLen > 80 {
903✔
4009
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4010
                        sigLen)
×
4011
        }
×
4012

4013
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
903✔
4014
        if err != nil {
903✔
4015
                return err
×
4016
        }
×
4017

4018
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
903✔
4019
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4020
        }
×
4021
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
903✔
4022
        if err != nil {
903✔
4023
                return err
×
4024
        }
×
4025

4026
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
903✔
4027
                return err
×
4028
        }
×
4029

4030
        // With the alias bucket updated, we'll now update the index that
4031
        // tracks the time series of node updates.
4032
        var indexKey [8 + 33]byte
903✔
4033
        byteOrder.PutUint64(indexKey[:8], updateUnix)
903✔
4034
        copy(indexKey[8:], nodePub)
903✔
4035

903✔
4036
        // If there was already an old index entry for this node, then we'll
903✔
4037
        // delete the old one before we write the new entry.
903✔
4038
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
1,008✔
4039
                // Extract out the old update time to we can reconstruct the
105✔
4040
                // prior index key to delete it from the index.
105✔
4041
                oldUpdateTime := nodeBytes[:8]
105✔
4042

105✔
4043
                var oldIndexKey [8 + 33]byte
105✔
4044
                copy(oldIndexKey[:8], oldUpdateTime)
105✔
4045
                copy(oldIndexKey[8:], nodePub)
105✔
4046

105✔
4047
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
105✔
4048
                        return err
×
4049
                }
×
4050
        }
4051

4052
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
903✔
4053
                return err
×
4054
        }
×
4055

4056
        return nodeBucket.Put(nodePub, b.Bytes())
903✔
4057
}
4058

4059
func fetchLightningNode(nodeBucket kvdb.RBucket,
4060
        nodePub []byte) (LightningNode, error) {
3,589✔
4061

3,589✔
4062
        nodeBytes := nodeBucket.Get(nodePub)
3,589✔
4063
        if nodeBytes == nil {
3,667✔
4064
                return LightningNode{}, ErrGraphNodeNotFound
78✔
4065
        }
78✔
4066

4067
        nodeReader := bytes.NewReader(nodeBytes)
3,514✔
4068
        return deserializeLightningNode(nodeReader)
3,514✔
4069
}
4070

4071
func deserializeLightningNodeCacheable(r io.Reader) (*graphCacheNode, error) {
123✔
4072
        // Always populate a feature vector, even if we don't have a node
123✔
4073
        // announcement and short circuit below.
123✔
4074
        node := newGraphCacheNode(
123✔
4075
                route.Vertex{},
123✔
4076
                lnwire.EmptyFeatureVector(),
123✔
4077
        )
123✔
4078

123✔
4079
        var nodeScratch [8]byte
123✔
4080

123✔
4081
        // Skip ahead:
123✔
4082
        // - LastUpdate (8 bytes)
123✔
4083
        if _, err := r.Read(nodeScratch[:]); err != nil {
123✔
4084
                return nil, err
×
4085
        }
×
4086

4087
        if _, err := io.ReadFull(r, node.pubKeyBytes[:]); err != nil {
123✔
4088
                return nil, err
×
4089
        }
×
4090

4091
        // Read the node announcement flag.
4092
        if _, err := r.Read(nodeScratch[:2]); err != nil {
123✔
4093
                return nil, err
×
4094
        }
×
4095
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
123✔
4096

123✔
4097
        // The rest of the data is optional, and will only be there if we got a
123✔
4098
        // node announcement for this node.
123✔
4099
        if hasNodeAnn == 0 {
126✔
4100
                return node, nil
3✔
4101
        }
3✔
4102

4103
        // We did get a node announcement for this node, so we'll have the rest
4104
        // of the data available.
4105
        var rgb uint8
123✔
4106
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4107
                return nil, err
×
4108
        }
×
4109
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4110
                return nil, err
×
4111
        }
×
4112
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
123✔
4113
                return nil, err
×
4114
        }
×
4115

4116
        if _, err := wire.ReadVarString(r, 0); err != nil {
123✔
4117
                return nil, err
×
4118
        }
×
4119

4120
        if err := node.features.Decode(r); err != nil {
123✔
4121
                return nil, err
×
4122
        }
×
4123

4124
        return node, nil
123✔
4125
}
4126

4127
func deserializeLightningNode(r io.Reader) (LightningNode, error) {
8,467✔
4128
        var (
8,467✔
4129
                node    LightningNode
8,467✔
4130
                scratch [8]byte
8,467✔
4131
                err     error
8,467✔
4132
        )
8,467✔
4133

8,467✔
4134
        // Always populate a feature vector, even if we don't have a node
8,467✔
4135
        // announcement and short circuit below.
8,467✔
4136
        node.Features = lnwire.EmptyFeatureVector()
8,467✔
4137

8,467✔
4138
        if _, err := r.Read(scratch[:]); err != nil {
8,467✔
4139
                return LightningNode{}, err
×
4140
        }
×
4141

4142
        unix := int64(byteOrder.Uint64(scratch[:]))
8,467✔
4143
        node.LastUpdate = time.Unix(unix, 0)
8,467✔
4144

8,467✔
4145
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,467✔
4146
                return LightningNode{}, err
×
4147
        }
×
4148

4149
        if _, err := r.Read(scratch[:2]); err != nil {
8,467✔
4150
                return LightningNode{}, err
×
4151
        }
×
4152

4153
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,467✔
4154
        if hasNodeAnn == 1 {
16,792✔
4155
                node.HaveNodeAnnouncement = true
8,325✔
4156
        } else {
8,470✔
4157
                node.HaveNodeAnnouncement = false
145✔
4158
        }
145✔
4159

4160
        // The rest of the data is optional, and will only be there if we got a node
4161
        // announcement for this node.
4162
        if !node.HaveNodeAnnouncement {
8,612✔
4163
                return node, nil
145✔
4164
        }
145✔
4165

4166
        // We did get a node announcement for this node, so we'll have the rest
4167
        // of the data available.
4168
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,325✔
4169
                return LightningNode{}, err
×
4170
        }
×
4171
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,325✔
4172
                return LightningNode{}, err
×
4173
        }
×
4174
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,325✔
4175
                return LightningNode{}, err
×
4176
        }
×
4177

4178
        node.Alias, err = wire.ReadVarString(r, 0)
8,325✔
4179
        if err != nil {
8,325✔
4180
                return LightningNode{}, err
×
4181
        }
×
4182

4183
        err = node.Features.Decode(r)
8,325✔
4184
        if err != nil {
8,325✔
4185
                return LightningNode{}, err
×
4186
        }
×
4187

4188
        if _, err := r.Read(scratch[:2]); err != nil {
8,325✔
4189
                return LightningNode{}, err
×
4190
        }
×
4191
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,325✔
4192

8,325✔
4193
        var addresses []net.Addr
8,325✔
4194
        for i := 0; i < numAddresses; i++ {
18,878✔
4195
                address, err := deserializeAddr(r)
10,553✔
4196
                if err != nil {
10,553✔
4197
                        return LightningNode{}, err
×
4198
                }
×
4199
                addresses = append(addresses, address)
10,553✔
4200
        }
4201
        node.Addresses = addresses
8,325✔
4202

8,325✔
4203
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,325✔
4204
        if err != nil {
8,325✔
4205
                return LightningNode{}, err
×
4206
        }
×
4207

4208
        // We'll try and see if there are any opaque bytes left, if not, then
4209
        // we'll ignore the EOF error and return the node as is.
4210
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
8,325✔
4211
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,325✔
4212
        )
8,325✔
4213
        switch {
8,325✔
4214
        case err == io.ErrUnexpectedEOF:
×
4215
        case err == io.EOF:
×
4216
        case err != nil:
×
4217
                return LightningNode{}, err
×
4218
        }
4219

4220
        return node, nil
8,325✔
4221
}
4222

4223
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4224
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,470✔
4225

1,470✔
4226
        var b bytes.Buffer
1,470✔
4227

1,470✔
4228
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,470✔
4229
                return err
×
4230
        }
×
4231
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,470✔
4232
                return err
×
4233
        }
×
4234
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,470✔
4235
                return err
×
4236
        }
×
4237
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,470✔
4238
                return err
×
4239
        }
×
4240

4241
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,470✔
4242
                return err
×
4243
        }
×
4244

4245
        authProof := edgeInfo.AuthProof
1,470✔
4246
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,470✔
4247
        if authProof != nil {
2,857✔
4248
                nodeSig1 = authProof.NodeSig1Bytes
1,387✔
4249
                nodeSig2 = authProof.NodeSig2Bytes
1,387✔
4250
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,387✔
4251
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,387✔
4252
        }
1,387✔
4253

4254
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,470✔
4255
                return err
×
4256
        }
×
4257
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,470✔
4258
                return err
×
4259
        }
×
4260
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,470✔
4261
                return err
×
4262
        }
×
4263
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,470✔
4264
                return err
×
4265
        }
×
4266

4267
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,470✔
4268
                return err
×
4269
        }
×
4270
        if err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity)); err != nil {
1,470✔
4271
                return err
×
4272
        }
×
4273
        if _, err := b.Write(chanID[:]); err != nil {
1,470✔
4274
                return err
×
4275
        }
×
4276
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,470✔
4277
                return err
×
4278
        }
×
4279

4280
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,470✔
4281
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4282
        }
×
4283
        err := wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,470✔
4284
        if err != nil {
1,470✔
4285
                return err
×
4286
        }
×
4287

4288
        return edgeIndex.Put(chanID[:], b.Bytes())
1,470✔
4289
}
4290

4291
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4292
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,176✔
4293

4,176✔
4294
        edgeInfoBytes := edgeIndex.Get(chanID)
4,176✔
4295
        if edgeInfoBytes == nil {
4,247✔
4296
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
71✔
4297
        }
71✔
4298

4299
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,108✔
4300
        return deserializeChanEdgeInfo(edgeInfoReader)
4,108✔
4301
}
4302

4303
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,734✔
4304
        var (
4,734✔
4305
                err      error
4,734✔
4306
                edgeInfo models.ChannelEdgeInfo
4,734✔
4307
        )
4,734✔
4308

4,734✔
4309
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,734✔
4310
                return models.ChannelEdgeInfo{}, err
×
4311
        }
×
4312
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,734✔
4313
                return models.ChannelEdgeInfo{}, err
×
4314
        }
×
4315
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,734✔
4316
                return models.ChannelEdgeInfo{}, err
×
4317
        }
×
4318
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,734✔
4319
                return models.ChannelEdgeInfo{}, err
×
4320
        }
×
4321

4322
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,734✔
4323
        if err != nil {
4,734✔
4324
                return models.ChannelEdgeInfo{}, err
×
4325
        }
×
4326

4327
        proof := &models.ChannelAuthProof{}
4,734✔
4328

4,734✔
4329
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,734✔
4330
        if err != nil {
4,734✔
4331
                return models.ChannelEdgeInfo{}, err
×
4332
        }
×
4333
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,734✔
4334
        if err != nil {
4,734✔
4335
                return models.ChannelEdgeInfo{}, err
×
4336
        }
×
4337
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,734✔
4338
        if err != nil {
4,734✔
4339
                return models.ChannelEdgeInfo{}, err
×
4340
        }
×
4341
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,734✔
4342
        if err != nil {
4,734✔
4343
                return models.ChannelEdgeInfo{}, err
×
4344
        }
×
4345

4346
        if !proof.IsEmpty() {
6,515✔
4347
                edgeInfo.AuthProof = proof
1,781✔
4348
        }
1,781✔
4349

4350
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,734✔
4351
        if err := readOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,734✔
4352
                return models.ChannelEdgeInfo{}, err
×
4353
        }
×
4354
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,734✔
4355
                return models.ChannelEdgeInfo{}, err
×
4356
        }
×
4357
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,734✔
4358
                return models.ChannelEdgeInfo{}, err
×
4359
        }
×
4360

4361
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,734✔
4362
                return models.ChannelEdgeInfo{}, err
×
4363
        }
×
4364

4365
        // We'll try and see if there are any opaque bytes left, if not, then
4366
        // we'll ignore the EOF error and return the edge as is.
4367
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
4,734✔
4368
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
4,734✔
4369
        )
4,734✔
4370
        switch {
4,734✔
4371
        case err == io.ErrUnexpectedEOF:
×
4372
        case err == io.EOF:
×
4373
        case err != nil:
×
4374
                return models.ChannelEdgeInfo{}, err
×
4375
        }
4376

4377
        return edgeInfo, nil
4,734✔
4378
}
4379

4380
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4381
        from, to []byte) error {
2,631✔
4382

2,631✔
4383
        var edgeKey [33 + 8]byte
2,631✔
4384
        copy(edgeKey[:], from)
2,631✔
4385
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,631✔
4386

2,631✔
4387
        var b bytes.Buffer
2,631✔
4388
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,631✔
4389
                return err
×
4390
        }
×
4391

4392
        // Before we write out the new edge, we'll create a new entry in the
4393
        // update index in order to keep it fresh.
4394
        updateUnix := uint64(edge.LastUpdate.Unix())
2,631✔
4395
        var indexKey [8 + 8]byte
2,631✔
4396
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,631✔
4397
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,631✔
4398

2,631✔
4399
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,631✔
4400
        if err != nil {
2,631✔
4401
                return err
×
4402
        }
×
4403

4404
        // If there was already an entry for this edge, then we'll need to
4405
        // delete the old one to ensure we don't leave around any after-images.
4406
        // An unknown policy value does not have a update time recorded, so
4407
        // it also does not need to be removed.
4408
        if edgeBytes := edges.Get(edgeKey[:]); edgeBytes != nil &&
2,631✔
4409
                !bytes.Equal(edgeBytes[:], unknownPolicy) {
2,658✔
4410

27✔
4411
                // In order to delete the old entry, we'll need to obtain the
27✔
4412
                // *prior* update time in order to delete it. To do this, we'll
27✔
4413
                // need to deserialize the existing policy within the database
27✔
4414
                // (now outdated by the new one), and delete its corresponding
27✔
4415
                // entry within the update index. We'll ignore any
27✔
4416
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
27✔
4417
                // the channel ID and update time to delete the entry.
27✔
4418
                // TODO(halseth): get rid of these invalid policies in a
27✔
4419
                // migration.
27✔
4420
                oldEdgePolicy, err := deserializeChanEdgePolicy(
27✔
4421
                        bytes.NewReader(edgeBytes),
27✔
4422
                )
27✔
4423
                if err != nil && err != ErrEdgePolicyOptionalFieldNotFound {
27✔
4424
                        return err
×
4425
                }
×
4426

4427
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
27✔
4428

27✔
4429
                var oldIndexKey [8 + 8]byte
27✔
4430
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
27✔
4431
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
27✔
4432

27✔
4433
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
27✔
4434
                        return err
×
4435
                }
×
4436
        }
4437

4438
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,631✔
4439
                return err
×
4440
        }
×
4441

4442
        updateEdgePolicyDisabledIndex(
2,631✔
4443
                edges, edge.ChannelID,
2,631✔
4444
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,631✔
4445
                edge.IsDisabled(),
2,631✔
4446
        )
2,631✔
4447

2,631✔
4448
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,631✔
4449
}
4450

4451
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4452
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4453
// one.
4454
// The direction represents the direction of the edge and disabled is used for
4455
// deciding whether to remove or add an entry to the bucket.
4456
// In general a channel is disabled if two entries for the same chanID exist
4457
// in this bucket.
4458
// Maintaining the bucket this way allows a fast retrieval of disabled
4459
// channels, for example when prune is needed.
4460
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4461
        direction bool, disabled bool) error {
2,913✔
4462

2,913✔
4463
        var disabledEdgeKey [8 + 1]byte
2,913✔
4464
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,913✔
4465
        if direction {
4,369✔
4466
                disabledEdgeKey[8] = 1
1,456✔
4467
        }
1,456✔
4468

4469
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,913✔
4470
                disabledEdgePolicyBucket,
2,913✔
4471
        )
2,913✔
4472
        if err != nil {
2,913✔
4473
                return err
×
4474
        }
×
4475

4476
        if disabled {
2,942✔
4477
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4478
        }
29✔
4479

4480
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,887✔
4481
}
4482

4483
// putChanEdgePolicyUnknown marks the edge policy as unknown
4484
// in the edges bucket.
4485
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4486
        from []byte) error {
2,935✔
4487

2,935✔
4488
        var edgeKey [33 + 8]byte
2,935✔
4489
        copy(edgeKey[:], from)
2,935✔
4490
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,935✔
4491

2,935✔
4492
        if edges.Get(edgeKey[:]) != nil {
2,935✔
4493
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4494
                        " when there is already a policy present", channelID)
×
4495
        }
×
4496

4497
        return edges.Put(edgeKey[:], unknownPolicy)
2,935✔
4498
}
4499

4500
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4501
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,165✔
4502

8,165✔
4503
        var edgeKey [33 + 8]byte
8,165✔
4504
        copy(edgeKey[:], nodePub)
8,165✔
4505
        copy(edgeKey[33:], chanID[:])
8,165✔
4506

8,165✔
4507
        edgeBytes := edges.Get(edgeKey[:])
8,165✔
4508
        if edgeBytes == nil {
8,165✔
4509
                return nil, ErrEdgeNotFound
×
4510
        }
×
4511

4512
        // No need to deserialize unknown policy.
4513
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,539✔
4514
                return nil, nil
374✔
4515
        }
374✔
4516

4517
        edgeReader := bytes.NewReader(edgeBytes)
7,794✔
4518

7,794✔
4519
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,794✔
4520
        switch {
7,794✔
4521
        // If the db policy was missing an expected optional field, we return
4522
        // nil as if the policy was unknown.
4523
        case err == ErrEdgePolicyOptionalFieldNotFound:
1✔
4524
                return nil, nil
1✔
4525

4526
        case err != nil:
×
4527
                return nil, err
×
4528
        }
4529

4530
        return ep, nil
7,793✔
4531
}
4532

4533
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4534
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4535
        error) {
241✔
4536

241✔
4537
        edgeInfo := edgeIndex.Get(chanID)
241✔
4538
        if edgeInfo == nil {
241✔
4539
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4540
                        chanID)
×
4541
        }
×
4542

4543
        // The first node is contained within the first half of the edge
4544
        // information. We only propagate the error here and below if it's
4545
        // something other than edge non-existence.
4546
        node1Pub := edgeInfo[:33]
241✔
4547
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
241✔
4548
        if err != nil {
241✔
4549
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4550
                        node1Pub)
×
4551
        }
×
4552

4553
        // Similarly, the second node is contained within the latter
4554
        // half of the edge information.
4555
        node2Pub := edgeInfo[33:66]
241✔
4556
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
241✔
4557
        if err != nil {
241✔
4558
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4559
                        node2Pub)
×
4560
        }
×
4561

4562
        return edge1, edge2, nil
241✔
4563
}
4564

4565
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4566
        to []byte) error {
2,633✔
4567

2,633✔
4568
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,633✔
4569
        if err != nil {
2,633✔
4570
                return err
×
4571
        }
×
4572

4573
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,633✔
4574
                return err
×
4575
        }
×
4576

4577
        var scratch [8]byte
2,633✔
4578
        updateUnix := uint64(edge.LastUpdate.Unix())
2,633✔
4579
        byteOrder.PutUint64(scratch[:], updateUnix)
2,633✔
4580
        if _, err := w.Write(scratch[:]); err != nil {
2,633✔
4581
                return err
×
4582
        }
×
4583

4584
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,633✔
4585
                return err
×
4586
        }
×
4587
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,633✔
4588
                return err
×
4589
        }
×
4590
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,633✔
4591
                return err
×
4592
        }
×
4593
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,633✔
4594
                return err
×
4595
        }
×
4596
        if err := binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat)); err != nil {
2,633✔
4597
                return err
×
4598
        }
×
4599
        if err := binary.Write(w, byteOrder, uint64(edge.FeeProportionalMillionths)); err != nil {
2,633✔
4600
                return err
×
4601
        }
×
4602

4603
        if _, err := w.Write(to); err != nil {
2,633✔
4604
                return err
×
4605
        }
×
4606

4607
        // If the max_htlc field is present, we write it. To be compatible with
4608
        // older versions that wasn't aware of this field, we write it as part
4609
        // of the opaque data.
4610
        // TODO(halseth): clean up when moving to TLV.
4611
        var opaqueBuf bytes.Buffer
2,633✔
4612
        if edge.MessageFlags.HasMaxHtlc() {
4,882✔
4613
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,249✔
4614
                if err != nil {
2,249✔
4615
                        return err
×
4616
                }
×
4617
        }
4618

4619
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,633✔
4620
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4621
        }
×
4622
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,633✔
4623
                return err
×
4624
        }
×
4625

4626
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,633✔
4627
                return err
×
4628
        }
×
4629
        return nil
2,633✔
4630
}
4631

4632
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,819✔
4633
        // Deserialize the policy. Note that in case an optional field is not
7,819✔
4634
        // found, both an error and a populated policy object are returned.
7,819✔
4635
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,819✔
4636
        if deserializeErr != nil &&
7,819✔
4637
                deserializeErr != ErrEdgePolicyOptionalFieldNotFound {
7,819✔
4638

×
4639
                return nil, deserializeErr
×
4640
        }
×
4641

4642
        return edge, deserializeErr
7,819✔
4643
}
4644

4645
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4646
        error) {
8,826✔
4647

8,826✔
4648
        edge := &models.ChannelEdgePolicy{}
8,826✔
4649

8,826✔
4650
        var err error
8,826✔
4651
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,826✔
4652
        if err != nil {
8,826✔
4653
                return nil, err
×
4654
        }
×
4655

4656
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,826✔
4657
                return nil, err
×
4658
        }
×
4659

4660
        var scratch [8]byte
8,826✔
4661
        if _, err := r.Read(scratch[:]); err != nil {
8,826✔
4662
                return nil, err
×
4663
        }
×
4664
        unix := int64(byteOrder.Uint64(scratch[:]))
8,826✔
4665
        edge.LastUpdate = time.Unix(unix, 0)
8,826✔
4666

8,826✔
4667
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,826✔
4668
                return nil, err
×
4669
        }
×
4670
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,826✔
4671
                return nil, err
×
4672
        }
×
4673
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,826✔
4674
                return nil, err
×
4675
        }
×
4676

4677
        var n uint64
8,826✔
4678
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,826✔
4679
                return nil, err
×
4680
        }
×
4681
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,826✔
4682

8,826✔
4683
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,826✔
4684
                return nil, err
×
4685
        }
×
4686
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,826✔
4687

8,826✔
4688
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,826✔
4689
                return nil, err
×
4690
        }
×
4691
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,826✔
4692

8,826✔
4693
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,826✔
4694
                return nil, err
×
4695
        }
×
4696

4697
        // We'll try and see if there are any opaque bytes left, if not, then
4698
        // we'll ignore the EOF error and return the edge as is.
4699
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,826✔
4700
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,826✔
4701
        )
8,826✔
4702
        switch {
8,826✔
4703
        case err == io.ErrUnexpectedEOF:
×
4704
        case err == io.EOF:
3✔
4705
        case err != nil:
×
4706
                return nil, err
×
4707
        }
4708

4709
        // See if optional fields are present.
4710
        if edge.MessageFlags.HasMaxHtlc() {
17,272✔
4711
                // The max_htlc field should be at the beginning of the opaque
8,446✔
4712
                // bytes.
8,446✔
4713
                opq := edge.ExtraOpaqueData
8,446✔
4714

8,446✔
4715
                // If the max_htlc field is not present, it might be old data
8,446✔
4716
                // stored before this field was validated. We'll return the
8,446✔
4717
                // edge along with an error.
8,446✔
4718
                if len(opq) < 8 {
8,449✔
4719
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4720
                }
3✔
4721

4722
                maxHtlc := byteOrder.Uint64(opq[:8])
8,443✔
4723
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,443✔
4724

8,443✔
4725
                // Exclude the parsed field from the rest of the opaque data.
8,443✔
4726
                edge.ExtraOpaqueData = opq[8:]
8,443✔
4727
        }
4728

4729
        return edge, nil
8,823✔
4730
}
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