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

lightningnetwork / lnd / 11934293069

20 Nov 2024 01:22PM UTC coverage: 58.969% (+0.02%) from 58.951%
11934293069

Pull #9242

github

aakselrod
testing: get goroutines from sweeper when deadlocked at shutdown
Pull Request #9242: Reapply #8644

50 of 83 new or added lines in 4 files covered. (60.24%)

63 existing lines in 14 files now uncovered.

132805 of 225212 relevant lines covered (58.97%)

19552.57 hits per line

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

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

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

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

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

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

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

1,878✔
205
        if !noMigrations {
3,756✔
206
                if err := initChannelGraph(db); err != nil {
1,878✔
207
                        return nil, err
×
208
                }
×
209
        }
210

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

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

1,846✔
231
                err := g.ForEachNodeCacheable(
1,846✔
232
                        func(tx kvdb.RTx, node GraphCacheNode) error {
1,949✔
233
                                g.graphCache.AddNodeFeatures(node)
103✔
234

103✔
235
                                return nil
103✔
236
                        },
103✔
237
                )
238
                if err != nil {
1,846✔
239
                        return nil, err
×
240
                }
×
241

242
                err = g.ForEachChannel(func(info *models.ChannelEdgeInfo,
1,846✔
243
                        policy1, policy2 *models.ChannelEdgePolicy) error {
2,245✔
244

399✔
245
                        g.graphCache.AddChannel(info, policy1, policy2)
399✔
246

399✔
247
                        return nil
399✔
248
                })
399✔
249
                if err != nil {
1,846✔
250
                        return nil, err
×
251
                }
×
252

253
                log.Debugf("Finished populating in-memory channel graph (took "+
1,846✔
254
                        "%v, %s)", time.Since(startTime), g.graphCache.Stats())
1,846✔
255
        }
256

257
        return g, nil
1,878✔
258
}
259

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

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

1,850✔
271
        // Create a map to store all channel edge policies.
1,850✔
272
        channelMap := make(map[channelMapKey]*models.ChannelEdgePolicy)
1,850✔
273

1,850✔
274
        err := kvdb.ForAll(edges, func(k, edgeBytes []byte) error {
10,236✔
275
                // Skip embedded buckets.
8,386✔
276
                if bytes.Equal(k, edgeIndexBucket) ||
8,386✔
277
                        bytes.Equal(k, edgeUpdateIndexBucket) ||
8,386✔
278
                        bytes.Equal(k, zombieBucket) ||
8,386✔
279
                        bytes.Equal(k, disabledEdgePolicyBucket) ||
8,386✔
280
                        bytes.Equal(k, channelPointBucket) {
15,782✔
281

7,396✔
282
                        return nil
7,396✔
283
                }
7,396✔
284

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

290
                var key channelMapKey
993✔
291
                copy(key.nodeKey[:], k[:33])
993✔
292
                copy(key.chanID[:], k[33:])
993✔
293

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

299
                edgeReader := bytes.NewReader(edgeBytes)
993✔
300
                edge, err := deserializeChanEdgePolicyRaw(
993✔
301
                        edgeReader,
993✔
302
                )
993✔
303

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

310
                case err != nil:
×
311
                        return err
×
312
                }
313

314
                channelMap[key] = edge
993✔
315

993✔
316
                return nil
993✔
317
        })
318
        if err != nil {
1,850✔
319
                return nil, err
×
320
        }
×
321

322
        return channelMap, nil
1,850✔
323
}
324

325
var graphTopLevelBuckets = [][]byte{
326
        nodeBucket,
327
        edgeBucket,
328
        graphMetaBucket,
329
        closedScidBucket,
330
}
331

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

349
        return initChannelGraph(c.db)
×
350
}
351

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

364
                nodes := tx.ReadWriteBucket(nodeBucket)
1,878✔
365
                _, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
1,878✔
366
                if err != nil {
1,878✔
367
                        return err
×
368
                }
×
369
                _, err = nodes.CreateBucketIfNotExists(nodeUpdateIndexBucket)
1,878✔
370
                if err != nil {
1,878✔
371
                        return err
×
372
                }
×
373

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

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

400
        return nil
1,878✔
401
}
402

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

410
        return c.db.BeginReadTx()
53✔
411
}
412

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

1,850✔
425
        return c.db.View(func(tx kvdb.RTx) error {
3,700✔
426
                edges := tx.ReadBucket(edgeBucket)
1,850✔
427
                if edges == nil {
1,850✔
428
                        return ErrGraphNoEdgesFound
×
429
                }
×
430

431
                // First, load all edges in memory indexed by node and channel
432
                // id.
433
                channelMap, err := c.getChannelMap(edges)
1,850✔
434
                if err != nil {
1,850✔
435
                        return err
×
436
                }
×
437

438
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,850✔
439
                if edgeIndex == nil {
1,850✔
440
                        return ErrGraphNoEdgesFound
×
441
                }
×
442

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

498✔
449
                        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
498✔
450
                        info, err := deserializeChanEdgeInfo(edgeInfoReader)
498✔
451
                        if err != nil {
498✔
452
                                return err
×
453
                        }
×
454

455
                        policy1 := channelMap[channelMapKey{
498✔
456
                                nodeKey: info.NodeKey1Bytes,
498✔
457
                                chanID:  chanID,
498✔
458
                        }]
498✔
459

498✔
460
                        policy2 := channelMap[channelMapKey{
498✔
461
                                nodeKey: info.NodeKey2Bytes,
498✔
462
                                chanID:  chanID,
498✔
463
                        }]
498✔
464

498✔
465
                        return cb(&info, policy1, policy2)
498✔
466
                })
467
        }, func() {})
1,850✔
468
}
469

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

696✔
479
        if c.graphCache != nil {
1,155✔
480
                return c.graphCache.ForEachChannel(node, cb)
459✔
481
        }
459✔
482

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

492
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
240✔
493
                p2 *models.ChannelEdgePolicy) error {
733✔
494

493✔
495
                var cachedInPolicy *models.CachedEdgePolicy
493✔
496
                if p2 != nil {
983✔
497
                        cachedInPolicy = models.NewCachedPolicy(p2)
490✔
498
                        cachedInPolicy.ToNodePubKey = toNodeCallback
490✔
499
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
490✔
500
                }
490✔
501

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

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

492✔
522
                if node == e.NodeKey2Bytes {
740✔
523
                        directedChannel.OtherNode = e.NodeKey1Bytes
248✔
524
                }
248✔
525

526
                return cb(directedChannel)
492✔
527
        }
528
        return nodeTraversal(tx, node[:], c.db, dbCallback)
240✔
529
}
530

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

1,125✔
536
        if c.graphCache != nil {
1,575✔
537
                return c.graphCache.GetFeatures(node), nil
450✔
538
        }
450✔
539

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

547
        // If we couldn't find a node announcement, populate a blank feature
548
        // vector.
549
        case ErrGraphNodeNotFound:
5✔
550
                return lnwire.EmptyFeatureVector(), nil
5✔
551

552
        // Otherwise, bubble the error up.
553
        default:
×
554
                return nil, err
×
555
        }
556
}
557

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

1✔
566
        if c.graphCache != nil {
1✔
567
                return c.graphCache.ForEachNode(cb)
×
568
        }
×
569

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

20✔
577
                err := c.ForEachNodeChannelTx(tx, node.PubKeyBytes,
20✔
578
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
20✔
579
                                p1 *models.ChannelEdgePolicy,
20✔
580
                                p2 *models.ChannelEdgePolicy) error {
210✔
581

190✔
582
                                toNodeCallback := func() route.Vertex {
190✔
583
                                        return node.PubKeyBytes
×
584
                                }
×
585
                                toNodeFeatures, err := c.FetchNodeFeatures(
190✔
586
                                        node.PubKeyBytes,
190✔
587
                                )
190✔
588
                                if err != nil {
190✔
589
                                        return err
×
590
                                }
×
591

592
                                var cachedInPolicy *models.CachedEdgePolicy
190✔
593
                                if p2 != nil {
380✔
594
                                        cachedInPolicy =
190✔
595
                                                models.NewCachedPolicy(p2)
190✔
596
                                        cachedInPolicy.ToNodePubKey =
190✔
597
                                                toNodeCallback
190✔
598
                                        cachedInPolicy.ToNodeFeatures =
190✔
599
                                                toNodeFeatures
190✔
600
                                }
190✔
601

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

190✔
612
                                if node.PubKeyBytes == e.NodeKey2Bytes {
285✔
613
                                        directedChannel.OtherNode =
95✔
614
                                                e.NodeKey1Bytes
95✔
615
                                }
95✔
616

617
                                channels[e.ChannelID] = directedChannel
190✔
618

190✔
619
                                return nil
190✔
620
                        })
621
                if err != nil {
20✔
622
                        return err
×
623
                }
×
624

625
                return cb(node.PubKeyBytes, channels)
20✔
626
        })
627
}
628

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

6✔
636
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
637
                edges := tx.ReadBucket(edgeBucket)
6✔
638
                if edges == nil {
6✔
639
                        return ErrGraphNoEdgesFound
×
640
                }
×
641

642
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
643
                        disabledEdgePolicyBucket,
6✔
644
                )
6✔
645
                if disabledEdgePolicyIndex == nil {
7✔
646
                        return nil
1✔
647
                }
1✔
648

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

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

671
        return disabledChanIDs, nil
6✔
672
}
673

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

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

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

700
                        nodeReader := bytes.NewReader(nodeBytes)
1,181✔
701
                        node, err := deserializeLightningNode(nodeReader)
1,181✔
702
                        if err != nil {
1,181✔
703
                                return err
×
704
                        }
×
705

706
                        // Execute the callback, the transaction will abort if
707
                        // this returns an error.
708
                        return cb(tx, &node)
1,181✔
709
                })
710
        }
711

712
        return kvdb.View(c.db, traversal, func() {})
264✔
713
}
714

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

1,847✔
722
        traversal := func(tx kvdb.RTx) error {
3,694✔
723
                // First grab the nodes bucket which stores the mapping from
1,847✔
724
                // pubKey to node information.
1,847✔
725
                nodes := tx.ReadBucket(nodeBucket)
1,847✔
726
                if nodes == nil {
1,847✔
727
                        return ErrGraphNotFound
×
728
                }
×
729

730
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
5,658✔
731
                        // If this is the source key, then we skip this
3,811✔
732
                        // iteration as the value for this key is a pubKey
3,811✔
733
                        // rather than raw node information.
3,811✔
734
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
7,502✔
735
                                return nil
3,691✔
736
                        }
3,691✔
737

738
                        nodeReader := bytes.NewReader(nodeBytes)
123✔
739
                        cacheableNode, err := deserializeLightningNodeCacheable(
123✔
740
                                nodeReader,
123✔
741
                        )
123✔
742
                        if err != nil {
123✔
743
                                return err
×
744
                        }
×
745

746
                        // Execute the callback, the transaction will abort if
747
                        // this returns an error.
748
                        return cb(tx, cacheableNode)
123✔
749
                })
750
        }
751

752
        return kvdb.View(c.db, traversal, func() {})
3,694✔
753
}
754

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

769
                node, err := c.sourceNode(nodes)
231✔
770
                if err != nil {
232✔
771
                        return err
1✔
772
                }
1✔
773
                source = node
230✔
774

230✔
775
                return nil
230✔
776
        }, func() {
231✔
777
                source = nil
231✔
778
        })
231✔
779
        if err != nil {
232✔
780
                return nil, err
1✔
781
        }
1✔
782

783
        return source, nil
230✔
784
}
785

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

796
        // With the pubKey of the source node retrieved, we're able to
797
        // fetch the full node information.
798
        node, err := fetchLightningNode(nodes, selfPub)
488✔
799
        if err != nil {
488✔
800
                return nil, err
×
801
        }
×
802

803
        return &node, nil
488✔
804
}
805

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

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

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

826
                // Finally, we commit the information of the lightning node
827
                // itself.
828
                return addLightningNode(tx, node)
119✔
829
        }, func() {})
119✔
830
}
831

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

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

855
                        return addLightningNode(tx, node)
788✔
856
                },
857
        }
858

859
        for _, f := range op {
791✔
860
                f(r)
3✔
861
        }
3✔
862

863
        return c.nodeScheduler.Execute(r)
788✔
864
}
865

866
func addLightningNode(tx kvdb.RwTx, node *LightningNode) error {
976✔
867
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
976✔
868
        if err != nil {
976✔
869
                return err
×
870
        }
×
871

872
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
976✔
873
        if err != nil {
976✔
874
                return err
×
875
        }
×
876

877
        updateIndex, err := nodes.CreateBucketIfNotExists(
976✔
878
                nodeUpdateIndexBucket,
976✔
879
        )
976✔
880
        if err != nil {
976✔
881
                return err
×
882
        }
×
883

884
        return putLightningNode(nodes, aliases, updateIndex, node)
976✔
885
}
886

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

5✔
892
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
893
                nodes := tx.ReadBucket(nodeBucket)
5✔
894
                if nodes == nil {
5✔
895
                        return ErrGraphNodesNotFound
×
896
                }
×
897

898
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
5✔
899
                if aliases == nil {
5✔
900
                        return ErrGraphNodesNotFound
×
901
                }
×
902

903
                nodePub := pub.SerializeCompressed()
5✔
904
                a := aliases.Get(nodePub)
5✔
905
                if a == nil {
6✔
906
                        return ErrNodeAliasNotFound
1✔
907
                }
1✔
908

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

920
        return alias, nil
4✔
921
}
922

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

933
                if c.graphCache != nil {
6✔
934
                        c.graphCache.RemoveNode(nodePub)
3✔
935
                }
3✔
936

937
                return c.deleteLightningNode(nodes, nodePub[:])
3✔
938
        }, func() {})
3✔
939
}
940

941
// deleteLightningNode uses an existing database transaction to remove a
942
// vertex/node from the database according to the node's public key.
943
func (c *ChannelGraph) deleteLightningNode(nodes kvdb.RwBucket,
944
        compressedPubKey []byte) error {
67✔
945

67✔
946
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
67✔
947
        if aliases == nil {
67✔
948
                return ErrGraphNodesNotFound
×
949
        }
×
950

951
        if err := aliases.Delete(compressedPubKey); err != nil {
67✔
952
                return err
×
953
        }
×
954

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

963
        if err := nodes.Delete(compressedPubKey); err != nil {
67✔
964
                return err
×
965
        }
×
966

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

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

67✔
982
        return nodeUpdateIndex.Delete(indexKey[:])
67✔
983
}
984

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

1,680✔
994
        var alreadyExists bool
1,680✔
995
        r := &batch.Request{
1,680✔
996
                Reset: func() {
3,360✔
997
                        alreadyExists = false
1,680✔
998
                },
1,680✔
999
                Update: func(tx kvdb.RwTx) error {
1,680✔
1000
                        err := c.addChannelEdge(tx, edge)
1,680✔
1001

1,680✔
1002
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,680✔
1003
                        // succeed, but propagate the error via local state.
1,680✔
1004
                        if err == ErrEdgeAlreadyExist {
1,898✔
1005
                                alreadyExists = true
218✔
1006
                                return nil
218✔
1007
                        }
218✔
1008

1009
                        return err
1,462✔
1010
                },
1011
                OnCommit: func(err error) error {
1,680✔
1012
                        switch {
1,680✔
1013
                        case err != nil:
×
1014
                                return err
×
1015
                        case alreadyExists:
218✔
1016
                                return ErrEdgeAlreadyExist
218✔
1017
                        default:
1,462✔
1018
                                c.rejectCache.remove(edge.ChannelID)
1,462✔
1019
                                c.chanCache.remove(edge.ChannelID)
1,462✔
1020
                                return nil
1,462✔
1021
                        }
1022
                },
1023
        }
1024

1025
        for _, f := range op {
1,683✔
1026
                f(r)
3✔
1027
        }
3✔
1028

1029
        return c.chanScheduler.Execute(r)
1,680✔
1030
}
1031

1032
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1033
// utilize an existing db transaction.
1034
func (c *ChannelGraph) addChannelEdge(tx kvdb.RwTx,
1035
        edge *models.ChannelEdgeInfo) error {
1,680✔
1036

1,680✔
1037
        // Construct the channel's primary key which is the 8-byte channel ID.
1,680✔
1038
        var chanKey [8]byte
1,680✔
1039
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,680✔
1040

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

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

1064
        if c.graphCache != nil {
2,742✔
1065
                c.graphCache.AddChannel(edge, nil, nil)
1,280✔
1066
        }
1,280✔
1067

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

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

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

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

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

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

221✔
1142
        var (
221✔
1143
                upd1Time time.Time
221✔
1144
                upd2Time time.Time
221✔
1145
                exists   bool
221✔
1146
                isZombie bool
221✔
1147
        )
221✔
1148

221✔
1149
        // We'll query the cache with the shared lock held to allow multiple
221✔
1150
        // readers to access values in the cache concurrently if they exist.
221✔
1151
        c.cacheMu.RLock()
221✔
1152
        if entry, ok := c.rejectCache.get(chanID); ok {
289✔
1153
                c.cacheMu.RUnlock()
68✔
1154
                upd1Time = time.Unix(entry.upd1Time, 0)
68✔
1155
                upd2Time = time.Unix(entry.upd2Time, 0)
68✔
1156
                exists, isZombie = entry.flags.unpack()
68✔
1157
                return upd1Time, upd2Time, exists, isZombie, nil
68✔
1158
        }
68✔
1159
        c.cacheMu.RUnlock()
156✔
1160

156✔
1161
        c.cacheMu.Lock()
156✔
1162
        defer c.cacheMu.Unlock()
156✔
1163

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

1174
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
290✔
1175
                edges := tx.ReadBucket(edgeBucket)
145✔
1176
                if edges == nil {
145✔
1177
                        return ErrGraphNoEdgesFound
×
1178
                }
×
1179
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
145✔
1180
                if edgeIndex == nil {
145✔
1181
                        return ErrGraphNoEdgesFound
×
1182
                }
×
1183

1184
                var channelID [8]byte
145✔
1185
                byteOrder.PutUint64(channelID[:], chanID)
145✔
1186

145✔
1187
                // If the edge doesn't exist, then we'll also check our zombie
145✔
1188
                // index.
145✔
1189
                if edgeIndex.Get(channelID[:]) == nil {
243✔
1190
                        exists = false
98✔
1191
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
98✔
1192
                        if zombieIndex != nil {
196✔
1193
                                isZombie, _, _ = isZombieEdge(
98✔
1194
                                        zombieIndex, chanID,
98✔
1195
                                )
98✔
1196
                        }
98✔
1197

1198
                        return nil
98✔
1199
                }
1200

1201
                exists = true
50✔
1202
                isZombie = false
50✔
1203

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

1212
                e1, e2, err := fetchChanEdgePolicies(
50✔
1213
                        edgeIndex, edges, channelID[:],
50✔
1214
                )
50✔
1215
                if err != nil {
50✔
1216
                        return err
×
1217
                }
×
1218

1219
                // As we may have only one of the edges populated, only set the
1220
                // update time if the edge was found in the database.
1221
                if e1 != nil {
71✔
1222
                        upd1Time = e1.LastUpdate
21✔
1223
                }
21✔
1224
                if e2 != nil {
69✔
1225
                        upd2Time = e2.LastUpdate
19✔
1226
                }
19✔
1227

1228
                return nil
50✔
1229
        }, func() {}); err != nil {
145✔
1230
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1231
        }
×
1232

1233
        c.rejectCache.insert(chanID, rejectCacheEntry{
145✔
1234
                upd1Time: upd1Time.Unix(),
145✔
1235
                upd2Time: upd2Time.Unix(),
145✔
1236
                flags:    packRejectFlags(exists, isZombie),
145✔
1237
        })
145✔
1238

145✔
1239
        return upd1Time, upd2Time, exists, isZombie, nil
145✔
1240
}
1241

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

4✔
1252
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
8✔
1253
                edges := tx.ReadWriteBucket(edgeBucket)
4✔
1254
                if edge == nil {
4✔
1255
                        return ErrEdgeNotFound
×
1256
                }
×
1257

1258
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
4✔
1259
                if edgeIndex == nil {
4✔
1260
                        return ErrEdgeNotFound
×
1261
                }
×
1262

1263
                if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo == nil {
4✔
1264
                        return ErrEdgeNotFound
×
1265
                }
×
1266

1267
                if c.graphCache != nil {
8✔
1268
                        c.graphCache.UpdateChannel(edge)
4✔
1269
                }
4✔
1270

1271
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
4✔
1272
        }, func() {})
4✔
1273
}
1274

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

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

237✔
1295
        c.cacheMu.Lock()
237✔
1296
        defer c.cacheMu.Unlock()
237✔
1297

237✔
1298
        var chansClosed []*models.ChannelEdgeInfo
237✔
1299

237✔
1300
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
474✔
1301
                // First grab the edges bucket which houses the information
237✔
1302
                // we'd like to delete
237✔
1303
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
237✔
1304
                if err != nil {
237✔
1305
                        return err
×
1306
                }
×
1307

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

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

135✔
1333
                        var opBytes bytes.Buffer
135✔
1334
                        if err := writeOutpoint(&opBytes, chanPoint); err != nil {
135✔
1335
                                return err
×
1336
                        }
×
1337

1338
                        // First attempt to see if the channel exists within
1339
                        // the database, if not, then we can exit early.
1340
                        chanID := chanIndex.Get(opBytes.Bytes())
135✔
1341
                        if chanID == nil {
250✔
1342
                                continue
115✔
1343
                        }
1344

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

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

1365
                        chansClosed = append(chansClosed, &edgeInfo)
23✔
1366
                }
1367

1368
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
237✔
1369
                if err != nil {
237✔
1370
                        return err
×
1371
                }
×
1372

1373
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
237✔
1374
                if err != nil {
237✔
1375
                        return err
×
1376
                }
×
1377

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

237✔
1384
                var newTip [pruneTipBytes]byte
237✔
1385
                copy(newTip[:], blockHash[:])
237✔
1386

237✔
1387
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
237✔
1388
                if err != nil {
237✔
1389
                        return err
×
1390
                }
×
1391

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

1403
        for _, channel := range chansClosed {
260✔
1404
                c.rejectCache.remove(channel.ChannelID)
23✔
1405
                c.chanCache.remove(channel.ChannelID)
23✔
1406
        }
23✔
1407

1408
        if c.graphCache != nil {
474✔
1409
                log.Debugf("Pruned graph, cache now has %s",
237✔
1410
                        c.graphCache.Stats())
237✔
1411
        }
237✔
1412

1413
        return chansClosed, nil
237✔
1414
}
1415

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

1435
                return c.pruneGraphNodes(nodes, edgeIndex)
27✔
1436
        }, func() {})
27✔
1437
}
1438

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

261✔
1445
        log.Trace("Pruning nodes from graph with no open channels")
261✔
1446

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

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

1466
                var nodePub [33]byte
501✔
1467
                copy(nodePub[:], pubKey)
501✔
1468
                nodeRefCounts[nodePub] = 0
501✔
1469

501✔
1470
                return nil
501✔
1471
        })
1472
        if err != nil {
261✔
1473
                return err
×
1474
        }
×
1475

1476
        // To ensure we never delete the source node, we'll start off by
1477
        // bumping its ref count to 1.
1478
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
261✔
1479

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

189✔
1491
                // With the nodes extracted, we'll increase the ref count of
189✔
1492
                // each of the nodes.
189✔
1493
                nodeRefCounts[node1]++
189✔
1494
                nodeRefCounts[node2]++
189✔
1495

189✔
1496
                return nil
189✔
1497
        })
189✔
1498
        if err != nil {
261✔
1499
                return err
×
1500
        }
×
1501

1502
        // Finally, we'll make a second pass over the set of nodes, and delete
1503
        // any nodes that have a ref count of zero.
1504
        var numNodesPruned int
261✔
1505
        for nodePubKey, refCount := range nodeRefCounts {
762✔
1506
                // If the ref count of the node isn't zero, then we can safely
501✔
1507
                // skip it as it still has edges to or from it within the
501✔
1508
                // graph.
501✔
1509
                if refCount != 0 {
941✔
1510
                        continue
440✔
1511
                }
1512

1513
                if c.graphCache != nil {
128✔
1514
                        c.graphCache.RemoveNode(nodePubKey)
64✔
1515
                }
64✔
1516

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

×
1523
                                log.Warnf("Unable to prune node %x from the "+
×
1524
                                        "graph: %v", nodePubKey, err)
×
1525
                                continue
×
1526
                        }
1527

1528
                        return err
×
1529
                }
1530

1531
                log.Infof("Pruned unconnected node %x from channel graph",
64✔
1532
                        nodePubKey[:])
64✔
1533

64✔
1534
                numNodesPruned++
64✔
1535
        }
1536

1537
        if numNodesPruned > 0 {
309✔
1538
                log.Infof("Pruned %v unconnected nodes from the channel graph",
48✔
1539
                        numNodesPruned)
48✔
1540
        }
48✔
1541

1542
        return nil
261✔
1543
}
1544

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

164✔
1555
        // Every channel having a ShortChannelID starting at 'height'
164✔
1556
        // will no longer be confirmed.
164✔
1557
        startShortChanID := lnwire.ShortChannelID{
164✔
1558
                BlockHeight: height,
164✔
1559
        }
164✔
1560

164✔
1561
        // Delete everything after this height from the db up until the
164✔
1562
        // SCID alias range.
164✔
1563
        endShortChanID := aliasmgr.StartingAlias
164✔
1564

164✔
1565
        // The block height will be the 3 first bytes of the channel IDs.
164✔
1566
        var chanIDStart [8]byte
164✔
1567
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
164✔
1568
        var chanIDEnd [8]byte
164✔
1569
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
164✔
1570

164✔
1571
        c.cacheMu.Lock()
164✔
1572
        defer c.cacheMu.Unlock()
164✔
1573

164✔
1574
        // Keep track of the channels that are removed from the graph.
164✔
1575
        var removedChans []*models.ChannelEdgeInfo
164✔
1576

164✔
1577
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
328✔
1578
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
164✔
1579
                if err != nil {
164✔
1580
                        return err
×
1581
                }
×
1582
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
164✔
1583
                if err != nil {
164✔
1584
                        return err
×
1585
                }
×
1586
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
164✔
1587
                if err != nil {
164✔
1588
                        return err
×
1589
                }
×
1590
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
164✔
1591
                if err != nil {
164✔
1592
                        return err
×
1593
                }
×
1594

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

164✔
1604
                //nolint:lll
164✔
1605
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
164✔
1606
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
251✔
1607
                        edgeInfoReader := bytes.NewReader(v)
87✔
1608
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
87✔
1609
                        if err != nil {
87✔
1610
                                return err
×
1611
                        }
×
1612

1613
                        keys = append(keys, k)
87✔
1614
                        removedChans = append(removedChans, &edgeInfo)
87✔
1615
                }
1616

1617
                for _, k := range keys {
251✔
1618
                        err = c.delChannelEdgeUnsafe(
87✔
1619
                                edges, edgeIndex, chanIndex, zombieIndex,
87✔
1620
                                k, false, false,
87✔
1621
                        )
87✔
1622
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
87✔
1623
                                return err
×
1624
                        }
×
1625
                }
1626

1627
                // Delete all the entries in the prune log having a height
1628
                // greater or equal to the block disconnected.
1629
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
164✔
1630
                if err != nil {
164✔
1631
                        return err
×
1632
                }
×
1633

1634
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
164✔
1635
                if err != nil {
164✔
1636
                        return err
×
1637
                }
×
1638

1639
                var pruneKeyStart [4]byte
164✔
1640
                byteOrder.PutUint32(pruneKeyStart[:], height)
164✔
1641

164✔
1642
                var pruneKeyEnd [4]byte
164✔
1643
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
164✔
1644

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

89✔
1652
                        pruneKeys = append(pruneKeys, k)
89✔
1653
                }
89✔
1654

1655
                for _, k := range pruneKeys {
253✔
1656
                        if err := pruneBucket.Delete(k); err != nil {
89✔
1657
                                return err
×
1658
                        }
×
1659
                }
1660

1661
                return nil
164✔
1662
        }, func() {
164✔
1663
                removedChans = nil
164✔
1664
        }); err != nil {
164✔
1665
                return nil, err
×
1666
        }
×
1667

1668
        for _, channel := range removedChans {
251✔
1669
                c.rejectCache.remove(channel.ChannelID)
87✔
1670
                c.chanCache.remove(channel.ChannelID)
87✔
1671
        }
87✔
1672

1673
        return removedChans, nil
164✔
1674
}
1675

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

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

1696
                pruneCursor := pruneBucket.ReadCursor()
58✔
1697

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

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

39✔
1710
                return nil
39✔
1711
        }, func() {})
58✔
1712
        if err != nil {
80✔
1713
                return nil, 0, err
22✔
1714
        }
22✔
1715

1716
        return &tipHash, tipHeight, nil
39✔
1717
}
1718

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

146✔
1730
        // TODO(roasbeef): possibly delete from node bucket if node has no more
146✔
1731
        // channels
146✔
1732
        // TODO(roasbeef): don't delete both edges?
146✔
1733

146✔
1734
        c.cacheMu.Lock()
146✔
1735
        defer c.cacheMu.Unlock()
146✔
1736

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

1759
                var rawChanID [8]byte
146✔
1760
                for _, chanID := range chanIDs {
231✔
1761
                        byteOrder.PutUint64(rawChanID[:], chanID)
85✔
1762
                        err := c.delChannelEdgeUnsafe(
85✔
1763
                                edges, edgeIndex, chanIndex, zombieIndex,
85✔
1764
                                rawChanID[:], markZombie, strictZombiePruning,
85✔
1765
                        )
85✔
1766
                        if err != nil {
139✔
1767
                                return err
54✔
1768
                        }
54✔
1769
                }
1770

1771
                return nil
92✔
1772
        }, func() {})
146✔
1773
        if err != nil {
200✔
1774
                return err
54✔
1775
        }
54✔
1776

1777
        for _, chanID := range chanIDs {
122✔
1778
                c.rejectCache.remove(chanID)
30✔
1779
                c.chanCache.remove(chanID)
30✔
1780
        }
30✔
1781

1782
        return nil
92✔
1783
}
1784

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

1800
        return chanID, nil
4✔
1801
}
1802

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

1810
        edges := tx.ReadBucket(edgeBucket)
4✔
1811
        if edges == nil {
4✔
1812
                return 0, ErrGraphNoEdgesFound
×
1813
        }
×
1814
        chanIndex := edges.NestedReadBucket(channelPointBucket)
4✔
1815
        if chanIndex == nil {
4✔
1816
                return 0, ErrGraphNoEdgesFound
×
1817
        }
×
1818

1819
        chanIDBytes := chanIndex.Get(b.Bytes())
4✔
1820
        if chanIDBytes == nil {
7✔
1821
                return 0, ErrEdgeNotFound
3✔
1822
        }
3✔
1823

1824
        chanID := byteOrder.Uint64(chanIDBytes)
4✔
1825

4✔
1826
        return chanID, nil
4✔
1827
}
1828

1829
// TODO(roasbeef): allow updates to use Batch?
1830

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

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

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

6✔
1851
                lastChanID, _ := cidCursor.Last()
6✔
1852

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

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

1870
        return cid, nil
6✔
1871
}
1872

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

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

1884
        // Policy2 points to the "second" edge policy of the channel containing
1885
        // the dynamic information required to properly route through the edge.
1886
        Policy2 *models.ChannelEdgePolicy
1887

1888
        // Node1 is "node 1" in the channel. This is the node that would have
1889
        // produced Policy1 if it exists.
1890
        Node1 *LightningNode
1891

1892
        // Node2 is "node 2" in the channel. This is the node that would have
1893
        // produced Policy2 if it exists.
1894
        Node2 *LightningNode
1895
}
1896

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

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

145✔
1909
        c.cacheMu.Lock()
145✔
1910
        defer c.cacheMu.Unlock()
145✔
1911

145✔
1912
        var hits int
145✔
1913
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
290✔
1914
                edges := tx.ReadBucket(edgeBucket)
145✔
1915
                if edges == nil {
145✔
1916
                        return ErrGraphNoEdgesFound
×
1917
                }
×
1918
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
145✔
1919
                if edgeIndex == nil {
145✔
1920
                        return ErrGraphNoEdgesFound
×
1921
                }
×
1922
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
145✔
1923
                if edgeUpdateIndex == nil {
145✔
1924
                        return ErrGraphNoEdgesFound
×
1925
                }
×
1926

1927
                nodes := tx.ReadBucket(nodeBucket)
145✔
1928
                if nodes == nil {
145✔
1929
                        return ErrGraphNodesNotFound
×
1930
                }
×
1931

1932
                // We'll now obtain a cursor to perform a range query within
1933
                // the index to find all channels within the horizon.
1934
                updateCursor := edgeUpdateIndex.ReadCursor()
145✔
1935

145✔
1936
                var startTimeBytes, endTimeBytes [8 + 8]byte
145✔
1937
                byteOrder.PutUint64(
145✔
1938
                        startTimeBytes[:8], uint64(startTime.Unix()),
145✔
1939
                )
145✔
1940
                byteOrder.PutUint64(
145✔
1941
                        endTimeBytes[:8], uint64(endTime.Unix()),
145✔
1942
                )
145✔
1943

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

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

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

1962
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
41✔
1963
                                hits++
11✔
1964
                                edgesSeen[chanIDInt] = struct{}{}
11✔
1965
                                edgesInHorizon = append(edgesInHorizon, channel)
11✔
1966
                                continue
11✔
1967
                        }
1968

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

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

1989
                        node1, err := fetchLightningNode(
21✔
1990
                                nodes, edgeInfo.NodeKey1Bytes[:],
21✔
1991
                        )
21✔
1992
                        if err != nil {
21✔
1993
                                return err
×
1994
                        }
×
1995

1996
                        node2, err := fetchLightningNode(
21✔
1997
                                nodes, edgeInfo.NodeKey2Bytes[:],
21✔
1998
                        )
21✔
1999
                        if err != nil {
21✔
2000
                                return err
×
2001
                        }
×
2002

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

2017
                return nil
145✔
2018
        }, func() {
145✔
2019
                edgesSeen = make(map[uint64]struct{})
145✔
2020
                edgesToCache = make(map[uint64]ChannelEdge)
145✔
2021
                edgesInHorizon = nil
145✔
2022
        })
145✔
2023
        switch {
145✔
2024
        case err == ErrGraphNoEdgesFound:
×
2025
                fallthrough
×
2026
        case err == ErrGraphNodesNotFound:
×
2027
                break
×
2028

2029
        case err != nil:
×
2030
                return nil, err
×
2031
        }
2032

2033
        // Insert any edges loaded from disk into the cache.
2034
        for chanid, channel := range edgesToCache {
166✔
2035
                c.chanCache.insert(chanid, channel)
21✔
2036
        }
21✔
2037

2038
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
145✔
2039
                float64(hits)/float64(len(edgesInHorizon)), hits,
145✔
2040
                len(edgesInHorizon))
145✔
2041

145✔
2042
        return edgesInHorizon, nil
145✔
2043
}
2044

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

11✔
2052
        var nodesInHorizon []LightningNode
11✔
2053

11✔
2054
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
22✔
2055
                nodes := tx.ReadBucket(nodeBucket)
11✔
2056
                if nodes == nil {
11✔
2057
                        return ErrGraphNodesNotFound
×
2058
                }
×
2059

2060
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
11✔
2061
                if nodeUpdateIndex == nil {
11✔
2062
                        return ErrGraphNodesNotFound
×
2063
                }
×
2064

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

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

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

32✔
2083
                        nodePub := indexKey[8:]
32✔
2084
                        node, err := fetchLightningNode(nodes, nodePub)
32✔
2085
                        if err != nil {
32✔
2086
                                return err
×
2087
                        }
×
2088

2089
                        nodesInHorizon = append(nodesInHorizon, node)
32✔
2090
                }
2091

2092
                return nil
11✔
2093
        }, func() {
11✔
2094
                nodesInHorizon = nil
11✔
2095
        })
11✔
2096
        switch {
11✔
2097
        case err == ErrGraphNoEdgesFound:
×
2098
                fallthrough
×
2099
        case err == ErrGraphNodesNotFound:
×
2100
                break
×
2101

2102
        case err != nil:
×
2103
                return nil, err
×
2104
        }
2105

2106
        return nodesInHorizon, nil
11✔
2107
}
2108

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

128✔
2117
        var newChanIDs []uint64
128✔
2118

128✔
2119
        c.cacheMu.Lock()
128✔
2120
        defer c.cacheMu.Unlock()
128✔
2121

128✔
2122
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
256✔
2123
                edges := tx.ReadBucket(edgeBucket)
128✔
2124
                if edges == nil {
128✔
2125
                        return ErrGraphNoEdgesFound
×
2126
                }
×
2127
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
128✔
2128
                if edgeIndex == nil {
128✔
2129
                        return ErrGraphNoEdgesFound
×
2130
                }
×
2131

2132
                // Fetch the zombie index, it may not exist if no edges have
2133
                // ever been marked as zombies. If the index has been
2134
                // initialized, we will use it later to skip known zombie edges.
2135
                zombieIndex := edges.NestedReadBucket(zombieBucket)
128✔
2136

128✔
2137
                // We'll run through the set of chanIDs and collate only the
128✔
2138
                // set of channel that are unable to be found within our db.
128✔
2139
                var cidBytes [8]byte
128✔
2140
                for _, info := range chansInfo {
244✔
2141
                        scid := info.ShortChannelID.ToUint64()
116✔
2142
                        byteOrder.PutUint64(cidBytes[:], scid)
116✔
2143

116✔
2144
                        // If the edge is already known, skip it.
116✔
2145
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
135✔
2146
                                continue
19✔
2147
                        }
2148

2149
                        // If the edge is a known zombie, skip it.
2150
                        if zombieIndex != nil {
200✔
2151
                                isZombie, _, _ := isZombieEdge(
100✔
2152
                                        zombieIndex, scid,
100✔
2153
                                )
100✔
2154

100✔
2155
                                // TODO(ziggie): Make sure that for the strict
100✔
2156
                                // pruning case we compare the pubkeys and
100✔
2157
                                // whether the right timestamp is not older than
100✔
2158
                                // the `ChannelPruneExpiry`.
100✔
2159
                                //
100✔
2160
                                // NOTE: The timestamp data has no verification
100✔
2161
                                // attached to it in the `ReplyChannelRange` msg
100✔
2162
                                // so we are trusting this data at this point.
100✔
2163
                                // However it is not critical because we are
100✔
2164
                                // just removing the channel from the db when
100✔
2165
                                // the timestamps are more recent. During the
100✔
2166
                                // querying of the gossip msg verification
100✔
2167
                                // happens as usual.
100✔
2168
                                // However we should start punishing peers when
100✔
2169
                                // they don't provide us honest data ?
100✔
2170
                                isStillZombie := isZombieChan(
100✔
2171
                                        info.Node1UpdateTimestamp,
100✔
2172
                                        info.Node2UpdateTimestamp,
100✔
2173
                                )
100✔
2174

100✔
2175
                                switch {
100✔
2176
                                // If the edge is a known zombie and if we
2177
                                // would still consider it a zombie given the
2178
                                // latest update timestamps, then we skip this
2179
                                // channel.
2180
                                case isZombie && isStillZombie:
25✔
2181
                                        continue
25✔
2182

2183
                                // Otherwise, if we have marked it as a zombie
2184
                                // but the latest update timestamps could bring
2185
                                // it back from the dead, then we mark it alive,
2186
                                // and we let it be added to the set of IDs to
2187
                                // query our peer for.
2188
                                case isZombie && !isStillZombie:
22✔
2189
                                        err := c.markEdgeLiveUnsafe(tx, scid)
22✔
2190
                                        if err != nil {
22✔
2191
                                                return err
×
2192
                                        }
×
2193
                                }
2194
                        }
2195

2196
                        newChanIDs = append(newChanIDs, scid)
75✔
2197
                }
2198

2199
                return nil
128✔
2200
        }, func() {
128✔
2201
                newChanIDs = nil
128✔
2202
        })
128✔
2203
        switch {
128✔
2204
        // If we don't know of any edges yet, then we'll return the entire set
2205
        // of chan IDs specified.
2206
        case err == ErrGraphNoEdgesFound:
×
2207
                ogChanIDs := make([]uint64, len(chansInfo))
×
2208
                for i, info := range chansInfo {
×
2209
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2210
                }
×
2211

2212
                return ogChanIDs, nil
×
2213

2214
        case err != nil:
×
2215
                return nil, err
×
2216
        }
2217

2218
        return newChanIDs, nil
128✔
2219
}
2220

2221
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2222
// latest received channel updates for the channel.
2223
type ChannelUpdateInfo struct {
2224
        // ShortChannelID is the SCID identifier of the channel.
2225
        ShortChannelID lnwire.ShortChannelID
2226

2227
        // Node1UpdateTimestamp is the timestamp of the latest received update
2228
        // from the node 1 channel peer. This will be set to zero time if no
2229
        // update has yet been received from this node.
2230
        Node1UpdateTimestamp time.Time
2231

2232
        // Node2UpdateTimestamp is the timestamp of the latest received update
2233
        // from the node 2 channel peer. This will be set to zero time if no
2234
        // update has yet been received from this node.
2235
        Node2UpdateTimestamp time.Time
2236
}
2237

2238
// NewChannelUpdateInfo is a constructor which makes sure we initialize the
2239
// timestamps with zero seconds unix timestamp which equals
2240
// `January 1, 1970, 00:00:00 UTC` in case the value is `time.Time{}`.
2241
func NewChannelUpdateInfo(scid lnwire.ShortChannelID, node1Timestamp,
2242
        node2Timestamp time.Time) ChannelUpdateInfo {
221✔
2243

221✔
2244
        chanInfo := ChannelUpdateInfo{
221✔
2245
                ShortChannelID:       scid,
221✔
2246
                Node1UpdateTimestamp: node1Timestamp,
221✔
2247
                Node2UpdateTimestamp: node2Timestamp,
221✔
2248
        }
221✔
2249

221✔
2250
        if node1Timestamp.IsZero() {
432✔
2251
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
211✔
2252
        }
211✔
2253

2254
        if node2Timestamp.IsZero() {
432✔
2255
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
211✔
2256
        }
211✔
2257

2258
        return chanInfo
221✔
2259
}
2260

2261
// BlockChannelRange represents a range of channels for a given block height.
2262
type BlockChannelRange struct {
2263
        // Height is the height of the block all of the channels below were
2264
        // included in.
2265
        Height uint32
2266

2267
        // Channels is the list of channels identified by their short ID
2268
        // representation known to us that were included in the block height
2269
        // above. The list may include channel update timestamp information if
2270
        // requested.
2271
        Channels []ChannelUpdateInfo
2272
}
2273

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

14✔
2284
        startChanID := &lnwire.ShortChannelID{
14✔
2285
                BlockHeight: startHeight,
14✔
2286
        }
14✔
2287

14✔
2288
        endChanID := lnwire.ShortChannelID{
14✔
2289
                BlockHeight: endHeight,
14✔
2290
                TxIndex:     math.MaxUint32 & 0x00ffffff,
14✔
2291
                TxPosition:  math.MaxUint16,
14✔
2292
        }
14✔
2293

14✔
2294
        // As we need to perform a range scan, we'll convert the starting and
14✔
2295
        // ending height to their corresponding values when encoded using short
14✔
2296
        // channel ID's.
14✔
2297
        var chanIDStart, chanIDEnd [8]byte
14✔
2298
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
14✔
2299
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
14✔
2300

14✔
2301
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
14✔
2302
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
2303
                edges := tx.ReadBucket(edgeBucket)
14✔
2304
                if edges == nil {
14✔
2305
                        return ErrGraphNoEdgesFound
×
2306
                }
×
2307
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
2308
                if edgeIndex == nil {
14✔
2309
                        return ErrGraphNoEdgesFound
×
2310
                }
×
2311

2312
                cursor := edgeIndex.ReadCursor()
14✔
2313

14✔
2314
                // We'll now iterate through the database, and find each
14✔
2315
                // channel ID that resides within the specified range.
14✔
2316
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
14✔
2317
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
61✔
2318
                        // Don't send alias SCIDs during gossip sync.
47✔
2319
                        edgeReader := bytes.NewReader(v)
47✔
2320
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
47✔
2321
                        if err != nil {
47✔
2322
                                return err
×
2323
                        }
×
2324

2325
                        if edgeInfo.AuthProof == nil {
50✔
2326
                                continue
3✔
2327
                        }
2328

2329
                        // This channel ID rests within the target range, so
2330
                        // we'll add it to our returned set.
2331
                        rawCid := byteOrder.Uint64(k)
47✔
2332
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
47✔
2333

47✔
2334
                        chanInfo := NewChannelUpdateInfo(
47✔
2335
                                cid, time.Time{}, time.Time{},
47✔
2336
                        )
47✔
2337

47✔
2338
                        if !withTimestamps {
69✔
2339
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2340
                                        channelsPerBlock[cid.BlockHeight],
22✔
2341
                                        chanInfo,
22✔
2342
                                )
22✔
2343

22✔
2344
                                continue
22✔
2345
                        }
2346

2347
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
25✔
2348

25✔
2349
                        rawPolicy := edges.Get(node1Key)
25✔
2350
                        if len(rawPolicy) != 0 {
34✔
2351
                                r := bytes.NewReader(rawPolicy)
9✔
2352

9✔
2353
                                edge, err := deserializeChanEdgePolicyRaw(r)
9✔
2354
                                if err != nil && !errors.Is(
9✔
2355
                                        err, ErrEdgePolicyOptionalFieldNotFound,
9✔
2356
                                ) {
9✔
2357

×
2358
                                        return err
×
2359
                                }
×
2360

2361
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
9✔
2362
                        }
2363

2364
                        rawPolicy = edges.Get(node2Key)
25✔
2365
                        if len(rawPolicy) != 0 {
39✔
2366
                                r := bytes.NewReader(rawPolicy)
14✔
2367

14✔
2368
                                edge, err := deserializeChanEdgePolicyRaw(r)
14✔
2369
                                if err != nil && !errors.Is(
14✔
2370
                                        err, ErrEdgePolicyOptionalFieldNotFound,
14✔
2371
                                ) {
14✔
2372

×
2373
                                        return err
×
2374
                                }
×
2375

2376
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
14✔
2377
                        }
2378

2379
                        channelsPerBlock[cid.BlockHeight] = append(
25✔
2380
                                channelsPerBlock[cid.BlockHeight], chanInfo,
25✔
2381
                        )
25✔
2382
                }
2383

2384
                return nil
14✔
2385
        }, func() {
14✔
2386
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
14✔
2387
        })
14✔
2388

2389
        switch {
14✔
2390
        // If we don't know of any channels yet, then there's nothing to
2391
        // filter, so we'll return an empty slice.
2392
        case err == ErrGraphNoEdgesFound || len(channelsPerBlock) == 0:
6✔
2393
                return nil, nil
6✔
2394

2395
        case err != nil:
×
2396
                return nil, err
×
2397
        }
2398

2399
        // Return the channel ranges in ascending block height order.
2400
        blocks := make([]uint32, 0, len(channelsPerBlock))
11✔
2401
        for block := range channelsPerBlock {
36✔
2402
                blocks = append(blocks, block)
25✔
2403
        }
25✔
2404
        sort.Slice(blocks, func(i, j int) bool {
36✔
2405
                return blocks[i] < blocks[j]
25✔
2406
        })
25✔
2407

2408
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
11✔
2409
        for _, block := range blocks {
36✔
2410
                channelRanges = append(channelRanges, BlockChannelRange{
25✔
2411
                        Height:   block,
25✔
2412
                        Channels: channelsPerBlock[block],
25✔
2413
                })
25✔
2414
        }
25✔
2415

2416
        return channelRanges, nil
11✔
2417
}
2418

2419
// FetchChanInfos returns the set of channel edges that correspond to the passed
2420
// channel ID's. If an edge is the query is unknown to the database, it will
2421
// skipped and the result will contain only those edges that exist at the time
2422
// of the query. This can be used to respond to peer queries that are seeking to
2423
// fill in gaps in their view of the channel graph.
2424
func (c *ChannelGraph) FetchChanInfos(chanIDs []uint64) ([]ChannelEdge, error) {
6✔
2425
        return c.fetchChanInfos(nil, chanIDs)
6✔
2426
}
6✔
2427

2428
// fetchChanInfos returns the set of channel edges that correspond to the passed
2429
// channel ID's. If an edge is the query is unknown to the database, it will
2430
// skipped and the result will contain only those edges that exist at the time
2431
// of the query. This can be used to respond to peer queries that are seeking to
2432
// fill in gaps in their view of the channel graph.
2433
//
2434
// NOTE: An optional transaction may be provided. If none is provided, then a
2435
// new one will be created.
2436
func (c *ChannelGraph) fetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2437
        []ChannelEdge, error) {
29✔
2438
        // TODO(roasbeef): sort cids?
29✔
2439

29✔
2440
        var (
29✔
2441
                chanEdges []ChannelEdge
29✔
2442
                cidBytes  [8]byte
29✔
2443
        )
29✔
2444

29✔
2445
        fetchChanInfos := func(tx kvdb.RTx) error {
58✔
2446
                edges := tx.ReadBucket(edgeBucket)
29✔
2447
                if edges == nil {
29✔
2448
                        return ErrGraphNoEdgesFound
×
2449
                }
×
2450
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
29✔
2451
                if edgeIndex == nil {
29✔
2452
                        return ErrGraphNoEdgesFound
×
2453
                }
×
2454
                nodes := tx.ReadBucket(nodeBucket)
29✔
2455
                if nodes == nil {
29✔
2456
                        return ErrGraphNotFound
×
2457
                }
×
2458

2459
                for _, cid := range chanIDs {
65✔
2460
                        byteOrder.PutUint64(cidBytes[:], cid)
36✔
2461

36✔
2462
                        // First, we'll fetch the static edge information. If
36✔
2463
                        // the edge is unknown, we will skip the edge and
36✔
2464
                        // continue gathering all known edges.
36✔
2465
                        edgeInfo, err := fetchChanEdgeInfo(
36✔
2466
                                edgeIndex, cidBytes[:],
36✔
2467
                        )
36✔
2468
                        switch {
36✔
2469
                        case errors.Is(err, ErrEdgeNotFound):
28✔
2470
                                continue
28✔
2471
                        case err != nil:
×
2472
                                return err
×
2473
                        }
2474

2475
                        // With the static information obtained, we'll now
2476
                        // fetch the dynamic policy info.
2477
                        edge1, edge2, err := fetchChanEdgePolicies(
11✔
2478
                                edgeIndex, edges, cidBytes[:],
11✔
2479
                        )
11✔
2480
                        if err != nil {
11✔
2481
                                return err
×
2482
                        }
×
2483

2484
                        node1, err := fetchLightningNode(
11✔
2485
                                nodes, edgeInfo.NodeKey1Bytes[:],
11✔
2486
                        )
11✔
2487
                        if err != nil {
11✔
2488
                                return err
×
2489
                        }
×
2490

2491
                        node2, err := fetchLightningNode(
11✔
2492
                                nodes, edgeInfo.NodeKey2Bytes[:],
11✔
2493
                        )
11✔
2494
                        if err != nil {
11✔
2495
                                return err
×
2496
                        }
×
2497

2498
                        chanEdges = append(chanEdges, ChannelEdge{
11✔
2499
                                Info:    &edgeInfo,
11✔
2500
                                Policy1: edge1,
11✔
2501
                                Policy2: edge2,
11✔
2502
                                Node1:   &node1,
11✔
2503
                                Node2:   &node2,
11✔
2504
                        })
11✔
2505
                }
2506
                return nil
29✔
2507
        }
2508

2509
        if tx == nil {
36✔
2510
                err := kvdb.View(c.db, fetchChanInfos, func() {
14✔
2511
                        chanEdges = nil
7✔
2512
                })
7✔
2513
                if err != nil {
7✔
2514
                        return nil, err
×
2515
                }
×
2516

2517
                return chanEdges, nil
7✔
2518
        }
2519

2520
        err := fetchChanInfos(tx)
22✔
2521
        if err != nil {
22✔
2522
                return nil, err
×
2523
        }
×
2524

2525
        return chanEdges, nil
22✔
2526
}
2527

2528
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2529
        edge1, edge2 *models.ChannelEdgePolicy) error {
136✔
2530

136✔
2531
        // First, we'll fetch the edge update index bucket which currently
136✔
2532
        // stores an entry for the channel we're about to delete.
136✔
2533
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
136✔
2534
        if updateIndex == nil {
136✔
2535
                // No edges in bucket, return early.
×
2536
                return nil
×
2537
        }
×
2538

2539
        // Now that we have the bucket, we'll attempt to construct a template
2540
        // for the index key: updateTime || chanid.
2541
        var indexKey [8 + 8]byte
136✔
2542
        byteOrder.PutUint64(indexKey[8:], chanID)
136✔
2543

136✔
2544
        // With the template constructed, we'll attempt to delete an entry that
136✔
2545
        // would have been created by both edges: we'll alternate the update
136✔
2546
        // times, as one may had overridden the other.
136✔
2547
        if edge1 != nil {
149✔
2548
                byteOrder.PutUint64(indexKey[:8], uint64(edge1.LastUpdate.Unix()))
13✔
2549
                if err := updateIndex.Delete(indexKey[:]); err != nil {
13✔
2550
                        return err
×
2551
                }
×
2552
        }
2553

2554
        // We'll also attempt to delete the entry that may have been created by
2555
        // the second edge.
2556
        if edge2 != nil {
151✔
2557
                byteOrder.PutUint64(indexKey[:8], uint64(edge2.LastUpdate.Unix()))
15✔
2558
                if err := updateIndex.Delete(indexKey[:]); err != nil {
15✔
2559
                        return err
×
2560
                }
×
2561
        }
2562

2563
        return nil
136✔
2564
}
2565

2566
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2567
// cache. It then goes on to delete any policy info and edge info for this
2568
// channel from the DB and finally, if isZombie is true, it will add an entry
2569
// for this channel in the zombie index.
2570
//
2571
// NOTE: this method MUST only be called if the cacheMu has already been
2572
// acquired.
2573
func (c *ChannelGraph) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2574
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2575
        strictZombie bool) error {
190✔
2576

190✔
2577
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
190✔
2578
        if err != nil {
244✔
2579
                return err
54✔
2580
        }
54✔
2581

2582
        if c.graphCache != nil {
272✔
2583
                c.graphCache.RemoveChannel(
136✔
2584
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
136✔
2585
                        edgeInfo.ChannelID,
136✔
2586
                )
136✔
2587
        }
136✔
2588

2589
        // We'll also remove the entry in the edge update index bucket before
2590
        // we delete the edges themselves so we can access their last update
2591
        // times.
2592
        cid := byteOrder.Uint64(chanID)
136✔
2593
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
136✔
2594
        if err != nil {
136✔
2595
                return err
×
2596
        }
×
2597
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
136✔
2598
        if err != nil {
136✔
2599
                return err
×
2600
        }
×
2601

2602
        // The edge key is of the format pubKey || chanID. First we construct
2603
        // the latter half, populating the channel ID.
2604
        var edgeKey [33 + 8]byte
136✔
2605
        copy(edgeKey[33:], chanID)
136✔
2606

136✔
2607
        // With the latter half constructed, copy over the first public key to
136✔
2608
        // delete the edge in this direction, then the second to delete the
136✔
2609
        // edge in the opposite direction.
136✔
2610
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
136✔
2611
        if edges.Get(edgeKey[:]) != nil {
272✔
2612
                if err := edges.Delete(edgeKey[:]); err != nil {
136✔
2613
                        return err
×
2614
                }
×
2615
        }
2616
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
136✔
2617
        if edges.Get(edgeKey[:]) != nil {
272✔
2618
                if err := edges.Delete(edgeKey[:]); err != nil {
136✔
2619
                        return err
×
2620
                }
×
2621
        }
2622

2623
        // As part of deleting the edge we also remove all disabled entries
2624
        // from the edgePolicyDisabledIndex bucket. We do that for both directions.
2625
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
136✔
2626
        if err != nil {
136✔
NEW
2627
                return err
×
NEW
2628
        }
×
2629
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
136✔
2630
        if err != nil {
136✔
NEW
2631
                return err
×
NEW
2632
        }
×
2633

2634
        // With the edge data deleted, we can purge the information from the two
2635
        // edge indexes.
2636
        if err := edgeIndex.Delete(chanID); err != nil {
136✔
2637
                return err
×
2638
        }
×
2639
        var b bytes.Buffer
136✔
2640
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
136✔
2641
                return err
×
2642
        }
×
2643
        if err := chanIndex.Delete(b.Bytes()); err != nil {
136✔
2644
                return err
×
2645
        }
×
2646

2647
        // Finally, we'll mark the edge as a zombie within our index if it's
2648
        // being removed due to the channel becoming a zombie. We do this to
2649
        // ensure we don't store unnecessary data for spent channels.
2650
        if !isZombie {
247✔
2651
                return nil
111✔
2652
        }
111✔
2653

2654
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
28✔
2655
        if strictZombie {
33✔
2656
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
5✔
2657
        }
5✔
2658

2659
        return markEdgeZombie(
28✔
2660
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
28✔
2661
        )
28✔
2662
}
2663

2664
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2665
// particular pair of channel policies. The return values are one of:
2666
//  1. (pubkey1, pubkey2)
2667
//  2. (pubkey1, blank)
2668
//  3. (blank, pubkey2)
2669
//
2670
// A blank pubkey means that corresponding node will be unable to resurrect a
2671
// channel on its own. For example, node1 may continue to publish recent
2672
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2673
// we don't want another fresh update from node1 to resurrect, as the edge can
2674
// only become live once node2 finally sends something recent.
2675
//
2676
// In the case where we have neither update, we allow either party to resurrect
2677
// the channel. If the channel were to be marked zombie again, it would be
2678
// marked with the correct lagging channel since we received an update from only
2679
// one side.
2680
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
2681
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
5✔
2682

5✔
2683
        switch {
5✔
2684
        // If we don't have either edge policy, we'll return both pubkeys so
2685
        // that the channel can be resurrected by either party.
2686
        case e1 == nil && e2 == nil:
2✔
2687
                return info.NodeKey1Bytes, info.NodeKey2Bytes
2✔
2688

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

2696
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2697
        // return a blank pubkey for edge1. In this case, only an update from
2698
        // edge2 can resurect the channel.
2699
        default:
2✔
2700
                return [33]byte{}, info.NodeKey2Bytes
2✔
2701
        }
2702
}
2703

2704
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2705
// within the database for the referenced channel. The `flags` attribute within
2706
// the ChannelEdgePolicy determines which of the directed edges are being
2707
// updated. If the flag is 1, then the first node's information is being
2708
// updated, otherwise it's the second node's information. The node ordering is
2709
// determined by the lexicographical ordering of the identity public keys of the
2710
// nodes on either side of the channel.
2711
func (c *ChannelGraph) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2712
        op ...batch.SchedulerOption) error {
2,634✔
2713

2,634✔
2714
        var (
2,634✔
2715
                isUpdate1    bool
2,634✔
2716
                edgeNotFound bool
2,634✔
2717
        )
2,634✔
2718

2,634✔
2719
        r := &batch.Request{
2,634✔
2720
                Reset: func() {
5,268✔
2721
                        isUpdate1 = false
2,634✔
2722
                        edgeNotFound = false
2,634✔
2723
                },
2,634✔
2724
                Update: func(tx kvdb.RwTx) error {
2,634✔
2725
                        var err error
2,634✔
2726
                        isUpdate1, err = updateEdgePolicy(
2,634✔
2727
                                tx, edge, c.graphCache,
2,634✔
2728
                        )
2,634✔
2729

2,634✔
2730
                        // Silence ErrEdgeNotFound so that the batch can
2,634✔
2731
                        // succeed, but propagate the error via local state.
2,634✔
2732
                        if errors.Is(err, ErrEdgeNotFound) {
2,637✔
2733
                                edgeNotFound = true
3✔
2734
                                return nil
3✔
2735
                        }
3✔
2736

2737
                        return err
2,631✔
2738
                },
2739
                OnCommit: func(err error) error {
2,634✔
2740
                        switch {
2,634✔
2741
                        case err != nil:
×
2742
                                return err
×
2743
                        case edgeNotFound:
3✔
2744
                                return ErrEdgeNotFound
3✔
2745
                        default:
2,631✔
2746
                                c.updateEdgeCache(edge, isUpdate1)
2,631✔
2747
                                return nil
2,631✔
2748
                        }
2749
                },
2750
        }
2751

2752
        for _, f := range op {
2,637✔
2753
                f(r)
3✔
2754
        }
3✔
2755

2756
        return c.chanScheduler.Execute(r)
2,634✔
2757
}
2758

2759
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2760
        isUpdate1 bool) {
2,631✔
2761

2,631✔
2762
        // If an entry for this channel is found in reject cache, we'll modify
2,631✔
2763
        // the entry with the updated timestamp for the direction that was just
2,631✔
2764
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,631✔
2765
        // during the next query for this edge.
2,631✔
2766
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,639✔
2767
                if isUpdate1 {
14✔
2768
                        entry.upd1Time = e.LastUpdate.Unix()
6✔
2769
                } else {
11✔
2770
                        entry.upd2Time = e.LastUpdate.Unix()
5✔
2771
                }
5✔
2772
                c.rejectCache.insert(e.ChannelID, entry)
8✔
2773
        }
2774

2775
        // If an entry for this channel is found in channel cache, we'll modify
2776
        // the entry with the updated policy for the direction that was just
2777
        // written. If the edge doesn't exist, we'll defer loading the info and
2778
        // policies and lazily read from disk during the next query.
2779
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
2,634✔
2780
                if isUpdate1 {
6✔
2781
                        channel.Policy1 = e
3✔
2782
                } else {
6✔
2783
                        channel.Policy2 = e
3✔
2784
                }
3✔
2785
                c.chanCache.insert(e.ChannelID, channel)
3✔
2786
        }
2787
}
2788

2789
// updateEdgePolicy attempts to update an edge's policy within the relevant
2790
// buckets using an existing database transaction. The returned boolean will be
2791
// true if the updated policy belongs to node1, and false if the policy belonged
2792
// to node2.
2793
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy,
2794
        graphCache *GraphCache) (bool, error) {
2,634✔
2795

2,634✔
2796
        edges := tx.ReadWriteBucket(edgeBucket)
2,634✔
2797
        if edges == nil {
2,634✔
2798
                return false, ErrEdgeNotFound
×
2799
        }
×
2800
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,634✔
2801
        if edgeIndex == nil {
2,634✔
2802
                return false, ErrEdgeNotFound
×
2803
        }
×
2804

2805
        // Create the channelID key be converting the channel ID
2806
        // integer into a byte slice.
2807
        var chanID [8]byte
2,634✔
2808
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,634✔
2809

2,634✔
2810
        // With the channel ID, we then fetch the value storing the two
2,634✔
2811
        // nodes which connect this channel edge.
2,634✔
2812
        nodeInfo := edgeIndex.Get(chanID[:])
2,634✔
2813
        if nodeInfo == nil {
2,637✔
2814
                return false, ErrEdgeNotFound
3✔
2815
        }
3✔
2816

2817
        // Depending on the flags value passed above, either the first
2818
        // or second edge policy is being updated.
2819
        var fromNode, toNode []byte
2,631✔
2820
        var isUpdate1 bool
2,631✔
2821
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3,952✔
2822
                fromNode = nodeInfo[:33]
1,321✔
2823
                toNode = nodeInfo[33:66]
1,321✔
2824
                isUpdate1 = true
1,321✔
2825
        } else {
2,634✔
2826
                fromNode = nodeInfo[33:66]
1,313✔
2827
                toNode = nodeInfo[:33]
1,313✔
2828
                isUpdate1 = false
1,313✔
2829
        }
1,313✔
2830

2831
        // Finally, with the direction of the edge being updated
2832
        // identified, we update the on-disk edge representation.
2833
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,631✔
2834
        if err != nil {
2,631✔
2835
                return false, err
×
2836
        }
×
2837

2838
        var (
2,631✔
2839
                fromNodePubKey route.Vertex
2,631✔
2840
                toNodePubKey   route.Vertex
2,631✔
2841
        )
2,631✔
2842
        copy(fromNodePubKey[:], fromNode)
2,631✔
2843
        copy(toNodePubKey[:], toNode)
2,631✔
2844

2,631✔
2845
        if graphCache != nil {
4,892✔
2846
                graphCache.UpdatePolicy(
2,261✔
2847
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,261✔
2848
                )
2,261✔
2849
        }
2,261✔
2850

2851
        return isUpdate1, nil
2,631✔
2852
}
2853

2854
// LightningNode represents an individual vertex/node within the channel graph.
2855
// A node is connected to other nodes by one or more channel edges emanating
2856
// from it. As the graph is directed, a node will also have an incoming edge
2857
// attached to it for each outgoing edge.
2858
type LightningNode struct {
2859
        // PubKeyBytes is the raw bytes of the public key of the target node.
2860
        PubKeyBytes [33]byte
2861
        pubKey      *btcec.PublicKey
2862

2863
        // HaveNodeAnnouncement indicates whether we received a node
2864
        // announcement for this particular node. If true, the remaining fields
2865
        // will be set, if false only the PubKey is known for this node.
2866
        HaveNodeAnnouncement bool
2867

2868
        // LastUpdate is the last time the vertex information for this node has
2869
        // been updated.
2870
        LastUpdate time.Time
2871

2872
        // Address is the TCP address this node is reachable over.
2873
        Addresses []net.Addr
2874

2875
        // Color is the selected color for the node.
2876
        Color color.RGBA
2877

2878
        // Alias is a nick-name for the node. The alias can be used to confirm
2879
        // a node's identity or to serve as a short ID for an address book.
2880
        Alias string
2881

2882
        // AuthSigBytes is the raw signature under the advertised public key
2883
        // which serves to authenticate the attributes announced by this node.
2884
        AuthSigBytes []byte
2885

2886
        // Features is the list of protocol features supported by this node.
2887
        Features *lnwire.FeatureVector
2888

2889
        // ExtraOpaqueData is the set of data that was appended to this
2890
        // message, some of which we may not actually know how to iterate or
2891
        // parse. By holding onto this data, we ensure that we're able to
2892
        // properly validate the set of signatures that cover these new fields,
2893
        // and ensure we're able to make upgrades to the network in a forwards
2894
        // compatible manner.
2895
        ExtraOpaqueData []byte
2896

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

2900
        // TODO(roasbeef): add update method and fetch?
2901
}
2902

2903
// PubKey is the node's long-term identity public key. This key will be used to
2904
// authenticated any advertisements/updates sent by the node.
2905
//
2906
// NOTE: By having this method to access an attribute, we ensure we only need
2907
// to fully deserialize the pubkey if absolutely necessary.
2908
func (l *LightningNode) PubKey() (*btcec.PublicKey, error) {
1,448✔
2909
        if l.pubKey != nil {
1,922✔
2910
                return l.pubKey, nil
474✔
2911
        }
474✔
2912

2913
        key, err := btcec.ParsePubKey(l.PubKeyBytes[:])
977✔
2914
        if err != nil {
977✔
2915
                return nil, err
×
2916
        }
×
2917
        l.pubKey = key
977✔
2918

977✔
2919
        return key, nil
977✔
2920
}
2921

2922
// AuthSig is a signature under the advertised public key which serves to
2923
// authenticate the attributes announced by this node.
2924
//
2925
// NOTE: By having this method to access an attribute, we ensure we only need
2926
// to fully deserialize the signature if absolutely necessary.
2927
func (l *LightningNode) AuthSig() (*ecdsa.Signature, error) {
×
2928
        return ecdsa.ParseSignature(l.AuthSigBytes)
×
2929
}
×
2930

2931
// AddPubKey is a setter-link method that can be used to swap out the public
2932
// key for a node.
2933
func (l *LightningNode) AddPubKey(key *btcec.PublicKey) {
63✔
2934
        l.pubKey = key
63✔
2935
        copy(l.PubKeyBytes[:], key.SerializeCompressed())
63✔
2936
}
63✔
2937

2938
// NodeAnnouncement retrieves the latest node announcement of the node.
2939
func (l *LightningNode) NodeAnnouncement(signed bool) (*lnwire.NodeAnnouncement,
2940
        error) {
17✔
2941

17✔
2942
        if !l.HaveNodeAnnouncement {
20✔
2943
                return nil, fmt.Errorf("node does not have node announcement")
3✔
2944
        }
3✔
2945

2946
        alias, err := lnwire.NewNodeAlias(l.Alias)
17✔
2947
        if err != nil {
17✔
2948
                return nil, err
×
2949
        }
×
2950

2951
        nodeAnn := &lnwire.NodeAnnouncement{
17✔
2952
                Features:        l.Features.RawFeatureVector,
17✔
2953
                NodeID:          l.PubKeyBytes,
17✔
2954
                RGBColor:        l.Color,
17✔
2955
                Alias:           alias,
17✔
2956
                Addresses:       l.Addresses,
17✔
2957
                Timestamp:       uint32(l.LastUpdate.Unix()),
17✔
2958
                ExtraOpaqueData: l.ExtraOpaqueData,
17✔
2959
        }
17✔
2960

17✔
2961
        if !signed {
20✔
2962
                return nodeAnn, nil
3✔
2963
        }
3✔
2964

2965
        sig, err := lnwire.NewSigFromECDSARawSignature(l.AuthSigBytes)
17✔
2966
        if err != nil {
17✔
2967
                return nil, err
×
2968
        }
×
2969

2970
        nodeAnn.Signature = sig
17✔
2971

17✔
2972
        return nodeAnn, nil
17✔
2973
}
2974

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

16✔
2981
        // In order to determine whether this node is publicly advertised within
16✔
2982
        // the graph, we'll need to look at all of its edges and check whether
16✔
2983
        // they extend to any other node than the source node. errDone will be
16✔
2984
        // used to terminate the check early.
16✔
2985
        nodeIsPublic := false
16✔
2986
        errDone := errors.New("done")
16✔
2987
        err := c.ForEachNodeChannelTx(tx, nodePub, func(tx kvdb.RTx,
16✔
2988
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
16✔
2989
                _ *models.ChannelEdgePolicy) error {
29✔
2990

13✔
2991
                // If this edge doesn't extend to the source node, we'll
13✔
2992
                // terminate our search as we can now conclude that the node is
13✔
2993
                // publicly advertised within the graph due to the local node
13✔
2994
                // knowing of the current edge.
13✔
2995
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
13✔
2996
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
19✔
2997

6✔
2998
                        nodeIsPublic = true
6✔
2999
                        return errDone
6✔
3000
                }
6✔
3001

3002
                // Since the edge _does_ extend to the source node, we'll also
3003
                // need to ensure that this is a public edge.
3004
                if info.AuthProof != nil {
19✔
3005
                        nodeIsPublic = true
9✔
3006
                        return errDone
9✔
3007
                }
9✔
3008

3009
                // Otherwise, we'll continue our search.
3010
                return nil
4✔
3011
        })
3012
        if err != nil && err != errDone {
16✔
3013
                return false, err
×
3014
        }
×
3015

3016
        return nodeIsPublic, nil
16✔
3017
}
3018

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

2,944✔
3026
        return c.fetchLightningNode(tx, nodePub)
2,944✔
3027
}
2,944✔
3028

3029
// FetchLightningNode attempts to look up a target node by its identity public
3030
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3031
// returned.
3032
func (c *ChannelGraph) FetchLightningNode(nodePub route.Vertex) (*LightningNode,
3033
        error) {
829✔
3034

829✔
3035
        return c.fetchLightningNode(nil, nodePub)
829✔
3036
}
829✔
3037

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

3,773✔
3045
        var node *LightningNode
3,773✔
3046
        fetch := func(tx kvdb.RTx) error {
7,546✔
3047
                // First grab the nodes bucket which stores the mapping from
3,773✔
3048
                // pubKey to node information.
3,773✔
3049
                nodes := tx.ReadBucket(nodeBucket)
3,773✔
3050
                if nodes == nil {
3,773✔
3051
                        return ErrGraphNotFound
×
3052
                }
×
3053

3054
                // If a key for this serialized public key isn't found, then
3055
                // the target node doesn't exist within the database.
3056
                nodeBytes := nodes.Get(nodePub[:])
3,773✔
3057
                if nodeBytes == nil {
3,784✔
3058
                        return ErrGraphNodeNotFound
11✔
3059
                }
11✔
3060

3061
                // If the node is found, then we can de deserialize the node
3062
                // information to return to the user.
3063
                nodeReader := bytes.NewReader(nodeBytes)
3,765✔
3064
                n, err := deserializeLightningNode(nodeReader)
3,765✔
3065
                if err != nil {
3,765✔
3066
                        return err
×
3067
                }
×
3068

3069
                node = &n
3,765✔
3070

3,765✔
3071
                return nil
3,765✔
3072
        }
3073

3074
        if tx == nil {
4,602✔
3075
                err := kvdb.View(
829✔
3076
                        c.db, fetch, func() {
1,658✔
3077
                                node = nil
829✔
3078
                        },
829✔
3079
                )
3080
                if err != nil {
840✔
3081
                        return nil, err
11✔
3082
                }
11✔
3083

3084
                return node, nil
821✔
3085
        }
3086

3087
        err := fetch(tx)
2,944✔
3088
        if err != nil {
2,944✔
3089
                return nil, err
×
3090
        }
×
3091

3092
        return node, nil
2,944✔
3093
}
3094

3095
// graphCacheNode is a struct that wraps a LightningNode in a way that it can be
3096
// cached in the graph cache.
3097
type graphCacheNode struct {
3098
        pubKeyBytes route.Vertex
3099
        features    *lnwire.FeatureVector
3100
}
3101

3102
// newGraphCacheNode returns a new cache optimized node.
3103
func newGraphCacheNode(pubKey route.Vertex,
3104
        features *lnwire.FeatureVector) *graphCacheNode {
728✔
3105

728✔
3106
        return &graphCacheNode{
728✔
3107
                pubKeyBytes: pubKey,
728✔
3108
                features:    features,
728✔
3109
        }
728✔
3110
}
728✔
3111

3112
// PubKey returns the node's public identity key.
3113
func (n *graphCacheNode) PubKey() route.Vertex {
728✔
3114
        return n.pubKeyBytes
728✔
3115
}
728✔
3116

3117
// Features returns the node's features.
3118
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
708✔
3119
        return n.features
708✔
3120
}
708✔
3121

3122
// ForEachChannel iterates through all channels of this node, executing the
3123
// passed callback with an edge info structure and the policies of each end
3124
// of the channel. The first edge policy is the outgoing edge *to* the
3125
// connecting node, while the second is the incoming edge *from* the
3126
// connecting node. If the callback returns an error, then the iteration is
3127
// halted with the error propagated back up to the caller.
3128
//
3129
// Unknown policies are passed into the callback as nil values.
3130
func (n *graphCacheNode) ForEachChannel(tx kvdb.RTx,
3131
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3132
                *models.ChannelEdgePolicy) error) error {
628✔
3133

628✔
3134
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
628✔
3135
}
628✔
3136

3137
var _ GraphCacheNode = (*graphCacheNode)(nil)
3138

3139
// HasLightningNode determines if the graph has a vertex identified by the
3140
// target node identity public key. If the node exists in the database, a
3141
// timestamp of when the data for the node was lasted updated is returned along
3142
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3143
// boolean.
3144
func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool, error) {
19✔
3145
        var (
19✔
3146
                updateTime time.Time
19✔
3147
                exists     bool
19✔
3148
        )
19✔
3149

19✔
3150
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
38✔
3151
                // First grab the nodes bucket which stores the mapping from
19✔
3152
                // pubKey to node information.
19✔
3153
                nodes := tx.ReadBucket(nodeBucket)
19✔
3154
                if nodes == nil {
19✔
3155
                        return ErrGraphNotFound
×
3156
                }
×
3157

3158
                // If a key for this serialized public key isn't found, we can
3159
                // exit early.
3160
                nodeBytes := nodes.Get(nodePub[:])
19✔
3161
                if nodeBytes == nil {
25✔
3162
                        exists = false
6✔
3163
                        return nil
6✔
3164
                }
6✔
3165

3166
                // Otherwise we continue on to obtain the time stamp
3167
                // representing the last time the data for this node was
3168
                // updated.
3169
                nodeReader := bytes.NewReader(nodeBytes)
16✔
3170
                node, err := deserializeLightningNode(nodeReader)
16✔
3171
                if err != nil {
16✔
3172
                        return err
×
3173
                }
×
3174

3175
                exists = true
16✔
3176
                updateTime = node.LastUpdate
16✔
3177
                return nil
16✔
3178
        }, func() {
19✔
3179
                updateTime = time.Time{}
19✔
3180
                exists = false
19✔
3181
        })
19✔
3182
        if err != nil {
19✔
3183
                return time.Time{}, exists, err
×
3184
        }
×
3185

3186
        return updateTime, exists, nil
19✔
3187
}
3188

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

1,869✔
3195
        traversal := func(tx kvdb.RTx) error {
3,738✔
3196
                edges := tx.ReadBucket(edgeBucket)
1,869✔
3197
                if edges == nil {
1,869✔
3198
                        return ErrGraphNotFound
×
3199
                }
×
3200
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,869✔
3201
                if edgeIndex == nil {
1,869✔
3202
                        return ErrGraphNoEdgesFound
×
3203
                }
×
3204

3205
                // In order to reach all the edges for this node, we take
3206
                // advantage of the construction of the key-space within the
3207
                // edge bucket. The keys are stored in the form: pubKey ||
3208
                // chanID. Therefore, starting from a chanID of zero, we can
3209
                // scan forward in the bucket, grabbing all the edges for the
3210
                // node. Once the prefix no longer matches, then we know we're
3211
                // done.
3212
                var nodeStart [33 + 8]byte
1,869✔
3213
                copy(nodeStart[:], nodePub)
1,869✔
3214
                copy(nodeStart[33:], chanStart[:])
1,869✔
3215

1,869✔
3216
                // Starting from the key pubKey || 0, we seek forward in the
1,869✔
3217
                // bucket until the retrieved key no longer has the public key
1,869✔
3218
                // as its prefix. This indicates that we've stepped over into
1,869✔
3219
                // another node's edges, so we can terminate our scan.
1,869✔
3220
                edgeCursor := edges.ReadCursor()
1,869✔
3221
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() {
5,715✔
3222
                        // If the prefix still matches, the channel id is
3,846✔
3223
                        // returned in nodeEdge. Channel id is used to lookup
3,846✔
3224
                        // the node at the other end of the channel and both
3,846✔
3225
                        // edge policies.
3,846✔
3226
                        chanID := nodeEdge[33:]
3,846✔
3227
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3,846✔
3228
                        if err != nil {
3,846✔
3229
                                return err
×
3230
                        }
×
3231

3232
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,846✔
3233
                                edges, chanID, nodePub,
3,846✔
3234
                        )
3,846✔
3235
                        if err != nil {
3,846✔
3236
                                return err
×
3237
                        }
×
3238

3239
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,846✔
3240
                        if err != nil {
3,846✔
3241
                                return err
×
3242
                        }
×
3243

3244
                        incomingPolicy, err := fetchChanEdgePolicy(
3,846✔
3245
                                edges, chanID, otherNode[:],
3,846✔
3246
                        )
3,846✔
3247
                        if err != nil {
3,846✔
3248
                                return err
×
3249
                        }
×
3250

3251
                        // Finally, we execute the callback.
3252
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,846✔
3253
                        if err != nil {
3,858✔
3254
                                return err
12✔
3255
                        }
12✔
3256
                }
3257

3258
                return nil
1,860✔
3259
        }
3260

3261
        // If no transaction was provided, then we'll create a new transaction
3262
        // to execute the transaction within.
3263
        if tx == nil {
1,881✔
3264
                return kvdb.View(db, traversal, func() {})
24✔
3265
        }
3266

3267
        // Otherwise, we re-use the existing transaction to execute the graph
3268
        // traversal.
3269
        return traversal(tx)
1,860✔
3270
}
3271

3272
// ForEachNodeChannel iterates through all channels of the given node,
3273
// executing the passed callback with an edge info structure and the policies
3274
// of each end of the channel. The first edge policy is the outgoing edge *to*
3275
// the connecting node, while the second is the incoming edge *from* the
3276
// connecting node. If the callback returns an error, then the iteration is
3277
// halted with the error propagated back up to the caller.
3278
//
3279
// Unknown policies are passed into the callback as nil values.
3280
func (c *ChannelGraph) ForEachNodeChannel(nodePub route.Vertex,
3281
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3282
                *models.ChannelEdgePolicy) error) error {
9✔
3283

9✔
3284
        return nodeTraversal(nil, nodePub[:], c.db, cb)
9✔
3285
}
9✔
3286

3287
// ForEachNodeChannelTx iterates through all channels of the given node,
3288
// executing the passed callback with an edge info structure and the policies
3289
// of each end of the channel. The first edge policy is the outgoing edge *to*
3290
// the connecting node, while the second is the incoming edge *from* the
3291
// connecting node. If the callback returns an error, then the iteration is
3292
// halted with the error propagated back up to the caller.
3293
//
3294
// Unknown policies are passed into the callback as nil values.
3295
//
3296
// If the caller wishes to re-use an existing boltdb transaction, then it
3297
// should be passed as the first argument.  Otherwise, the first argument should
3298
// be nil and a fresh transaction will be created to execute the graph
3299
// traversal.
3300
func (c *ChannelGraph) ForEachNodeChannelTx(tx kvdb.RTx,
3301
        nodePub route.Vertex, cb func(kvdb.RTx, *models.ChannelEdgeInfo,
3302
                *models.ChannelEdgePolicy,
3303
                *models.ChannelEdgePolicy) error) error {
1,001✔
3304

1,001✔
3305
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,001✔
3306
}
1,001✔
3307

3308
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3309
// the target node in the channel. This is useful when one knows the pubkey of
3310
// one of the nodes, and wishes to obtain the full LightningNode for the other
3311
// end of the channel.
3312
func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx,
3313
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (*LightningNode,
3314
        error) {
3✔
3315

3✔
3316
        // Ensure that the node passed in is actually a member of the channel.
3✔
3317
        var targetNodeBytes [33]byte
3✔
3318
        switch {
3✔
3319
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
3✔
3320
                targetNodeBytes = channel.NodeKey2Bytes
3✔
3321
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
3✔
3322
                targetNodeBytes = channel.NodeKey1Bytes
3✔
3323
        default:
×
3324
                return nil, fmt.Errorf("node not participating in this channel")
×
3325
        }
3326

3327
        var targetNode *LightningNode
3✔
3328
        fetchNodeFunc := func(tx kvdb.RTx) error {
6✔
3329
                // First grab the nodes bucket which stores the mapping from
3✔
3330
                // pubKey to node information.
3✔
3331
                nodes := tx.ReadBucket(nodeBucket)
3✔
3332
                if nodes == nil {
3✔
3333
                        return ErrGraphNotFound
×
3334
                }
×
3335

3336
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
3✔
3337
                if err != nil {
3✔
3338
                        return err
×
3339
                }
×
3340

3341
                targetNode = &node
3✔
3342

3✔
3343
                return nil
3✔
3344
        }
3345

3346
        // If the transaction is nil, then we'll need to create a new one,
3347
        // otherwise we can use the existing db transaction.
3348
        var err error
3✔
3349
        if tx == nil {
3✔
3350
                err = kvdb.View(c.db, fetchNodeFunc, func() { targetNode = nil })
×
3351
        } else {
3✔
3352
                err = fetchNodeFunc(tx)
3✔
3353
        }
3✔
3354

3355
        return targetNode, err
3✔
3356
}
3357

3358
// computeEdgePolicyKeys is a helper function that can be used to compute the
3359
// keys used to index the channel edge policy info for the two nodes of the
3360
// edge. The keys for node 1 and node 2 are returned respectively.
3361
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
25✔
3362
        var (
25✔
3363
                node1Key [33 + 8]byte
25✔
3364
                node2Key [33 + 8]byte
25✔
3365
        )
25✔
3366

25✔
3367
        copy(node1Key[:], info.NodeKey1Bytes[:])
25✔
3368
        copy(node2Key[:], info.NodeKey2Bytes[:])
25✔
3369

25✔
3370
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
25✔
3371
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
25✔
3372

25✔
3373
        return node1Key[:], node2Key[:]
25✔
3374
}
25✔
3375

3376
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3377
// the channel identified by the funding outpoint. If the channel can't be
3378
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3379
// information for the channel itself is returned as well as two structs that
3380
// contain the routing policies for the channel in either direction.
3381
func (c *ChannelGraph) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3382
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3383
        *models.ChannelEdgePolicy, error) {
14✔
3384

14✔
3385
        var (
14✔
3386
                edgeInfo *models.ChannelEdgeInfo
14✔
3387
                policy1  *models.ChannelEdgePolicy
14✔
3388
                policy2  *models.ChannelEdgePolicy
14✔
3389
        )
14✔
3390

14✔
3391
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
28✔
3392
                // First, grab the node bucket. This will be used to populate
14✔
3393
                // the Node pointers in each edge read from disk.
14✔
3394
                nodes := tx.ReadBucket(nodeBucket)
14✔
3395
                if nodes == nil {
14✔
3396
                        return ErrGraphNotFound
×
3397
                }
×
3398

3399
                // Next, grab the edge bucket which stores the edges, and also
3400
                // the index itself so we can group the directed edges together
3401
                // logically.
3402
                edges := tx.ReadBucket(edgeBucket)
14✔
3403
                if edges == nil {
14✔
3404
                        return ErrGraphNoEdgesFound
×
3405
                }
×
3406
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
14✔
3407
                if edgeIndex == nil {
14✔
3408
                        return ErrGraphNoEdgesFound
×
3409
                }
×
3410

3411
                // If the channel's outpoint doesn't exist within the outpoint
3412
                // index, then the edge does not exist.
3413
                chanIndex := edges.NestedReadBucket(channelPointBucket)
14✔
3414
                if chanIndex == nil {
14✔
3415
                        return ErrGraphNoEdgesFound
×
3416
                }
×
3417
                var b bytes.Buffer
14✔
3418
                if err := writeOutpoint(&b, op); err != nil {
14✔
3419
                        return err
×
3420
                }
×
3421
                chanID := chanIndex.Get(b.Bytes())
14✔
3422
                if chanID == nil {
27✔
3423
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
13✔
3424
                }
13✔
3425

3426
                // If the channel is found to exists, then we'll first retrieve
3427
                // the general information for the channel.
3428
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
4✔
3429
                if err != nil {
4✔
3430
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3431
                }
×
3432
                edgeInfo = &edge
4✔
3433

4✔
3434
                // Once we have the information about the channels' parameters,
4✔
3435
                // we'll fetch the routing policies for each for the directed
4✔
3436
                // edges.
4✔
3437
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
4✔
3438
                if err != nil {
4✔
3439
                        return fmt.Errorf("failed to find policy: %w", err)
×
3440
                }
×
3441

3442
                policy1 = e1
4✔
3443
                policy2 = e2
4✔
3444
                return nil
4✔
3445
        }, func() {
14✔
3446
                edgeInfo = nil
14✔
3447
                policy1 = nil
14✔
3448
                policy2 = nil
14✔
3449
        })
14✔
3450
        if err != nil {
27✔
3451
                return nil, nil, nil, err
13✔
3452
        }
13✔
3453

3454
        return edgeInfo, policy1, policy2, nil
4✔
3455
}
3456

3457
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3458
// channel identified by the channel ID. If the channel can't be found, then
3459
// ErrEdgeNotFound is returned. A struct which houses the general information
3460
// for the channel itself is returned as well as two structs that contain the
3461
// routing policies for the channel in either direction.
3462
//
3463
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3464
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3465
// the ChannelEdgeInfo will only include the public keys of each node.
3466
func (c *ChannelGraph) FetchChannelEdgesByID(chanID uint64) (
3467
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3468
        *models.ChannelEdgePolicy, error) {
28✔
3469

28✔
3470
        var (
28✔
3471
                edgeInfo  *models.ChannelEdgeInfo
28✔
3472
                policy1   *models.ChannelEdgePolicy
28✔
3473
                policy2   *models.ChannelEdgePolicy
28✔
3474
                channelID [8]byte
28✔
3475
        )
28✔
3476

28✔
3477
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
56✔
3478
                // First, grab the node bucket. This will be used to populate
28✔
3479
                // the Node pointers in each edge read from disk.
28✔
3480
                nodes := tx.ReadBucket(nodeBucket)
28✔
3481
                if nodes == nil {
28✔
3482
                        return ErrGraphNotFound
×
3483
                }
×
3484

3485
                // Next, grab the edge bucket which stores the edges, and also
3486
                // the index itself so we can group the directed edges together
3487
                // logically.
3488
                edges := tx.ReadBucket(edgeBucket)
28✔
3489
                if edges == nil {
28✔
3490
                        return ErrGraphNoEdgesFound
×
3491
                }
×
3492
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
28✔
3493
                if edgeIndex == nil {
28✔
3494
                        return ErrGraphNoEdgesFound
×
3495
                }
×
3496

3497
                byteOrder.PutUint64(channelID[:], chanID)
28✔
3498

28✔
3499
                // Now, attempt to fetch edge.
28✔
3500
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
28✔
3501

28✔
3502
                // If it doesn't exist, we'll quickly check our zombie index to
28✔
3503
                // see if we've previously marked it as so.
28✔
3504
                if errors.Is(err, ErrEdgeNotFound) {
32✔
3505
                        // If the zombie index doesn't exist, or the edge is not
4✔
3506
                        // marked as a zombie within it, then we'll return the
4✔
3507
                        // original ErrEdgeNotFound error.
4✔
3508
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3509
                        if zombieIndex == nil {
4✔
3510
                                return ErrEdgeNotFound
×
3511
                        }
×
3512

3513
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
4✔
3514
                                zombieIndex, chanID,
4✔
3515
                        )
4✔
3516
                        if !isZombie {
7✔
3517
                                return ErrEdgeNotFound
3✔
3518
                        }
3✔
3519

3520
                        // Otherwise, the edge is marked as a zombie, so we'll
3521
                        // populate the edge info with the public keys of each
3522
                        // party as this is the only information we have about
3523
                        // it and return an error signaling so.
3524
                        edgeInfo = &models.ChannelEdgeInfo{
4✔
3525
                                NodeKey1Bytes: pubKey1,
4✔
3526
                                NodeKey2Bytes: pubKey2,
4✔
3527
                        }
4✔
3528
                        return ErrZombieEdge
4✔
3529
                }
3530

3531
                // Otherwise, we'll just return the error if any.
3532
                if err != nil {
27✔
3533
                        return err
×
3534
                }
×
3535

3536
                edgeInfo = &edge
27✔
3537

27✔
3538
                // Then we'll attempt to fetch the accompanying policies of this
27✔
3539
                // edge.
27✔
3540
                e1, e2, err := fetchChanEdgePolicies(
27✔
3541
                        edgeIndex, edges, channelID[:],
27✔
3542
                )
27✔
3543
                if err != nil {
27✔
3544
                        return err
×
3545
                }
×
3546

3547
                policy1 = e1
27✔
3548
                policy2 = e2
27✔
3549
                return nil
27✔
3550
        }, func() {
28✔
3551
                edgeInfo = nil
28✔
3552
                policy1 = nil
28✔
3553
                policy2 = nil
28✔
3554
        })
28✔
3555
        if err == ErrZombieEdge {
32✔
3556
                return edgeInfo, nil, nil, err
4✔
3557
        }
4✔
3558
        if err != nil {
30✔
3559
                return nil, nil, nil, err
3✔
3560
        }
3✔
3561

3562
        return edgeInfo, policy1, policy2, nil
27✔
3563
}
3564

3565
// IsPublicNode is a helper method that determines whether the node with the
3566
// given public key is seen as a public node in the graph from the graph's
3567
// source node's point of view.
3568
func (c *ChannelGraph) IsPublicNode(pubKey [33]byte) (bool, error) {
16✔
3569
        var nodeIsPublic bool
16✔
3570
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
32✔
3571
                nodes := tx.ReadBucket(nodeBucket)
16✔
3572
                if nodes == nil {
16✔
3573
                        return ErrGraphNodesNotFound
×
3574
                }
×
3575
                ourPubKey := nodes.Get(sourceKey)
16✔
3576
                if ourPubKey == nil {
16✔
3577
                        return ErrSourceNodeNotSet
×
3578
                }
×
3579
                node, err := fetchLightningNode(nodes, pubKey[:])
16✔
3580
                if err != nil {
16✔
3581
                        return err
×
3582
                }
×
3583

3584
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
16✔
3585
                return err
16✔
3586
        }, func() {
16✔
3587
                nodeIsPublic = false
16✔
3588
        })
16✔
3589
        if err != nil {
16✔
3590
                return false, err
×
3591
        }
×
3592

3593
        return nodeIsPublic, nil
16✔
3594
}
3595

3596
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3597
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
49✔
3598
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
49✔
3599
        if err != nil {
49✔
3600
                return nil, err
×
3601
        }
×
3602

3603
        // With the witness script generated, we'll now turn it into a p2wsh
3604
        // script:
3605
        //  * OP_0 <sha256(script)>
3606
        bldr := txscript.NewScriptBuilder(
49✔
3607
                txscript.WithScriptAllocSize(input.P2WSHSize),
49✔
3608
        )
49✔
3609
        bldr.AddOp(txscript.OP_0)
49✔
3610
        scriptHash := sha256.Sum256(witnessScript)
49✔
3611
        bldr.AddData(scriptHash[:])
49✔
3612

49✔
3613
        return bldr.Script()
49✔
3614
}
3615

3616
// EdgePoint couples the outpoint of a channel with the funding script that it
3617
// creates. The FilteredChainView will use this to watch for spends of this
3618
// edge point on chain. We require both of these values as depending on the
3619
// concrete implementation, either the pkScript, or the out point will be used.
3620
type EdgePoint struct {
3621
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3622
        FundingPkScript []byte
3623

3624
        // OutPoint is the outpoint of the target channel.
3625
        OutPoint wire.OutPoint
3626
}
3627

3628
// String returns a human readable version of the target EdgePoint. We return
3629
// the outpoint directly as it is enough to uniquely identify the edge point.
3630
func (e *EdgePoint) String() string {
×
3631
        return e.OutPoint.String()
×
3632
}
×
3633

3634
// ChannelView returns the verifiable edge information for each active channel
3635
// within the known channel graph. The set of UTXO's (along with their scripts)
3636
// returned are the ones that need to be watched on chain to detect channel
3637
// closes on the resident blockchain.
3638
func (c *ChannelGraph) ChannelView() ([]EdgePoint, error) {
26✔
3639
        var edgePoints []EdgePoint
26✔
3640
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
52✔
3641
                // We're going to iterate over the entire channel index, so
26✔
3642
                // we'll need to fetch the edgeBucket to get to the index as
26✔
3643
                // it's a sub-bucket.
26✔
3644
                edges := tx.ReadBucket(edgeBucket)
26✔
3645
                if edges == nil {
26✔
3646
                        return ErrGraphNoEdgesFound
×
3647
                }
×
3648
                chanIndex := edges.NestedReadBucket(channelPointBucket)
26✔
3649
                if chanIndex == nil {
26✔
3650
                        return ErrGraphNoEdgesFound
×
3651
                }
×
3652
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
26✔
3653
                if edgeIndex == nil {
26✔
3654
                        return ErrGraphNoEdgesFound
×
3655
                }
×
3656

3657
                // Once we have the proper bucket, we'll range over each key
3658
                // (which is the channel point for the channel) and decode it,
3659
                // accumulating each entry.
3660
                return chanIndex.ForEach(func(chanPointBytes, chanID []byte) error {
71✔
3661
                        chanPointReader := bytes.NewReader(chanPointBytes)
45✔
3662

45✔
3663
                        var chanPoint wire.OutPoint
45✔
3664
                        err := readOutpoint(chanPointReader, &chanPoint)
45✔
3665
                        if err != nil {
45✔
3666
                                return err
×
3667
                        }
×
3668

3669
                        edgeInfo, err := fetchChanEdgeInfo(
45✔
3670
                                edgeIndex, chanID,
45✔
3671
                        )
45✔
3672
                        if err != nil {
45✔
3673
                                return err
×
3674
                        }
×
3675

3676
                        pkScript, err := genMultiSigP2WSH(
45✔
3677
                                edgeInfo.BitcoinKey1Bytes[:],
45✔
3678
                                edgeInfo.BitcoinKey2Bytes[:],
45✔
3679
                        )
45✔
3680
                        if err != nil {
45✔
3681
                                return err
×
3682
                        }
×
3683

3684
                        edgePoints = append(edgePoints, EdgePoint{
45✔
3685
                                FundingPkScript: pkScript,
45✔
3686
                                OutPoint:        chanPoint,
45✔
3687
                        })
45✔
3688

45✔
3689
                        return nil
45✔
3690
                })
3691
        }, func() {
26✔
3692
                edgePoints = nil
26✔
3693
        }); err != nil {
26✔
3694
                return nil, err
×
3695
        }
×
3696

3697
        return edgePoints, nil
26✔
3698
}
3699

3700
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3701
// zombie. This method is used on an ad-hoc basis, when channels need to be
3702
// marked as zombies outside the normal pruning cycle.
3703
func (c *ChannelGraph) MarkEdgeZombie(chanID uint64,
3704
        pubKey1, pubKey2 [33]byte) error {
130✔
3705

130✔
3706
        c.cacheMu.Lock()
130✔
3707
        defer c.cacheMu.Unlock()
130✔
3708

130✔
3709
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
260✔
3710
                edges := tx.ReadWriteBucket(edgeBucket)
130✔
3711
                if edges == nil {
130✔
3712
                        return ErrGraphNoEdgesFound
×
3713
                }
×
3714
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
130✔
3715
                if err != nil {
130✔
3716
                        return fmt.Errorf("unable to create zombie "+
×
3717
                                "bucket: %w", err)
×
3718
                }
×
3719

3720
                if c.graphCache != nil {
260✔
3721
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
130✔
3722
                }
130✔
3723

3724
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
130✔
3725
        })
3726
        if err != nil {
130✔
3727
                return err
×
3728
        }
×
3729

3730
        c.rejectCache.remove(chanID)
130✔
3731
        c.chanCache.remove(chanID)
130✔
3732

130✔
3733
        return nil
130✔
3734
}
3735

3736
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3737
// keys should represent the node public keys of the two parties involved in the
3738
// edge.
3739
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3740
        pubKey2 [33]byte) error {
158✔
3741

158✔
3742
        var k [8]byte
158✔
3743
        byteOrder.PutUint64(k[:], chanID)
158✔
3744

158✔
3745
        var v [66]byte
158✔
3746
        copy(v[:33], pubKey1[:])
158✔
3747
        copy(v[33:], pubKey2[:])
158✔
3748

158✔
3749
        return zombieIndex.Put(k[:], v[:])
158✔
3750
}
158✔
3751

3752
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3753
func (c *ChannelGraph) MarkEdgeLive(chanID uint64) error {
5✔
3754
        c.cacheMu.Lock()
5✔
3755
        defer c.cacheMu.Unlock()
5✔
3756

5✔
3757
        return c.markEdgeLiveUnsafe(nil, chanID)
5✔
3758
}
5✔
3759

3760
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3761
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3762
// case a new transaction will be created.
3763
//
3764
// NOTE: this method MUST only be called if the cacheMu has already been
3765
// acquired.
3766
func (c *ChannelGraph) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
27✔
3767
        dbFn := func(tx kvdb.RwTx) error {
54✔
3768
                edges := tx.ReadWriteBucket(edgeBucket)
27✔
3769
                if edges == nil {
27✔
3770
                        return ErrGraphNoEdgesFound
×
3771
                }
×
3772
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
27✔
3773
                if zombieIndex == nil {
27✔
3774
                        return nil
×
3775
                }
×
3776

3777
                var k [8]byte
27✔
3778
                byteOrder.PutUint64(k[:], chanID)
27✔
3779

27✔
3780
                if len(zombieIndex.Get(k[:])) == 0 {
28✔
3781
                        return ErrZombieEdgeNotFound
1✔
3782
                }
1✔
3783

3784
                return zombieIndex.Delete(k[:])
26✔
3785
        }
3786

3787
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3788
        // the existing transaction
3789
        var err error
27✔
3790
        if tx == nil {
32✔
3791
                err = kvdb.Update(c.db, dbFn, func() {})
10✔
3792
        } else {
22✔
3793
                err = dbFn(tx)
22✔
3794
        }
22✔
3795
        if err != nil {
28✔
3796
                return err
1✔
3797
        }
1✔
3798

3799
        c.rejectCache.remove(chanID)
26✔
3800
        c.chanCache.remove(chanID)
26✔
3801

26✔
3802
        // We need to add the channel back into our graph cache, otherwise we
26✔
3803
        // won't use it for path finding.
26✔
3804
        if c.graphCache != nil {
52✔
3805
                edgeInfos, err := c.fetchChanInfos(tx, []uint64{chanID})
26✔
3806
                if err != nil {
26✔
3807
                        return err
×
3808
                }
×
3809

3810
                for _, edgeInfo := range edgeInfos {
26✔
3811
                        c.graphCache.AddChannel(
×
3812
                                edgeInfo.Info, edgeInfo.Policy1,
×
3813
                                edgeInfo.Policy2,
×
3814
                        )
×
3815
                }
×
3816
        }
3817

3818
        return nil
26✔
3819
}
3820

3821
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3822
// zombie, then the two node public keys corresponding to this edge are also
3823
// returned.
3824
func (c *ChannelGraph) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
5✔
3825
        var (
5✔
3826
                isZombie         bool
5✔
3827
                pubKey1, pubKey2 [33]byte
5✔
3828
        )
5✔
3829

5✔
3830
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3831
                edges := tx.ReadBucket(edgeBucket)
5✔
3832
                if edges == nil {
5✔
3833
                        return ErrGraphNoEdgesFound
×
3834
                }
×
3835
                zombieIndex := edges.NestedReadBucket(zombieBucket)
5✔
3836
                if zombieIndex == nil {
5✔
3837
                        return nil
×
3838
                }
×
3839

3840
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
5✔
3841
                return nil
5✔
3842
        }, func() {
5✔
3843
                isZombie = false
5✔
3844
                pubKey1 = [33]byte{}
5✔
3845
                pubKey2 = [33]byte{}
5✔
3846
        })
5✔
3847
        if err != nil {
5✔
3848
                return false, [33]byte{}, [33]byte{}
×
3849
        }
×
3850

3851
        return isZombie, pubKey1, pubKey2
5✔
3852
}
3853

3854
// isZombieEdge returns whether an entry exists for the given channel in the
3855
// zombie index. If an entry exists, then the two node public keys corresponding
3856
// to this edge are also returned.
3857
func isZombieEdge(zombieIndex kvdb.RBucket,
3858
        chanID uint64) (bool, [33]byte, [33]byte) {
201✔
3859

201✔
3860
        var k [8]byte
201✔
3861
        byteOrder.PutUint64(k[:], chanID)
201✔
3862

201✔
3863
        v := zombieIndex.Get(k[:])
201✔
3864
        if v == nil {
314✔
3865
                return false, [33]byte{}, [33]byte{}
113✔
3866
        }
113✔
3867

3868
        var pubKey1, pubKey2 [33]byte
91✔
3869
        copy(pubKey1[:], v[:33])
91✔
3870
        copy(pubKey2[:], v[33:])
91✔
3871

91✔
3872
        return true, pubKey1, pubKey2
91✔
3873
}
3874

3875
// NumZombies returns the current number of zombie channels in the graph.
3876
func (c *ChannelGraph) NumZombies() (uint64, error) {
4✔
3877
        var numZombies uint64
4✔
3878
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3879
                edges := tx.ReadBucket(edgeBucket)
4✔
3880
                if edges == nil {
4✔
3881
                        return nil
×
3882
                }
×
3883
                zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3884
                if zombieIndex == nil {
4✔
3885
                        return nil
×
3886
                }
×
3887

3888
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3889
                        numZombies++
2✔
3890
                        return nil
2✔
3891
                })
2✔
3892
        }, func() {
4✔
3893
                numZombies = 0
4✔
3894
        })
4✔
3895
        if err != nil {
4✔
3896
                return 0, err
×
3897
        }
×
3898

3899
        return numZombies, nil
4✔
3900
}
3901

3902
// PutClosedScid stores a SCID for a closed channel in the database. This is so
3903
// that we can ignore channel announcements that we know to be closed without
3904
// having to validate them and fetch a block.
3905
func (c *ChannelGraph) PutClosedScid(scid lnwire.ShortChannelID) error {
1✔
3906
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
2✔
3907
                closedScids, err := tx.CreateTopLevelBucket(closedScidBucket)
1✔
3908
                if err != nil {
1✔
3909
                        return err
×
3910
                }
×
3911

3912
                var k [8]byte
1✔
3913
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3914

1✔
3915
                return closedScids.Put(k[:], []byte{})
1✔
3916
        }, func() {})
1✔
3917
}
3918

3919
// IsClosedScid checks whether a channel identified by the passed in scid is
3920
// closed. This helps avoid having to perform expensive validation checks.
3921
// TODO: Add an LRU cache to cut down on disc reads.
3922
func (c *ChannelGraph) IsClosedScid(scid lnwire.ShortChannelID) (bool, error) {
5✔
3923
        var isClosed bool
5✔
3924
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3925
                closedScids := tx.ReadBucket(closedScidBucket)
5✔
3926
                if closedScids == nil {
5✔
3927
                        return ErrClosedScidsNotFound
×
3928
                }
×
3929

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

5✔
3933
                if closedScids.Get(k[:]) != nil {
6✔
3934
                        isClosed = true
1✔
3935
                        return nil
1✔
3936
                }
1✔
3937

3938
                return nil
4✔
3939
        }, func() {
5✔
3940
                isClosed = false
5✔
3941
        })
5✔
3942
        if err != nil {
5✔
3943
                return false, err
×
3944
        }
×
3945

3946
        return isClosed, nil
5✔
3947
}
3948

3949
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3950
        updateIndex kvdb.RwBucket, node *LightningNode) error {
976✔
3951

976✔
3952
        var (
976✔
3953
                scratch [16]byte
976✔
3954
                b       bytes.Buffer
976✔
3955
        )
976✔
3956

976✔
3957
        pub, err := node.PubKey()
976✔
3958
        if err != nil {
976✔
3959
                return err
×
3960
        }
×
3961
        nodePub := pub.SerializeCompressed()
976✔
3962

976✔
3963
        // If the node has the update time set, write it, else write 0.
976✔
3964
        updateUnix := uint64(0)
976✔
3965
        if node.LastUpdate.Unix() > 0 {
1,826✔
3966
                updateUnix = uint64(node.LastUpdate.Unix())
850✔
3967
        }
850✔
3968

3969
        byteOrder.PutUint64(scratch[:8], updateUnix)
976✔
3970
        if _, err := b.Write(scratch[:8]); err != nil {
976✔
3971
                return err
×
3972
        }
×
3973

3974
        if _, err := b.Write(nodePub); err != nil {
976✔
3975
                return err
×
3976
        }
×
3977

3978
        // If we got a node announcement for this node, we will have the rest
3979
        // of the data available. If not we don't have more data to write.
3980
        if !node.HaveNodeAnnouncement {
1,052✔
3981
                // Write HaveNodeAnnouncement=0.
76✔
3982
                byteOrder.PutUint16(scratch[:2], 0)
76✔
3983
                if _, err := b.Write(scratch[:2]); err != nil {
76✔
3984
                        return err
×
3985
                }
×
3986

3987
                return nodeBucket.Put(nodePub, b.Bytes())
76✔
3988
        }
3989

3990
        // Write HaveNodeAnnouncement=1.
3991
        byteOrder.PutUint16(scratch[:2], 1)
903✔
3992
        if _, err := b.Write(scratch[:2]); err != nil {
903✔
3993
                return err
×
3994
        }
×
3995

3996
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
903✔
3997
                return err
×
3998
        }
×
3999
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
903✔
4000
                return err
×
4001
        }
×
4002
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
903✔
4003
                return err
×
4004
        }
×
4005

4006
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
903✔
4007
                return err
×
4008
        }
×
4009

4010
        if err := node.Features.Encode(&b); err != nil {
903✔
4011
                return err
×
4012
        }
×
4013

4014
        numAddresses := uint16(len(node.Addresses))
903✔
4015
        byteOrder.PutUint16(scratch[:2], numAddresses)
903✔
4016
        if _, err := b.Write(scratch[:2]); err != nil {
903✔
4017
                return err
×
4018
        }
×
4019

4020
        for _, address := range node.Addresses {
2,036✔
4021
                if err := serializeAddr(&b, address); err != nil {
1,133✔
4022
                        return err
×
4023
                }
×
4024
        }
4025

4026
        sigLen := len(node.AuthSigBytes)
903✔
4027
        if sigLen > 80 {
903✔
4028
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4029
                        sigLen)
×
4030
        }
×
4031

4032
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
903✔
4033
        if err != nil {
903✔
4034
                return err
×
4035
        }
×
4036

4037
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
903✔
4038
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4039
        }
×
4040
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
903✔
4041
        if err != nil {
903✔
4042
                return err
×
4043
        }
×
4044

4045
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
903✔
4046
                return err
×
4047
        }
×
4048

4049
        // With the alias bucket updated, we'll now update the index that
4050
        // tracks the time series of node updates.
4051
        var indexKey [8 + 33]byte
903✔
4052
        byteOrder.PutUint64(indexKey[:8], updateUnix)
903✔
4053
        copy(indexKey[8:], nodePub)
903✔
4054

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

105✔
4062
                var oldIndexKey [8 + 33]byte
105✔
4063
                copy(oldIndexKey[:8], oldUpdateTime)
105✔
4064
                copy(oldIndexKey[8:], nodePub)
105✔
4065

105✔
4066
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
105✔
4067
                        return err
×
4068
                }
×
4069
        }
4070

4071
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
903✔
4072
                return err
×
4073
        }
×
4074

4075
        return nodeBucket.Put(nodePub, b.Bytes())
903✔
4076
}
4077

4078
func fetchLightningNode(nodeBucket kvdb.RBucket,
4079
        nodePub []byte) (LightningNode, error) {
3,564✔
4080

3,564✔
4081
        nodeBytes := nodeBucket.Get(nodePub)
3,564✔
4082
        if nodeBytes == nil {
3,639✔
4083
                return LightningNode{}, ErrGraphNodeNotFound
75✔
4084
        }
75✔
4085

4086
        nodeReader := bytes.NewReader(nodeBytes)
3,492✔
4087
        return deserializeLightningNode(nodeReader)
3,492✔
4088
}
4089

4090
func deserializeLightningNodeCacheable(r io.Reader) (*graphCacheNode, error) {
123✔
4091
        // Always populate a feature vector, even if we don't have a node
123✔
4092
        // announcement and short circuit below.
123✔
4093
        node := newGraphCacheNode(
123✔
4094
                route.Vertex{},
123✔
4095
                lnwire.EmptyFeatureVector(),
123✔
4096
        )
123✔
4097

123✔
4098
        var nodeScratch [8]byte
123✔
4099

123✔
4100
        // Skip ahead:
123✔
4101
        // - LastUpdate (8 bytes)
123✔
4102
        if _, err := r.Read(nodeScratch[:]); err != nil {
123✔
4103
                return nil, err
×
4104
        }
×
4105

4106
        if _, err := io.ReadFull(r, node.pubKeyBytes[:]); err != nil {
123✔
4107
                return nil, err
×
4108
        }
×
4109

4110
        // Read the node announcement flag.
4111
        if _, err := r.Read(nodeScratch[:2]); err != nil {
123✔
4112
                return nil, err
×
4113
        }
×
4114
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
123✔
4115

123✔
4116
        // The rest of the data is optional, and will only be there if we got a
123✔
4117
        // node announcement for this node.
123✔
4118
        if hasNodeAnn == 0 {
126✔
4119
                return node, nil
3✔
4120
        }
3✔
4121

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

4135
        if _, err := wire.ReadVarString(r, 0); err != nil {
123✔
4136
                return nil, err
×
4137
        }
×
4138

4139
        if err := node.features.Decode(r); err != nil {
123✔
4140
                return nil, err
×
4141
        }
×
4142

4143
        return node, nil
123✔
4144
}
4145

4146
func deserializeLightningNode(r io.Reader) (LightningNode, error) {
8,445✔
4147
        var (
8,445✔
4148
                node    LightningNode
8,445✔
4149
                scratch [8]byte
8,445✔
4150
                err     error
8,445✔
4151
        )
8,445✔
4152

8,445✔
4153
        // Always populate a feature vector, even if we don't have a node
8,445✔
4154
        // announcement and short circuit below.
8,445✔
4155
        node.Features = lnwire.EmptyFeatureVector()
8,445✔
4156

8,445✔
4157
        if _, err := r.Read(scratch[:]); err != nil {
8,445✔
4158
                return LightningNode{}, err
×
4159
        }
×
4160

4161
        unix := int64(byteOrder.Uint64(scratch[:]))
8,445✔
4162
        node.LastUpdate = time.Unix(unix, 0)
8,445✔
4163

8,445✔
4164
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,445✔
4165
                return LightningNode{}, err
×
4166
        }
×
4167

4168
        if _, err := r.Read(scratch[:2]); err != nil {
8,445✔
4169
                return LightningNode{}, err
×
4170
        }
×
4171

4172
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,445✔
4173
        if hasNodeAnn == 1 {
16,756✔
4174
                node.HaveNodeAnnouncement = true
8,311✔
4175
        } else {
8,448✔
4176
                node.HaveNodeAnnouncement = false
137✔
4177
        }
137✔
4178

4179
        // The rest of the data is optional, and will only be there if we got a node
4180
        // announcement for this node.
4181
        if !node.HaveNodeAnnouncement {
8,582✔
4182
                return node, nil
137✔
4183
        }
137✔
4184

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

4197
        node.Alias, err = wire.ReadVarString(r, 0)
8,311✔
4198
        if err != nil {
8,311✔
4199
                return LightningNode{}, err
×
4200
        }
×
4201

4202
        err = node.Features.Decode(r)
8,311✔
4203
        if err != nil {
8,311✔
4204
                return LightningNode{}, err
×
4205
        }
×
4206

4207
        if _, err := r.Read(scratch[:2]); err != nil {
8,311✔
4208
                return LightningNode{}, err
×
4209
        }
×
4210
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,311✔
4211

8,311✔
4212
        var addresses []net.Addr
8,311✔
4213
        for i := 0; i < numAddresses; i++ {
18,837✔
4214
                address, err := deserializeAddr(r)
10,526✔
4215
                if err != nil {
10,526✔
4216
                        return LightningNode{}, err
×
4217
                }
×
4218
                addresses = append(addresses, address)
10,526✔
4219
        }
4220
        node.Addresses = addresses
8,311✔
4221

8,311✔
4222
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,311✔
4223
        if err != nil {
8,311✔
4224
                return LightningNode{}, err
×
4225
        }
×
4226

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

4239
        return node, nil
8,311✔
4240
}
4241

4242
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4243
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,463✔
4244

1,463✔
4245
        var b bytes.Buffer
1,463✔
4246

1,463✔
4247
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,463✔
4248
                return err
×
4249
        }
×
4250
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,463✔
4251
                return err
×
4252
        }
×
4253
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,463✔
4254
                return err
×
4255
        }
×
4256
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,463✔
4257
                return err
×
4258
        }
×
4259

4260
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,463✔
4261
                return err
×
4262
        }
×
4263

4264
        authProof := edgeInfo.AuthProof
1,463✔
4265
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,463✔
4266
        if authProof != nil {
2,843✔
4267
                nodeSig1 = authProof.NodeSig1Bytes
1,380✔
4268
                nodeSig2 = authProof.NodeSig2Bytes
1,380✔
4269
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,380✔
4270
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,380✔
4271
        }
1,380✔
4272

4273
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,463✔
4274
                return err
×
4275
        }
×
4276
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,463✔
4277
                return err
×
4278
        }
×
4279
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,463✔
4280
                return err
×
4281
        }
×
4282
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,463✔
4283
                return err
×
4284
        }
×
4285

4286
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,463✔
4287
                return err
×
4288
        }
×
4289
        if err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity)); err != nil {
1,463✔
4290
                return err
×
4291
        }
×
4292
        if _, err := b.Write(chanID[:]); err != nil {
1,463✔
4293
                return err
×
4294
        }
×
4295
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,463✔
4296
                return err
×
4297
        }
×
4298

4299
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,463✔
4300
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4301
        }
×
4302
        err := wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,463✔
4303
        if err != nil {
1,463✔
4304
                return err
×
4305
        }
×
4306

4307
        return edgeIndex.Put(chanID[:], b.Bytes())
1,463✔
4308
}
4309

4310
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4311
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,172✔
4312

4,172✔
4313
        edgeInfoBytes := edgeIndex.Get(chanID)
4,172✔
4314
        if edgeInfoBytes == nil {
4,255✔
4315
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
83✔
4316
        }
83✔
4317

4318
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,092✔
4319
        return deserializeChanEdgeInfo(edgeInfoReader)
4,092✔
4320
}
4321

4322
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,716✔
4323
        var (
4,716✔
4324
                err      error
4,716✔
4325
                edgeInfo models.ChannelEdgeInfo
4,716✔
4326
        )
4,716✔
4327

4,716✔
4328
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,716✔
4329
                return models.ChannelEdgeInfo{}, err
×
4330
        }
×
4331
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,716✔
4332
                return models.ChannelEdgeInfo{}, err
×
4333
        }
×
4334
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,716✔
4335
                return models.ChannelEdgeInfo{}, err
×
4336
        }
×
4337
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,716✔
4338
                return models.ChannelEdgeInfo{}, err
×
4339
        }
×
4340

4341
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,716✔
4342
        if err != nil {
4,716✔
4343
                return models.ChannelEdgeInfo{}, err
×
4344
        }
×
4345

4346
        proof := &models.ChannelAuthProof{}
4,716✔
4347

4,716✔
4348
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,716✔
4349
        if err != nil {
4,716✔
4350
                return models.ChannelEdgeInfo{}, err
×
4351
        }
×
4352
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,716✔
4353
        if err != nil {
4,716✔
4354
                return models.ChannelEdgeInfo{}, err
×
4355
        }
×
4356
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,716✔
4357
        if err != nil {
4,716✔
4358
                return models.ChannelEdgeInfo{}, err
×
4359
        }
×
4360
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,716✔
4361
        if err != nil {
4,716✔
4362
                return models.ChannelEdgeInfo{}, err
×
4363
        }
×
4364

4365
        if !proof.IsEmpty() {
6,479✔
4366
                edgeInfo.AuthProof = proof
1,763✔
4367
        }
1,763✔
4368

4369
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,716✔
4370
        if err := readOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,716✔
4371
                return models.ChannelEdgeInfo{}, err
×
4372
        }
×
4373
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,716✔
4374
                return models.ChannelEdgeInfo{}, err
×
4375
        }
×
4376
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,716✔
4377
                return models.ChannelEdgeInfo{}, err
×
4378
        }
×
4379

4380
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,716✔
4381
                return models.ChannelEdgeInfo{}, err
×
4382
        }
×
4383

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

4396
        return edgeInfo, nil
4,716✔
4397
}
4398

4399
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4400
        from, to []byte) error {
2,631✔
4401

2,631✔
4402
        var edgeKey [33 + 8]byte
2,631✔
4403
        copy(edgeKey[:], from)
2,631✔
4404
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,631✔
4405

2,631✔
4406
        var b bytes.Buffer
2,631✔
4407
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,631✔
4408
                return err
×
4409
        }
×
4410

4411
        // Before we write out the new edge, we'll create a new entry in the
4412
        // update index in order to keep it fresh.
4413
        updateUnix := uint64(edge.LastUpdate.Unix())
2,631✔
4414
        var indexKey [8 + 8]byte
2,631✔
4415
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,631✔
4416
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,631✔
4417

2,631✔
4418
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,631✔
4419
        if err != nil {
2,631✔
4420
                return err
×
4421
        }
×
4422

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

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

4446
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
27✔
4447

27✔
4448
                var oldIndexKey [8 + 8]byte
27✔
4449
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
27✔
4450
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
27✔
4451

27✔
4452
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
27✔
4453
                        return err
×
4454
                }
×
4455
        }
4456

4457
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,631✔
4458
                return err
×
4459
        }
×
4460

4461
        err = updateEdgePolicyDisabledIndex(
2,631✔
4462
                edges, edge.ChannelID,
2,631✔
4463
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,631✔
4464
                edge.IsDisabled(),
2,631✔
4465
        )
2,631✔
4466
        if err != nil {
2,631✔
NEW
4467
                return err
×
NEW
4468
        }
×
4469

4470
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,631✔
4471
}
4472

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

2,897✔
4485
        var disabledEdgeKey [8 + 1]byte
2,897✔
4486
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,897✔
4487
        if direction {
4,343✔
4488
                disabledEdgeKey[8] = 1
1,446✔
4489
        }
1,446✔
4490

4491
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,897✔
4492
                disabledEdgePolicyBucket,
2,897✔
4493
        )
2,897✔
4494
        if err != nil {
2,897✔
4495
                return err
×
4496
        }
×
4497

4498
        if disabled {
2,926✔
4499
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
29✔
4500
        }
29✔
4501

4502
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,871✔
4503
}
4504

4505
// putChanEdgePolicyUnknown marks the edge policy as unknown
4506
// in the edges bucket.
4507
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4508
        from []byte) error {
2,921✔
4509

2,921✔
4510
        var edgeKey [33 + 8]byte
2,921✔
4511
        copy(edgeKey[:], from)
2,921✔
4512
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,921✔
4513

2,921✔
4514
        if edges.Get(edgeKey[:]) != nil {
2,921✔
4515
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4516
                        " when there is already a policy present", channelID)
×
4517
        }
×
4518

4519
        return edges.Put(edgeKey[:], unknownPolicy)
2,921✔
4520
}
4521

4522
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4523
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,151✔
4524

8,151✔
4525
        var edgeKey [33 + 8]byte
8,151✔
4526
        copy(edgeKey[:], nodePub)
8,151✔
4527
        copy(edgeKey[33:], chanID[:])
8,151✔
4528

8,151✔
4529
        edgeBytes := edges.Get(edgeKey[:])
8,151✔
4530
        if edgeBytes == nil {
8,151✔
4531
                return nil, ErrEdgeNotFound
×
4532
        }
×
4533

4534
        // No need to deserialize unknown policy.
4535
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,511✔
4536
                return nil, nil
360✔
4537
        }
360✔
4538

4539
        edgeReader := bytes.NewReader(edgeBytes)
7,794✔
4540

7,794✔
4541
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,794✔
4542
        switch {
7,794✔
4543
        // If the db policy was missing an expected optional field, we return
4544
        // nil as if the policy was unknown.
4545
        case err == ErrEdgePolicyOptionalFieldNotFound:
1✔
4546
                return nil, nil
1✔
4547

4548
        case err != nil:
×
4549
                return nil, err
×
4550
        }
4551

4552
        return ep, nil
7,793✔
4553
}
4554

4555
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4556
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4557
        error) {
234✔
4558

234✔
4559
        edgeInfo := edgeIndex.Get(chanID)
234✔
4560
        if edgeInfo == nil {
234✔
4561
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4562
                        chanID)
×
4563
        }
×
4564

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

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

4584
        return edge1, edge2, nil
234✔
4585
}
4586

4587
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4588
        to []byte) error {
2,633✔
4589

2,633✔
4590
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,633✔
4591
        if err != nil {
2,633✔
4592
                return err
×
4593
        }
×
4594

4595
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,633✔
4596
                return err
×
4597
        }
×
4598

4599
        var scratch [8]byte
2,633✔
4600
        updateUnix := uint64(edge.LastUpdate.Unix())
2,633✔
4601
        byteOrder.PutUint64(scratch[:], updateUnix)
2,633✔
4602
        if _, err := w.Write(scratch[:]); err != nil {
2,633✔
4603
                return err
×
4604
        }
×
4605

4606
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,633✔
4607
                return err
×
4608
        }
×
4609
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,633✔
4610
                return err
×
4611
        }
×
4612
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,633✔
4613
                return err
×
4614
        }
×
4615
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,633✔
4616
                return err
×
4617
        }
×
4618
        if err := binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat)); err != nil {
2,633✔
4619
                return err
×
4620
        }
×
4621
        if err := binary.Write(w, byteOrder, uint64(edge.FeeProportionalMillionths)); err != nil {
2,633✔
4622
                return err
×
4623
        }
×
4624

4625
        if _, err := w.Write(to); err != nil {
2,633✔
4626
                return err
×
4627
        }
×
4628

4629
        // If the max_htlc field is present, we write it. To be compatible with
4630
        // older versions that wasn't aware of this field, we write it as part
4631
        // of the opaque data.
4632
        // TODO(halseth): clean up when moving to TLV.
4633
        var opaqueBuf bytes.Buffer
2,633✔
4634
        if edge.MessageFlags.HasMaxHtlc() {
4,882✔
4635
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,249✔
4636
                if err != nil {
2,249✔
4637
                        return err
×
4638
                }
×
4639
        }
4640

4641
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,633✔
4642
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4643
        }
×
4644
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,633✔
4645
                return err
×
4646
        }
×
4647

4648
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,633✔
4649
                return err
×
4650
        }
×
4651
        return nil
2,633✔
4652
}
4653

4654
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,819✔
4655
        // Deserialize the policy. Note that in case an optional field is not
7,819✔
4656
        // found, both an error and a populated policy object are returned.
7,819✔
4657
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,819✔
4658
        if deserializeErr != nil &&
7,819✔
4659
                deserializeErr != ErrEdgePolicyOptionalFieldNotFound {
7,819✔
4660

×
4661
                return nil, deserializeErr
×
4662
        }
×
4663

4664
        return edge, deserializeErr
7,819✔
4665
}
4666

4667
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4668
        error) {
8,826✔
4669

8,826✔
4670
        edge := &models.ChannelEdgePolicy{}
8,826✔
4671

8,826✔
4672
        var err error
8,826✔
4673
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,826✔
4674
        if err != nil {
8,826✔
4675
                return nil, err
×
4676
        }
×
4677

4678
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,826✔
4679
                return nil, err
×
4680
        }
×
4681

4682
        var scratch [8]byte
8,826✔
4683
        if _, err := r.Read(scratch[:]); err != nil {
8,826✔
4684
                return nil, err
×
4685
        }
×
4686
        unix := int64(byteOrder.Uint64(scratch[:]))
8,826✔
4687
        edge.LastUpdate = time.Unix(unix, 0)
8,826✔
4688

8,826✔
4689
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,826✔
4690
                return nil, err
×
4691
        }
×
4692
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,826✔
4693
                return nil, err
×
4694
        }
×
4695
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,826✔
4696
                return nil, err
×
4697
        }
×
4698

4699
        var n uint64
8,826✔
4700
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,826✔
4701
                return nil, err
×
4702
        }
×
4703
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,826✔
4704

8,826✔
4705
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,826✔
4706
                return nil, err
×
4707
        }
×
4708
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,826✔
4709

8,826✔
4710
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,826✔
4711
                return nil, err
×
4712
        }
×
4713
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,826✔
4714

8,826✔
4715
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,826✔
4716
                return nil, err
×
4717
        }
×
4718

4719
        // We'll try and see if there are any opaque bytes left, if not, then
4720
        // we'll ignore the EOF error and return the edge as is.
4721
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,826✔
4722
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,826✔
4723
        )
8,826✔
4724
        switch {
8,826✔
4725
        case err == io.ErrUnexpectedEOF:
×
4726
        case err == io.EOF:
3✔
4727
        case err != nil:
×
4728
                return nil, err
×
4729
        }
4730

4731
        // See if optional fields are present.
4732
        if edge.MessageFlags.HasMaxHtlc() {
17,272✔
4733
                // The max_htlc field should be at the beginning of the opaque
8,446✔
4734
                // bytes.
8,446✔
4735
                opq := edge.ExtraOpaqueData
8,446✔
4736

8,446✔
4737
                // If the max_htlc field is not present, it might be old data
8,446✔
4738
                // stored before this field was validated. We'll return the
8,446✔
4739
                // edge along with an error.
8,446✔
4740
                if len(opq) < 8 {
8,449✔
4741
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4742
                }
3✔
4743

4744
                maxHtlc := byteOrder.Uint64(opq[:8])
8,443✔
4745
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,443✔
4746

8,443✔
4747
                // Exclude the parsed field from the rest of the opaque data.
8,443✔
4748
                edge.ExtraOpaqueData = opq[8:]
8,443✔
4749
        }
4750

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