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

lightningnetwork / lnd / 11216766535

07 Oct 2024 01:37PM UTC coverage: 57.817% (-1.0%) from 58.817%
11216766535

Pull #9148

github

ProofOfKeags
lnwire: remove kickoff feerate from propose/commit
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

571 of 879 new or added lines in 16 files covered. (64.96%)

23253 existing lines in 251 files now uncovered.

99022 of 171268 relevant lines covered (57.82%)

38420.67 hits per line

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

75.53
/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,875✔
204

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

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

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

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

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

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

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

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

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

257
        return g, nil
1,875✔
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,847✔
270

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

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

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

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

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

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

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

990✔
304
                switch {
990✔
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
990✔
315

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

322
        return channelMap, nil
1,847✔
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,875✔
357
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
3,750✔
358
                for _, tlb := range graphTopLevelBuckets {
9,375✔
359
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
7,500✔
360
                                return err
×
361
                        }
×
362
                }
363

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

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

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

400
        return nil
1,875✔
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) {
131✔
406
        if c.graphCache != nil {
209✔
407
                return nil, nil
78✔
408
        }
78✔
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,847✔
424

1,847✔
425
        return c.db.View(func(tx kvdb.RTx) error {
3,694✔
426
                edges := tx.ReadBucket(edgeBucket)
1,847✔
427
                if edges == nil {
1,847✔
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,847✔
434
                if err != nil {
1,847✔
435
                        return err
×
436
                }
×
437

438
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,847✔
439
                if edgeIndex == nil {
1,847✔
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,342✔
446
                        var chanID [8]byte
495✔
447
                        copy(chanID[:], k)
495✔
448

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

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

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

495✔
465
                        return cb(&info, policy1, policy2)
495✔
466
                })
467
        }, func() {})
1,847✔
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 {
693✔
478

693✔
479
        if c.graphCache != nil {
1,149✔
480
                return c.graphCache.ForEachChannel(node, cb)
456✔
481
        }
456✔
482

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

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

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

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

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

489✔
522
                if node == e.NodeKey2Bytes {
734✔
523
                        directedChannel.OtherNode = e.NodeKey1Bytes
245✔
524
                }
245✔
525

526
                return cb(directedChannel)
489✔
527
        }
528
        return nodeTraversal(tx, node[:], c.db, dbCallback)
237✔
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,122✔
535

1,122✔
536
        if c.graphCache != nil {
1,569✔
537
                return c.graphCache.GetFeatures(node), nil
447✔
538
        }
447✔
539

540
        // Fallback that uses the database.
541
        targetNode, err := c.FetchLightningNode(node)
675✔
542
        switch err {
675✔
543
        // If the node exists and has features, return them directly.
544
        case nil:
670✔
545
                return targetNode.Features, nil
670✔
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 {
129✔
683

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

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

700
                        nodeReader := bytes.NewReader(nodeBytes)
1,178✔
701
                        node, err := deserializeLightningNode(nodeReader)
1,178✔
702
                        if err != nil {
1,178✔
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,178✔
709
                })
710
        }
711

712
        return kvdb.View(c.db, traversal, func() {})
258✔
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,844✔
721

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

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

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

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

752
        return kvdb.View(c.db, traversal, func() {})
3,688✔
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) {
228✔
760
        var source *LightningNode
228✔
761
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
456✔
762
                // First grab the nodes bucket which stores the mapping from
228✔
763
                // pubKey to node information.
228✔
764
                nodes := tx.ReadBucket(nodeBucket)
228✔
765
                if nodes == nil {
228✔
766
                        return ErrGraphNotFound
×
767
                }
×
768

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

227✔
775
                return nil
227✔
776
        }, func() {
228✔
777
                source = nil
228✔
778
        })
228✔
779
        if err != nil {
229✔
780
                return nil, err
1✔
781
        }
1✔
782

783
        return source, nil
227✔
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) {
495✔
791
        selfPub := nodes.Get(sourceKey)
495✔
792
        if selfPub == nil {
496✔
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)
494✔
799
        if err != nil {
494✔
800
                return nil, err
×
801
        }
×
802

803
        return &node, nil
494✔
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 {
116✔
810
        nodePubBytes := node.PubKeyBytes[:]
116✔
811

116✔
812
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
232✔
813
                // First grab the nodes bucket which stores the mapping from
116✔
814
                // pubKey to node information.
116✔
815
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
116✔
816
                if err != nil {
116✔
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 {
116✔
823
                        return err
×
824
                }
×
825

826
                // Finally, we commit the information of the lightning node
827
                // itself.
828
                return addLightningNode(tx, node)
116✔
829
        }, func() {})
116✔
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 {
785✔
842

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

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

859
        for _, f := range op {
785✔
UNCOV
860
                f(r)
×
UNCOV
861
        }
×
862

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

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

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

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

884
        return putLightningNode(nodes, aliases, updateIndex, node)
972✔
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) {
2✔
890
        var alias string
2✔
891

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

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

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

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

920
        return alias, nil
1✔
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 {
63✔
945

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

951
        if err := aliases.Delete(compressedPubKey); err != nil {
63✔
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)
63✔
959
        if err != nil {
63✔
960
                return err
×
961
        }
×
962

963
        if err := nodes.Delete(compressedPubKey); err != nil {
63✔
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)
63✔
971
        if nodeUpdateIndex == nil {
63✔
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())
63✔
978
        var indexKey [8 + 33]byte
63✔
979
        byteOrder.PutUint64(indexKey[:8], updateUnix)
63✔
980
        copy(indexKey[8:], compressedPubKey)
63✔
981

63✔
982
        return nodeUpdateIndex.Delete(indexKey[:])
63✔
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,683✔
993

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

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

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

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

1029
        return c.chanScheduler.Execute(r)
1,683✔
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,683✔
1036

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

1,683✔
1041
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,683✔
1042
        if err != nil {
1,683✔
1043
                return err
×
1044
        }
×
1045
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,683✔
1046
        if err != nil {
1,683✔
1047
                return err
×
1048
        }
×
1049
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,683✔
1050
        if err != nil {
1,683✔
1051
                return err
×
1052
        }
×
1053
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,683✔
1054
        if err != nil {
1,683✔
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,901✔
1061
                return ErrEdgeAlreadyExist
218✔
1062
        }
218✔
1063

1064
        if c.graphCache != nil {
2,748✔
1065
                c.graphCache.AddChannel(edge, nil, nil)
1,283✔
1066
        }
1,283✔
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,465✔
1073
        switch {
1,465✔
1074
        case node1Err == ErrGraphNodeNotFound:
18✔
1075
                node1Shell := LightningNode{
18✔
1076
                        PubKeyBytes:          edge.NodeKey1Bytes,
18✔
1077
                        HaveNodeAnnouncement: false,
18✔
1078
                }
18✔
1079
                err := addLightningNode(tx, &node1Shell)
18✔
1080
                if err != nil {
18✔
1081
                        return fmt.Errorf("unable to create shell node "+
×
1082
                                "for: %x", edge.NodeKey1Bytes)
×
1083
                }
×
1084
        case node1Err != nil:
×
1085
                return err
×
1086
        }
1087

1088
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
1,465✔
1089
        switch {
1,465✔
1090
        case node2Err == ErrGraphNodeNotFound:
53✔
1091
                node2Shell := LightningNode{
53✔
1092
                        PubKeyBytes:          edge.NodeKey2Bytes,
53✔
1093
                        HaveNodeAnnouncement: false,
53✔
1094
                }
53✔
1095
                err := addLightningNode(tx, &node2Shell)
53✔
1096
                if err != nil {
53✔
1097
                        return fmt.Errorf("unable to create shell node "+
×
1098
                                "for: %x", edge.NodeKey2Bytes)
×
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,465✔
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,465✔
1114
                &edge.NodeKey1Bytes,
1,465✔
1115
                &edge.NodeKey2Bytes,
1,465✔
1116
        }
1,465✔
1117
        for _, key := range keys {
4,395✔
1118
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,930✔
1119
                if err != nil {
2,930✔
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,465✔
1127
        if err := writeOutpoint(&b, &edge.ChannelPoint); err != nil {
1,465✔
1128
                return err
×
1129
        }
×
1130
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,465✔
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) {
217✔
1141

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

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

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

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

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

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

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

1198
                        return nil
95✔
1199
                }
1200

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

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

1212
                e1, e2, err := fetchChanEdgePolicies(
49✔
1213
                        edgeIndex, edges, channelID[:],
49✔
1214
                )
49✔
1215
                if err != nil {
49✔
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 {
67✔
1222
                        upd1Time = e1.LastUpdate
18✔
1223
                }
18✔
1224
                if e2 != nil {
65✔
1225
                        upd2Time = e2.LastUpdate
16✔
1226
                }
16✔
1227

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

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

144✔
1239
        return upd1Time, upd2Time, exists, isZombie, nil
144✔
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 {
1✔
1248
        // Construct the channel's primary key which is the 8-byte channel ID.
1✔
1249
        var chanKey [8]byte
1✔
1250
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1✔
1251

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

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

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

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

1271
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
1✔
1272
        }, func() {})
1✔
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) {
243✔
1294

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

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

243✔
1300
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
486✔
1301
                // First grab the edges bucket which houses the information
243✔
1302
                // we'd like to delete
243✔
1303
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
243✔
1304
                if err != nil {
243✔
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)
243✔
1310
                if err != nil {
243✔
1311
                        return err
×
1312
                }
×
1313
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
243✔
1314
                if err != nil {
243✔
1315
                        return err
×
1316
                }
×
1317
                nodes := tx.ReadWriteBucket(nodeBucket)
243✔
1318
                if nodes == nil {
243✔
1319
                        return ErrSourceNodeNotSet
×
1320
                }
×
1321
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
243✔
1322
                if err != nil {
243✔
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 {
421✔
1330
                        // TODO(roasbeef): load channel bloom filter, continue
178✔
1331
                        // if NOT if filter
178✔
1332

178✔
1333
                        var opBytes bytes.Buffer
178✔
1334
                        if err := writeOutpoint(&opBytes, chanPoint); err != nil {
178✔
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())
178✔
1341
                        if chanID == nil {
333✔
1342
                                continue
155✔
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)
243✔
1369
                if err != nil {
243✔
1370
                        return err
×
1371
                }
×
1372

1373
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
243✔
1374
                if err != nil {
243✔
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
243✔
1382
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
243✔
1383

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

243✔
1387
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
243✔
1388
                if err != nil {
243✔
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)
243✔
1396
        }, func() {
243✔
1397
                chansClosed = nil
243✔
1398
        })
243✔
1399
        if err != nil {
243✔
1400
                return nil, err
×
1401
        }
×
1402

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

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

1413
        return chansClosed, nil
243✔
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 {
24✔
1421
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
48✔
1422
                nodes := tx.ReadWriteBucket(nodeBucket)
24✔
1423
                if nodes == nil {
24✔
1424
                        return ErrGraphNodesNotFound
×
1425
                }
×
1426
                edges := tx.ReadWriteBucket(edgeBucket)
24✔
1427
                if edges == nil {
24✔
1428
                        return ErrGraphNotFound
×
1429
                }
×
1430
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
24✔
1431
                if edgeIndex == nil {
24✔
1432
                        return ErrGraphNoEdgesFound
×
1433
                }
×
1434

1435
                return c.pruneGraphNodes(nodes, edgeIndex)
24✔
1436
        }, func() {})
24✔
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 {
267✔
1444

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

267✔
1447
        // We'll retrieve the graph's source node to ensure we don't remove it
267✔
1448
        // even if it no longer has any open channels.
267✔
1449
        sourceNode, err := c.sourceNode(nodes)
267✔
1450
        if err != nil {
267✔
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)
267✔
1458
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,584✔
1459
                // If this is the source key, then we skip this
1,317✔
1460
                // iteration as the value for this key is a pubKey
1,317✔
1461
                // rather than raw node information.
1,317✔
1462
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
2,118✔
1463
                        return nil
801✔
1464
                }
801✔
1465

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

516✔
1470
                return nil
516✔
1471
        })
1472
        if err != nil {
267✔
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
267✔
1479

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

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

216✔
1496
                return nil
216✔
1497
        })
216✔
1498
        if err != nil {
267✔
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
267✔
1505
        for nodePubKey, refCount := range nodeRefCounts {
783✔
1506
                // If the ref count of the node isn't zero, then we can safely
516✔
1507
                // skip it as it still has edges to or from it within the
516✔
1508
                // graph.
516✔
1509
                if refCount != 0 {
972✔
1510
                        continue
456✔
1511
                }
1512

1513
                if c.graphCache != nil {
120✔
1514
                        c.graphCache.RemoveNode(nodePubKey)
60✔
1515
                }
60✔
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 {
60✔
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",
60✔
1532
                        nodePubKey[:])
60✔
1533

60✔
1534
                numNodesPruned++
60✔
1535
        }
1536

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

1542
        return nil
267✔
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) {
160✔
1554

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

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

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

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

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

160✔
1577
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
320✔
1578
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
160✔
1579
                if err != nil {
160✔
1580
                        return err
×
1581
                }
×
1582
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
160✔
1583
                if err != nil {
160✔
1584
                        return err
×
1585
                }
×
1586
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
160✔
1587
                if err != nil {
160✔
1588
                        return err
×
1589
                }
×
1590
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
160✔
1591
                if err != nil {
160✔
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
160✔
1602
                cursor := edgeIndex.ReadWriteCursor()
160✔
1603

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

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

1617
                for _, k := range keys {
253✔
1618
                        err = c.delChannelEdgeUnsafe(
93✔
1619
                                edges, edgeIndex, chanIndex, zombieIndex,
93✔
1620
                                k, false, false,
93✔
1621
                        )
93✔
1622
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
93✔
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)
160✔
1630
                if err != nil {
160✔
1631
                        return err
×
1632
                }
×
1633

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

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

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

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

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

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

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

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

1673
        return removedChans, nil
160✔
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) {
55✔
1681
        var (
55✔
1682
                tipHash   chainhash.Hash
55✔
1683
                tipHeight uint32
55✔
1684
        )
55✔
1685

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

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

55✔
1698
                // The prune key with the largest block height will be our
55✔
1699
                // prune tip.
55✔
1700
                k, v := pruneCursor.Last()
55✔
1701
                if k == nil {
74✔
1702
                        return ErrGraphNeverPruned
19✔
1703
                }
19✔
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[:])
36✔
1708
                tipHeight = byteOrder.Uint32(k[:])
36✔
1709

36✔
1710
                return nil
36✔
1711
        }, func() {})
55✔
1712
        if err != nil {
74✔
1713
                return nil, 0, err
19✔
1714
        }
19✔
1715

1716
        return &tipHash, tipHeight, nil
36✔
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 {
135✔
1729

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

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

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

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

1771
                return nil
81✔
1772
        }, func() {})
135✔
1773
        if err != nil {
189✔
1774
                return err
54✔
1775
        }
54✔
1776

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

1782
        return nil
81✔
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) {
1✔
1789
        var chanID uint64
1✔
1790
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
2✔
1791
                var err error
1✔
1792
                chanID, err = getChanID(tx, chanPoint)
1✔
1793
                return err
1✔
1794
        }, func() {
2✔
1795
                chanID = 0
1✔
1796
        }); err != nil {
1✔
UNCOV
1797
                return 0, err
×
UNCOV
1798
        }
×
1799

1800
        return chanID, nil
1✔
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) {
1✔
1805
        var b bytes.Buffer
1✔
1806
        if err := writeOutpoint(&b, chanPoint); err != nil {
1✔
1807
                return 0, err
×
1808
        }
×
1809

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

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

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

1✔
1826
        return chanID, nil
1✔
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) {
3✔
1835
        var cid uint64
3✔
1836

3✔
1837
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1838
                edges := tx.ReadBucket(edgeBucket)
3✔
1839
                if edges == nil {
3✔
1840
                        return ErrGraphNoEdgesFound
×
1841
                }
×
1842
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1843
                if edgeIndex == nil {
3✔
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()
3✔
1850

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

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

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

1870
        return cid, nil
3✔
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() {
191✔
1949

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

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

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

1969
                        // First, we'll fetch the static edge information.
1970
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
18✔
1971
                        if err != nil {
18✔
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(
18✔
1980
                                edgeIndex, edges, chanID,
18✔
1981
                        )
18✔
1982
                        if err != nil {
18✔
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(
18✔
1990
                                nodes, edgeInfo.NodeKey1Bytes[:],
18✔
1991
                        )
18✔
1992
                        if err != nil {
18✔
1993
                                return err
×
1994
                        }
×
1995

1996
                        node2, err := fetchLightningNode(
18✔
1997
                                nodes, edgeInfo.NodeKey2Bytes[:],
18✔
1998
                        )
18✔
1999
                        if err != nil {
18✔
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{}{}
18✔
2006
                        channel := ChannelEdge{
18✔
2007
                                Info:    &edgeInfo,
18✔
2008
                                Policy1: edge1,
18✔
2009
                                Policy2: edge2,
18✔
2010
                                Node1:   &node1,
18✔
2011
                                Node2:   &node2,
18✔
2012
                        }
18✔
2013
                        edgesInHorizon = append(edgesInHorizon, channel)
18✔
2014
                        edgesToCache[chanIDInt] = channel
18✔
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 {
163✔
2035
                c.chanCache.insert(chanid, channel)
18✔
2036
        }
18✔
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) {
8✔
2051

8✔
2052
        var nodesInHorizon []LightningNode
8✔
2053

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

2060
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
8✔
2061
                if nodeUpdateIndex == nil {
8✔
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()
8✔
2068

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

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

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

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

2092
                return nil
8✔
2093
        }, func() {
8✔
2094
                nodesInHorizon = nil
8✔
2095
        })
8✔
2096
        switch {
8✔
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
8✔
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) {
124✔
2116

124✔
2117
        var newChanIDs []uint64
124✔
2118

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

124✔
2122
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
248✔
2123
                edges := tx.ReadBucket(edgeBucket)
124✔
2124
                if edges == nil {
124✔
2125
                        return ErrGraphNoEdgesFound
×
2126
                }
×
2127
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
124✔
2128
                if edgeIndex == nil {
124✔
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)
124✔
2136

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

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

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

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

101✔
2175
                                switch {
101✔
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:
30✔
2181
                                        continue
30✔
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:
18✔
2189
                                        err := c.markEdgeLiveUnsafe(tx, scid)
18✔
2190
                                        if err != nil {
18✔
2191
                                                return err
×
2192
                                        }
×
2193
                                }
2194
                        }
2195

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

2199
                return nil
124✔
2200
        }, func() {
124✔
2201
                newChanIDs = nil
124✔
2202
        })
124✔
2203
        switch {
124✔
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
124✔
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 {
218✔
2243

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

218✔
2250
        if node1Timestamp.IsZero() {
426✔
2251
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
208✔
2252
        }
208✔
2253

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

2258
        return chanInfo
218✔
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) {
11✔
2283

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

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

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

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

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

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

2325
                        if edgeInfo.AuthProof == nil {
44✔
UNCOV
2326
                                continue
×
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)
44✔
2332
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
44✔
2333

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

44✔
2338
                        if !withTimestamps {
66✔
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)
22✔
2348

22✔
2349
                        rawPolicy := edges.Get(node1Key)
22✔
2350
                        if len(rawPolicy) != 0 {
28✔
2351
                                r := bytes.NewReader(rawPolicy)
6✔
2352

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

×
2358
                                        return err
×
2359
                                }
×
2360

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

2364
                        rawPolicy = edges.Get(node2Key)
22✔
2365
                        if len(rawPolicy) != 0 {
33✔
2366
                                r := bytes.NewReader(rawPolicy)
11✔
2367

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

×
2373
                                        return err
×
2374
                                }
×
2375

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

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

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

2389
        switch {
11✔
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:
3✔
2393
                return nil, nil
3✔
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))
8✔
2401
        for block := range channelsPerBlock {
30✔
2402
                blocks = append(blocks, block)
22✔
2403
        }
22✔
2404
        sort.Slice(blocks, func(i, j int) bool {
29✔
2405
                return blocks[i] < blocks[j]
21✔
2406
        })
21✔
2407

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

2416
        return channelRanges, nil
8✔
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) {
3✔
2425
        return c.fetchChanInfos(nil, chanIDs)
3✔
2426
}
3✔
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) {
22✔
2438
        // TODO(roasbeef): sort cids?
22✔
2439

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

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

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

29✔
2462
                        // First, we'll fetch the static edge information. If
29✔
2463
                        // the edge is unknown, we will skip the edge and
29✔
2464
                        // continue gathering all known edges.
29✔
2465
                        edgeInfo, err := fetchChanEdgeInfo(
29✔
2466
                                edgeIndex, cidBytes[:],
29✔
2467
                        )
29✔
2468
                        switch {
29✔
2469
                        case errors.Is(err, ErrEdgeNotFound):
21✔
2470
                                continue
21✔
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(
8✔
2478
                                edgeIndex, edges, cidBytes[:],
8✔
2479
                        )
8✔
2480
                        if err != nil {
8✔
2481
                                return err
×
2482
                        }
×
2483

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

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

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

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

2517
                return chanEdges, nil
4✔
2518
        }
2519

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

2525
        return chanEdges, nil
18✔
2526
}
2527

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

140✔
2531
        // First, we'll fetch the edge update index bucket which currently
140✔
2532
        // stores an entry for the channel we're about to delete.
140✔
2533
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
140✔
2534
        if updateIndex == nil {
140✔
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
140✔
2542
        byteOrder.PutUint64(indexKey[8:], chanID)
140✔
2543

140✔
2544
        // With the template constructed, we'll attempt to delete an entry that
140✔
2545
        // would have been created by both edges: we'll alternate the update
140✔
2546
        // times, as one may had overridden the other.
140✔
2547
        if edge1 != nil {
150✔
2548
                byteOrder.PutUint64(indexKey[:8], uint64(edge1.LastUpdate.Unix()))
10✔
2549
                if err := updateIndex.Delete(indexKey[:]); err != nil {
10✔
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 {
152✔
2557
                byteOrder.PutUint64(indexKey[:8], uint64(edge2.LastUpdate.Unix()))
12✔
2558
                if err := updateIndex.Delete(indexKey[:]); err != nil {
12✔
2559
                        return err
×
2560
                }
×
2561
        }
2562

2563
        return nil
140✔
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 {
194✔
2576

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

2582
        if c.graphCache != nil {
280✔
2583
                c.graphCache.RemoveChannel(
140✔
2584
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
140✔
2585
                        edgeInfo.ChannelID,
140✔
2586
                )
140✔
2587
        }
140✔
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)
140✔
2593
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
140✔
2594
        if err != nil {
140✔
2595
                return err
×
2596
        }
×
2597
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
140✔
2598
        if err != nil {
140✔
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
140✔
2605
        copy(edgeKey[33:], chanID)
140✔
2606

140✔
2607
        // With the latter half constructed, copy over the first public key to
140✔
2608
        // delete the edge in this direction, then the second to delete the
140✔
2609
        // edge in the opposite direction.
140✔
2610
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
140✔
2611
        if edges.Get(edgeKey[:]) != nil {
280✔
2612
                if err := edges.Delete(edgeKey[:]); err != nil {
140✔
2613
                        return err
×
2614
                }
×
2615
        }
2616
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
140✔
2617
        if edges.Get(edgeKey[:]) != nil {
280✔
2618
                if err := edges.Delete(edgeKey[:]); err != nil {
140✔
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
        updateEdgePolicyDisabledIndex(edges, cid, false, false)
140✔
2626
        updateEdgePolicyDisabledIndex(edges, cid, true, false)
140✔
2627

140✔
2628
        // With the edge data deleted, we can purge the information from the two
140✔
2629
        // edge indexes.
140✔
2630
        if err := edgeIndex.Delete(chanID); err != nil {
140✔
2631
                return err
×
2632
        }
×
2633
        var b bytes.Buffer
140✔
2634
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
140✔
2635
                return err
×
2636
        }
×
2637
        if err := chanIndex.Delete(b.Bytes()); err != nil {
140✔
2638
                return err
×
2639
        }
×
2640

2641
        // Finally, we'll mark the edge as a zombie within our index if it's
2642
        // being removed due to the channel becoming a zombie. We do this to
2643
        // ensure we don't store unnecessary data for spent channels.
2644
        if !isZombie {
258✔
2645
                return nil
118✔
2646
        }
118✔
2647

2648
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
22✔
2649
        if strictZombie {
25✔
2650
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2651
        }
3✔
2652

2653
        return markEdgeZombie(
22✔
2654
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
22✔
2655
        )
22✔
2656
}
2657

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

3✔
2677
        switch {
3✔
2678
        // If we don't have either edge policy, we'll return both pubkeys so
2679
        // that the channel can be resurrected by either party.
2680
        case e1 == nil && e2 == nil:
×
2681
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2682

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

2690
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2691
        // return a blank pubkey for edge1. In this case, only an update from
2692
        // edge2 can resurect the channel.
2693
        default:
2✔
2694
                return [33]byte{}, info.NodeKey2Bytes
2✔
2695
        }
2696
}
2697

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

2,631✔
2708
        var (
2,631✔
2709
                isUpdate1    bool
2,631✔
2710
                edgeNotFound bool
2,631✔
2711
        )
2,631✔
2712

2,631✔
2713
        r := &batch.Request{
2,631✔
2714
                Reset: func() {
5,262✔
2715
                        isUpdate1 = false
2,631✔
2716
                        edgeNotFound = false
2,631✔
2717
                },
2,631✔
2718
                Update: func(tx kvdb.RwTx) error {
2,631✔
2719
                        var err error
2,631✔
2720
                        isUpdate1, err = updateEdgePolicy(
2,631✔
2721
                                tx, edge, c.graphCache,
2,631✔
2722
                        )
2,631✔
2723

2,631✔
2724
                        // Silence ErrEdgeNotFound so that the batch can
2,631✔
2725
                        // succeed, but propagate the error via local state.
2,631✔
2726
                        if errors.Is(err, ErrEdgeNotFound) {
2,634✔
2727
                                edgeNotFound = true
3✔
2728
                                return nil
3✔
2729
                        }
3✔
2730

2731
                        return err
2,628✔
2732
                },
2733
                OnCommit: func(err error) error {
2,631✔
2734
                        switch {
2,631✔
2735
                        case err != nil:
×
2736
                                return err
×
2737
                        case edgeNotFound:
3✔
2738
                                return ErrEdgeNotFound
3✔
2739
                        default:
2,628✔
2740
                                c.updateEdgeCache(edge, isUpdate1)
2,628✔
2741
                                return nil
2,628✔
2742
                        }
2743
                },
2744
        }
2745

2746
        for _, f := range op {
2,631✔
UNCOV
2747
                f(r)
×
UNCOV
2748
        }
×
2749

2750
        return c.chanScheduler.Execute(r)
2,631✔
2751
}
2752

2753
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2754
        isUpdate1 bool) {
2,628✔
2755

2,628✔
2756
        // If an entry for this channel is found in reject cache, we'll modify
2,628✔
2757
        // the entry with the updated timestamp for the direction that was just
2,628✔
2758
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,628✔
2759
        // during the next query for this edge.
2,628✔
2760
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,633✔
2761
                if isUpdate1 {
8✔
2762
                        entry.upd1Time = e.LastUpdate.Unix()
3✔
2763
                } else {
5✔
2764
                        entry.upd2Time = e.LastUpdate.Unix()
2✔
2765
                }
2✔
2766
                c.rejectCache.insert(e.ChannelID, entry)
5✔
2767
        }
2768

2769
        // If an entry for this channel is found in channel cache, we'll modify
2770
        // the entry with the updated policy for the direction that was just
2771
        // written. If the edge doesn't exist, we'll defer loading the info and
2772
        // policies and lazily read from disk during the next query.
2773
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
2,628✔
UNCOV
2774
                if isUpdate1 {
×
UNCOV
2775
                        channel.Policy1 = e
×
UNCOV
2776
                } else {
×
UNCOV
2777
                        channel.Policy2 = e
×
UNCOV
2778
                }
×
UNCOV
2779
                c.chanCache.insert(e.ChannelID, channel)
×
2780
        }
2781
}
2782

2783
// updateEdgePolicy attempts to update an edge's policy within the relevant
2784
// buckets using an existing database transaction. The returned boolean will be
2785
// true if the updated policy belongs to node1, and false if the policy belonged
2786
// to node2.
2787
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy,
2788
        graphCache *GraphCache) (bool, error) {
2,631✔
2789

2,631✔
2790
        edges := tx.ReadWriteBucket(edgeBucket)
2,631✔
2791
        if edges == nil {
2,631✔
2792
                return false, ErrEdgeNotFound
×
2793
        }
×
2794
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,631✔
2795
        if edgeIndex == nil {
2,631✔
2796
                return false, ErrEdgeNotFound
×
2797
        }
×
2798

2799
        // Create the channelID key be converting the channel ID
2800
        // integer into a byte slice.
2801
        var chanID [8]byte
2,631✔
2802
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,631✔
2803

2,631✔
2804
        // With the channel ID, we then fetch the value storing the two
2,631✔
2805
        // nodes which connect this channel edge.
2,631✔
2806
        nodeInfo := edgeIndex.Get(chanID[:])
2,631✔
2807
        if nodeInfo == nil {
2,634✔
2808
                return false, ErrEdgeNotFound
3✔
2809
        }
3✔
2810

2811
        // Depending on the flags value passed above, either the first
2812
        // or second edge policy is being updated.
2813
        var fromNode, toNode []byte
2,628✔
2814
        var isUpdate1 bool
2,628✔
2815
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3,946✔
2816
                fromNode = nodeInfo[:33]
1,318✔
2817
                toNode = nodeInfo[33:66]
1,318✔
2818
                isUpdate1 = true
1,318✔
2819
        } else {
2,628✔
2820
                fromNode = nodeInfo[33:66]
1,310✔
2821
                toNode = nodeInfo[:33]
1,310✔
2822
                isUpdate1 = false
1,310✔
2823
        }
1,310✔
2824

2825
        // Finally, with the direction of the edge being updated
2826
        // identified, we update the on-disk edge representation.
2827
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,628✔
2828
        if err != nil {
2,628✔
2829
                return false, err
×
2830
        }
×
2831

2832
        var (
2,628✔
2833
                fromNodePubKey route.Vertex
2,628✔
2834
                toNodePubKey   route.Vertex
2,628✔
2835
        )
2,628✔
2836
        copy(fromNodePubKey[:], fromNode)
2,628✔
2837
        copy(toNodePubKey[:], toNode)
2,628✔
2838

2,628✔
2839
        if graphCache != nil {
4,886✔
2840
                graphCache.UpdatePolicy(
2,258✔
2841
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,258✔
2842
                )
2,258✔
2843
        }
2,258✔
2844

2845
        return isUpdate1, nil
2,628✔
2846
}
2847

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

2857
        // HaveNodeAnnouncement indicates whether we received a node
2858
        // announcement for this particular node. If true, the remaining fields
2859
        // will be set, if false only the PubKey is known for this node.
2860
        HaveNodeAnnouncement bool
2861

2862
        // LastUpdate is the last time the vertex information for this node has
2863
        // been updated.
2864
        LastUpdate time.Time
2865

2866
        // Address is the TCP address this node is reachable over.
2867
        Addresses []net.Addr
2868

2869
        // Color is the selected color for the node.
2870
        Color color.RGBA
2871

2872
        // Alias is a nick-name for the node. The alias can be used to confirm
2873
        // a node's identity or to serve as a short ID for an address book.
2874
        Alias string
2875

2876
        // AuthSigBytes is the raw signature under the advertised public key
2877
        // which serves to authenticate the attributes announced by this node.
2878
        AuthSigBytes []byte
2879

2880
        // Features is the list of protocol features supported by this node.
2881
        Features *lnwire.FeatureVector
2882

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

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

2894
        // TODO(roasbeef): add update method and fetch?
2895
}
2896

2897
// PubKey is the node's long-term identity public key. This key will be used to
2898
// authenticated any advertisements/updates sent by the node.
2899
//
2900
// NOTE: By having this method to access an attribute, we ensure we only need
2901
// to fully deserialize the pubkey if absolutely necessary.
2902
func (l *LightningNode) PubKey() (*btcec.PublicKey, error) {
1,456✔
2903
        if l.pubKey != nil {
1,939✔
2904
                return l.pubKey, nil
483✔
2905
        }
483✔
2906

2907
        key, err := btcec.ParsePubKey(l.PubKeyBytes[:])
973✔
2908
        if err != nil {
973✔
2909
                return nil, err
×
2910
        }
×
2911
        l.pubKey = key
973✔
2912

973✔
2913
        return key, nil
973✔
2914
}
2915

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

2925
// AddPubKey is a setter-link method that can be used to swap out the public
2926
// key for a node.
2927
func (l *LightningNode) AddPubKey(key *btcec.PublicKey) {
60✔
2928
        l.pubKey = key
60✔
2929
        copy(l.PubKeyBytes[:], key.SerializeCompressed())
60✔
2930
}
60✔
2931

2932
// NodeAnnouncement retrieves the latest node announcement of the node.
2933
func (l *LightningNode) NodeAnnouncement(signed bool) (*lnwire.NodeAnnouncement,
2934
        error) {
14✔
2935

14✔
2936
        if !l.HaveNodeAnnouncement {
14✔
UNCOV
2937
                return nil, fmt.Errorf("node does not have node announcement")
×
UNCOV
2938
        }
×
2939

2940
        alias, err := lnwire.NewNodeAlias(l.Alias)
14✔
2941
        if err != nil {
14✔
2942
                return nil, err
×
2943
        }
×
2944

2945
        nodeAnn := &lnwire.NodeAnnouncement{
14✔
2946
                Features:        l.Features.RawFeatureVector,
14✔
2947
                NodeID:          l.PubKeyBytes,
14✔
2948
                RGBColor:        l.Color,
14✔
2949
                Alias:           alias,
14✔
2950
                Addresses:       l.Addresses,
14✔
2951
                Timestamp:       uint32(l.LastUpdate.Unix()),
14✔
2952
                ExtraOpaqueData: l.ExtraOpaqueData,
14✔
2953
        }
14✔
2954

14✔
2955
        if !signed {
14✔
UNCOV
2956
                return nodeAnn, nil
×
UNCOV
2957
        }
×
2958

2959
        sig, err := lnwire.NewSigFromECDSARawSignature(l.AuthSigBytes)
14✔
2960
        if err != nil {
14✔
2961
                return nil, err
×
2962
        }
×
2963

2964
        nodeAnn.Signature = sig
14✔
2965

14✔
2966
        return nodeAnn, nil
14✔
2967
}
2968

2969
// isPublic determines whether the node is seen as public within the graph from
2970
// the source node's point of view. An existing database transaction can also be
2971
// specified.
2972
func (c *ChannelGraph) isPublic(tx kvdb.RTx, nodePub route.Vertex,
2973
        sourcePubKey []byte) (bool, error) {
13✔
2974

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

10✔
2985
                // If this edge doesn't extend to the source node, we'll
10✔
2986
                // terminate our search as we can now conclude that the node is
10✔
2987
                // publicly advertised within the graph due to the local node
10✔
2988
                // knowing of the current edge.
10✔
2989
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
10✔
2990
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
13✔
2991

3✔
2992
                        nodeIsPublic = true
3✔
2993
                        return errDone
3✔
2994
                }
3✔
2995

2996
                // Since the edge _does_ extend to the source node, we'll also
2997
                // need to ensure that this is a public edge.
2998
                if info.AuthProof != nil {
13✔
2999
                        nodeIsPublic = true
6✔
3000
                        return errDone
6✔
3001
                }
6✔
3002

3003
                // Otherwise, we'll continue our search.
3004
                return nil
1✔
3005
        })
3006
        if err != nil && err != errDone {
13✔
3007
                return false, err
×
3008
        }
×
3009

3010
        return nodeIsPublic, nil
13✔
3011
}
3012

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

2,944✔
3020
        return c.fetchLightningNode(tx, nodePub)
2,944✔
3021
}
2,944✔
3022

3023
// FetchLightningNode attempts to look up a target node by its identity public
3024
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
3025
// returned.
3026
func (c *ChannelGraph) FetchLightningNode(nodePub route.Vertex) (*LightningNode,
3027
        error) {
826✔
3028

826✔
3029
        return c.fetchLightningNode(nil, nodePub)
826✔
3030
}
826✔
3031

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

3,770✔
3039
        var node *LightningNode
3,770✔
3040
        fetch := func(tx kvdb.RTx) error {
7,540✔
3041
                // First grab the nodes bucket which stores the mapping from
3,770✔
3042
                // pubKey to node information.
3,770✔
3043
                nodes := tx.ReadBucket(nodeBucket)
3,770✔
3044
                if nodes == nil {
3,770✔
3045
                        return ErrGraphNotFound
×
3046
                }
×
3047

3048
                // If a key for this serialized public key isn't found, then
3049
                // the target node doesn't exist within the database.
3050
                nodeBytes := nodes.Get(nodePub[:])
3,770✔
3051
                if nodeBytes == nil {
3,778✔
3052
                        return ErrGraphNodeNotFound
8✔
3053
                }
8✔
3054

3055
                // If the node is found, then we can de deserialize the node
3056
                // information to return to the user.
3057
                nodeReader := bytes.NewReader(nodeBytes)
3,762✔
3058
                n, err := deserializeLightningNode(nodeReader)
3,762✔
3059
                if err != nil {
3,762✔
3060
                        return err
×
3061
                }
×
3062

3063
                node = &n
3,762✔
3064

3,762✔
3065
                return nil
3,762✔
3066
        }
3067

3068
        if tx == nil {
4,596✔
3069
                err := kvdb.View(
826✔
3070
                        c.db, fetch, func() {
1,652✔
3071
                                node = nil
826✔
3072
                        },
826✔
3073
                )
3074
                if err != nil {
834✔
3075
                        return nil, err
8✔
3076
                }
8✔
3077

3078
                return node, nil
818✔
3079
        }
3080

3081
        err := fetch(tx)
2,944✔
3082
        if err != nil {
2,944✔
3083
                return nil, err
×
3084
        }
×
3085

3086
        return node, nil
2,944✔
3087
}
3088

3089
// graphCacheNode is a struct that wraps a LightningNode in a way that it can be
3090
// cached in the graph cache.
3091
type graphCacheNode struct {
3092
        pubKeyBytes route.Vertex
3093
        features    *lnwire.FeatureVector
3094
}
3095

3096
// newGraphCacheNode returns a new cache optimized node.
3097
func newGraphCacheNode(pubKey route.Vertex,
3098
        features *lnwire.FeatureVector) *graphCacheNode {
725✔
3099

725✔
3100
        return &graphCacheNode{
725✔
3101
                pubKeyBytes: pubKey,
725✔
3102
                features:    features,
725✔
3103
        }
725✔
3104
}
725✔
3105

3106
// PubKey returns the node's public identity key.
3107
func (n *graphCacheNode) PubKey() route.Vertex {
725✔
3108
        return n.pubKeyBytes
725✔
3109
}
725✔
3110

3111
// Features returns the node's features.
3112
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
705✔
3113
        return n.features
705✔
3114
}
705✔
3115

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

625✔
3128
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
625✔
3129
}
625✔
3130

3131
var _ GraphCacheNode = (*graphCacheNode)(nil)
3132

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

16✔
3144
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
32✔
3145
                // First grab the nodes bucket which stores the mapping from
16✔
3146
                // pubKey to node information.
16✔
3147
                nodes := tx.ReadBucket(nodeBucket)
16✔
3148
                if nodes == nil {
16✔
3149
                        return ErrGraphNotFound
×
3150
                }
×
3151

3152
                // If a key for this serialized public key isn't found, we can
3153
                // exit early.
3154
                nodeBytes := nodes.Get(nodePub[:])
16✔
3155
                if nodeBytes == nil {
19✔
3156
                        exists = false
3✔
3157
                        return nil
3✔
3158
                }
3✔
3159

3160
                // Otherwise we continue on to obtain the time stamp
3161
                // representing the last time the data for this node was
3162
                // updated.
3163
                nodeReader := bytes.NewReader(nodeBytes)
13✔
3164
                node, err := deserializeLightningNode(nodeReader)
13✔
3165
                if err != nil {
13✔
3166
                        return err
×
3167
                }
×
3168

3169
                exists = true
13✔
3170
                updateTime = node.LastUpdate
13✔
3171
                return nil
13✔
3172
        }, func() {
16✔
3173
                updateTime = time.Time{}
16✔
3174
                exists = false
16✔
3175
        })
16✔
3176
        if err != nil {
16✔
3177
                return time.Time{}, exists, err
×
3178
        }
×
3179

3180
        return updateTime, exists, nil
16✔
3181
}
3182

3183
// nodeTraversal is used to traverse all channels of a node given by its
3184
// public key and passes channel information into the specified callback.
3185
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3186
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3187
                *models.ChannelEdgePolicy) error) error {
1,866✔
3188

1,866✔
3189
        traversal := func(tx kvdb.RTx) error {
3,732✔
3190
                edges := tx.ReadBucket(edgeBucket)
1,866✔
3191
                if edges == nil {
1,866✔
3192
                        return ErrGraphNotFound
×
3193
                }
×
3194
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,866✔
3195
                if edgeIndex == nil {
1,866✔
3196
                        return ErrGraphNoEdgesFound
×
3197
                }
×
3198

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

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

3226
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,843✔
3227
                                edges, chanID, nodePub,
3,843✔
3228
                        )
3,843✔
3229
                        if err != nil {
3,843✔
3230
                                return err
×
3231
                        }
×
3232

3233
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,843✔
3234
                        if err != nil {
3,843✔
3235
                                return err
×
3236
                        }
×
3237

3238
                        incomingPolicy, err := fetchChanEdgePolicy(
3,843✔
3239
                                edges, chanID, otherNode[:],
3,843✔
3240
                        )
3,843✔
3241
                        if err != nil {
3,843✔
3242
                                return err
×
3243
                        }
×
3244

3245
                        // Finally, we execute the callback.
3246
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,843✔
3247
                        if err != nil {
3,852✔
3248
                                return err
9✔
3249
                        }
9✔
3250
                }
3251

3252
                return nil
1,857✔
3253
        }
3254

3255
        // If no transaction was provided, then we'll create a new transaction
3256
        // to execute the transaction within.
3257
        if tx == nil {
1,875✔
3258
                return kvdb.View(db, traversal, func() {})
18✔
3259
        }
3260

3261
        // Otherwise, we re-use the existing transaction to execute the graph
3262
        // traversal.
3263
        return traversal(tx)
1,857✔
3264
}
3265

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

6✔
3278
        return nodeTraversal(nil, nodePub[:], c.db, cb)
6✔
3279
}
6✔
3280

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

998✔
3299
        return nodeTraversal(tx, nodePub[:], c.db, cb)
998✔
3300
}
998✔
3301

3302
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3303
// the target node in the channel. This is useful when one knows the pubkey of
3304
// one of the nodes, and wishes to obtain the full LightningNode for the other
3305
// end of the channel.
3306
func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx,
3307
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (*LightningNode,
UNCOV
3308
        error) {
×
UNCOV
3309

×
UNCOV
3310
        // Ensure that the node passed in is actually a member of the channel.
×
UNCOV
3311
        var targetNodeBytes [33]byte
×
UNCOV
3312
        switch {
×
UNCOV
3313
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
×
UNCOV
3314
                targetNodeBytes = channel.NodeKey2Bytes
×
UNCOV
3315
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
×
UNCOV
3316
                targetNodeBytes = channel.NodeKey1Bytes
×
3317
        default:
×
3318
                return nil, fmt.Errorf("node not participating in this channel")
×
3319
        }
3320

UNCOV
3321
        var targetNode *LightningNode
×
UNCOV
3322
        fetchNodeFunc := func(tx kvdb.RTx) error {
×
UNCOV
3323
                // First grab the nodes bucket which stores the mapping from
×
UNCOV
3324
                // pubKey to node information.
×
UNCOV
3325
                nodes := tx.ReadBucket(nodeBucket)
×
UNCOV
3326
                if nodes == nil {
×
3327
                        return ErrGraphNotFound
×
3328
                }
×
3329

UNCOV
3330
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
×
UNCOV
3331
                if err != nil {
×
3332
                        return err
×
3333
                }
×
3334

UNCOV
3335
                targetNode = &node
×
UNCOV
3336

×
UNCOV
3337
                return nil
×
3338
        }
3339

3340
        // If the transaction is nil, then we'll need to create a new one,
3341
        // otherwise we can use the existing db transaction.
UNCOV
3342
        var err error
×
UNCOV
3343
        if tx == nil {
×
3344
                err = kvdb.View(c.db, fetchNodeFunc, func() { targetNode = nil })
×
UNCOV
3345
        } else {
×
UNCOV
3346
                err = fetchNodeFunc(tx)
×
UNCOV
3347
        }
×
3348

UNCOV
3349
        return targetNode, err
×
3350
}
3351

3352
// computeEdgePolicyKeys is a helper function that can be used to compute the
3353
// keys used to index the channel edge policy info for the two nodes of the
3354
// edge. The keys for node 1 and node 2 are returned respectively.
3355
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
22✔
3356
        var (
22✔
3357
                node1Key [33 + 8]byte
22✔
3358
                node2Key [33 + 8]byte
22✔
3359
        )
22✔
3360

22✔
3361
        copy(node1Key[:], info.NodeKey1Bytes[:])
22✔
3362
        copy(node2Key[:], info.NodeKey2Bytes[:])
22✔
3363

22✔
3364
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
22✔
3365
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
22✔
3366

22✔
3367
        return node1Key[:], node2Key[:]
22✔
3368
}
22✔
3369

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

11✔
3379
        var (
11✔
3380
                edgeInfo *models.ChannelEdgeInfo
11✔
3381
                policy1  *models.ChannelEdgePolicy
11✔
3382
                policy2  *models.ChannelEdgePolicy
11✔
3383
        )
11✔
3384

11✔
3385
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
22✔
3386
                // First, grab the node bucket. This will be used to populate
11✔
3387
                // the Node pointers in each edge read from disk.
11✔
3388
                nodes := tx.ReadBucket(nodeBucket)
11✔
3389
                if nodes == nil {
11✔
3390
                        return ErrGraphNotFound
×
3391
                }
×
3392

3393
                // Next, grab the edge bucket which stores the edges, and also
3394
                // the index itself so we can group the directed edges together
3395
                // logically.
3396
                edges := tx.ReadBucket(edgeBucket)
11✔
3397
                if edges == nil {
11✔
3398
                        return ErrGraphNoEdgesFound
×
3399
                }
×
3400
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
11✔
3401
                if edgeIndex == nil {
11✔
3402
                        return ErrGraphNoEdgesFound
×
3403
                }
×
3404

3405
                // If the channel's outpoint doesn't exist within the outpoint
3406
                // index, then the edge does not exist.
3407
                chanIndex := edges.NestedReadBucket(channelPointBucket)
11✔
3408
                if chanIndex == nil {
11✔
3409
                        return ErrGraphNoEdgesFound
×
3410
                }
×
3411
                var b bytes.Buffer
11✔
3412
                if err := writeOutpoint(&b, op); err != nil {
11✔
3413
                        return err
×
3414
                }
×
3415
                chanID := chanIndex.Get(b.Bytes())
11✔
3416
                if chanID == nil {
21✔
3417
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
10✔
3418
                }
10✔
3419

3420
                // If the channel is found to exists, then we'll first retrieve
3421
                // the general information for the channel.
3422
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
1✔
3423
                if err != nil {
1✔
3424
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3425
                }
×
3426
                edgeInfo = &edge
1✔
3427

1✔
3428
                // Once we have the information about the channels' parameters,
1✔
3429
                // we'll fetch the routing policies for each for the directed
1✔
3430
                // edges.
1✔
3431
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
1✔
3432
                if err != nil {
1✔
3433
                        return fmt.Errorf("failed to find policy: %w", err)
×
3434
                }
×
3435

3436
                policy1 = e1
1✔
3437
                policy2 = e2
1✔
3438
                return nil
1✔
3439
        }, func() {
11✔
3440
                edgeInfo = nil
11✔
3441
                policy1 = nil
11✔
3442
                policy2 = nil
11✔
3443
        })
11✔
3444
        if err != nil {
21✔
3445
                return nil, nil, nil, err
10✔
3446
        }
10✔
3447

3448
        return edgeInfo, policy1, policy2, nil
1✔
3449
}
3450

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

25✔
3464
        var (
25✔
3465
                edgeInfo  *models.ChannelEdgeInfo
25✔
3466
                policy1   *models.ChannelEdgePolicy
25✔
3467
                policy2   *models.ChannelEdgePolicy
25✔
3468
                channelID [8]byte
25✔
3469
        )
25✔
3470

25✔
3471
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
50✔
3472
                // First, grab the node bucket. This will be used to populate
25✔
3473
                // the Node pointers in each edge read from disk.
25✔
3474
                nodes := tx.ReadBucket(nodeBucket)
25✔
3475
                if nodes == nil {
25✔
3476
                        return ErrGraphNotFound
×
3477
                }
×
3478

3479
                // Next, grab the edge bucket which stores the edges, and also
3480
                // the index itself so we can group the directed edges together
3481
                // logically.
3482
                edges := tx.ReadBucket(edgeBucket)
25✔
3483
                if edges == nil {
25✔
3484
                        return ErrGraphNoEdgesFound
×
3485
                }
×
3486
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
25✔
3487
                if edgeIndex == nil {
25✔
3488
                        return ErrGraphNoEdgesFound
×
3489
                }
×
3490

3491
                byteOrder.PutUint64(channelID[:], chanID)
25✔
3492

25✔
3493
                // Now, attempt to fetch edge.
25✔
3494
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
25✔
3495

25✔
3496
                // If it doesn't exist, we'll quickly check our zombie index to
25✔
3497
                // see if we've previously marked it as so.
25✔
3498
                if errors.Is(err, ErrEdgeNotFound) {
26✔
3499
                        // If the zombie index doesn't exist, or the edge is not
1✔
3500
                        // marked as a zombie within it, then we'll return the
1✔
3501
                        // original ErrEdgeNotFound error.
1✔
3502
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
1✔
3503
                        if zombieIndex == nil {
1✔
3504
                                return ErrEdgeNotFound
×
3505
                        }
×
3506

3507
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
1✔
3508
                                zombieIndex, chanID,
1✔
3509
                        )
1✔
3510
                        if !isZombie {
1✔
UNCOV
3511
                                return ErrEdgeNotFound
×
UNCOV
3512
                        }
×
3513

3514
                        // Otherwise, the edge is marked as a zombie, so we'll
3515
                        // populate the edge info with the public keys of each
3516
                        // party as this is the only information we have about
3517
                        // it and return an error signaling so.
3518
                        edgeInfo = &models.ChannelEdgeInfo{
1✔
3519
                                NodeKey1Bytes: pubKey1,
1✔
3520
                                NodeKey2Bytes: pubKey2,
1✔
3521
                        }
1✔
3522
                        return ErrZombieEdge
1✔
3523
                }
3524

3525
                // Otherwise, we'll just return the error if any.
3526
                if err != nil {
24✔
3527
                        return err
×
3528
                }
×
3529

3530
                edgeInfo = &edge
24✔
3531

24✔
3532
                // Then we'll attempt to fetch the accompanying policies of this
24✔
3533
                // edge.
24✔
3534
                e1, e2, err := fetchChanEdgePolicies(
24✔
3535
                        edgeIndex, edges, channelID[:],
24✔
3536
                )
24✔
3537
                if err != nil {
24✔
3538
                        return err
×
3539
                }
×
3540

3541
                policy1 = e1
24✔
3542
                policy2 = e2
24✔
3543
                return nil
24✔
3544
        }, func() {
25✔
3545
                edgeInfo = nil
25✔
3546
                policy1 = nil
25✔
3547
                policy2 = nil
25✔
3548
        })
25✔
3549
        if err == ErrZombieEdge {
26✔
3550
                return edgeInfo, nil, nil, err
1✔
3551
        }
1✔
3552
        if err != nil {
24✔
UNCOV
3553
                return nil, nil, nil, err
×
UNCOV
3554
        }
×
3555

3556
        return edgeInfo, policy1, policy2, nil
24✔
3557
}
3558

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

3578
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
13✔
3579
                return err
13✔
3580
        }, func() {
13✔
3581
                nodeIsPublic = false
13✔
3582
        })
13✔
3583
        if err != nil {
13✔
3584
                return false, err
×
3585
        }
×
3586

3587
        return nodeIsPublic, nil
13✔
3588
}
3589

3590
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3591
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
46✔
3592
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
46✔
3593
        if err != nil {
46✔
3594
                return nil, err
×
3595
        }
×
3596

3597
        // With the witness script generated, we'll now turn it into a p2wsh
3598
        // script:
3599
        //  * OP_0 <sha256(script)>
3600
        bldr := txscript.NewScriptBuilder(
46✔
3601
                txscript.WithScriptAllocSize(input.P2WSHSize),
46✔
3602
        )
46✔
3603
        bldr.AddOp(txscript.OP_0)
46✔
3604
        scriptHash := sha256.Sum256(witnessScript)
46✔
3605
        bldr.AddData(scriptHash[:])
46✔
3606

46✔
3607
        return bldr.Script()
46✔
3608
}
3609

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

3618
        // OutPoint is the outpoint of the target channel.
3619
        OutPoint wire.OutPoint
3620
}
3621

3622
// String returns a human readable version of the target EdgePoint. We return
3623
// the outpoint directly as it is enough to uniquely identify the edge point.
3624
func (e *EdgePoint) String() string {
×
3625
        return e.OutPoint.String()
×
3626
}
×
3627

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

3651
                // Once we have the proper bucket, we'll range over each key
3652
                // (which is the channel point for the channel) and decode it,
3653
                // accumulating each entry.
3654
                return chanIndex.ForEach(func(chanPointBytes, chanID []byte) error {
65✔
3655
                        chanPointReader := bytes.NewReader(chanPointBytes)
42✔
3656

42✔
3657
                        var chanPoint wire.OutPoint
42✔
3658
                        err := readOutpoint(chanPointReader, &chanPoint)
42✔
3659
                        if err != nil {
42✔
3660
                                return err
×
3661
                        }
×
3662

3663
                        edgeInfo, err := fetchChanEdgeInfo(
42✔
3664
                                edgeIndex, chanID,
42✔
3665
                        )
42✔
3666
                        if err != nil {
42✔
3667
                                return err
×
3668
                        }
×
3669

3670
                        pkScript, err := genMultiSigP2WSH(
42✔
3671
                                edgeInfo.BitcoinKey1Bytes[:],
42✔
3672
                                edgeInfo.BitcoinKey2Bytes[:],
42✔
3673
                        )
42✔
3674
                        if err != nil {
42✔
3675
                                return err
×
3676
                        }
×
3677

3678
                        edgePoints = append(edgePoints, EdgePoint{
42✔
3679
                                FundingPkScript: pkScript,
42✔
3680
                                OutPoint:        chanPoint,
42✔
3681
                        })
42✔
3682

42✔
3683
                        return nil
42✔
3684
                })
3685
        }, func() {
23✔
3686
                edgePoints = nil
23✔
3687
        }); err != nil {
23✔
3688
                return nil, err
×
3689
        }
×
3690

3691
        return edgePoints, nil
23✔
3692
}
3693

3694
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3695
// zombie. This method is used on an ad-hoc basis, when channels need to be
3696
// marked as zombies outside the normal pruning cycle.
3697
func (c *ChannelGraph) MarkEdgeZombie(chanID uint64,
3698
        pubKey1, pubKey2 [33]byte) error {
123✔
3699

123✔
3700
        c.cacheMu.Lock()
123✔
3701
        defer c.cacheMu.Unlock()
123✔
3702

123✔
3703
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
246✔
3704
                edges := tx.ReadWriteBucket(edgeBucket)
123✔
3705
                if edges == nil {
123✔
3706
                        return ErrGraphNoEdgesFound
×
3707
                }
×
3708
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
123✔
3709
                if err != nil {
123✔
3710
                        return fmt.Errorf("unable to create zombie "+
×
3711
                                "bucket: %w", err)
×
3712
                }
×
3713

3714
                if c.graphCache != nil {
246✔
3715
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
123✔
3716
                }
123✔
3717

3718
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
123✔
3719
        })
3720
        if err != nil {
123✔
3721
                return err
×
3722
        }
×
3723

3724
        c.rejectCache.remove(chanID)
123✔
3725
        c.chanCache.remove(chanID)
123✔
3726

123✔
3727
        return nil
123✔
3728
}
3729

3730
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3731
// keys should represent the node public keys of the two parties involved in the
3732
// edge.
3733
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3734
        pubKey2 [33]byte) error {
145✔
3735

145✔
3736
        var k [8]byte
145✔
3737
        byteOrder.PutUint64(k[:], chanID)
145✔
3738

145✔
3739
        var v [66]byte
145✔
3740
        copy(v[:33], pubKey1[:])
145✔
3741
        copy(v[33:], pubKey2[:])
145✔
3742

145✔
3743
        return zombieIndex.Put(k[:], v[:])
145✔
3744
}
145✔
3745

3746
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3747
func (c *ChannelGraph) MarkEdgeLive(chanID uint64) error {
2✔
3748
        c.cacheMu.Lock()
2✔
3749
        defer c.cacheMu.Unlock()
2✔
3750

2✔
3751
        return c.markEdgeLiveUnsafe(nil, chanID)
2✔
3752
}
2✔
3753

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

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

20✔
3774
                if len(zombieIndex.Get(k[:])) == 0 {
21✔
3775
                        return ErrZombieEdgeNotFound
1✔
3776
                }
1✔
3777

3778
                return zombieIndex.Delete(k[:])
19✔
3779
        }
3780

3781
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3782
        // the existing transaction
3783
        var err error
20✔
3784
        if tx == nil {
22✔
3785
                err = kvdb.Update(c.db, dbFn, func() {})
4✔
3786
        } else {
18✔
3787
                err = dbFn(tx)
18✔
3788
        }
18✔
3789
        if err != nil {
21✔
3790
                return err
1✔
3791
        }
1✔
3792

3793
        c.rejectCache.remove(chanID)
19✔
3794
        c.chanCache.remove(chanID)
19✔
3795

19✔
3796
        // We need to add the channel back into our graph cache, otherwise we
19✔
3797
        // won't use it for path finding.
19✔
3798
        if c.graphCache != nil {
38✔
3799
                edgeInfos, err := c.fetchChanInfos(tx, []uint64{chanID})
19✔
3800
                if err != nil {
19✔
3801
                        return err
×
3802
                }
×
3803

3804
                for _, edgeInfo := range edgeInfos {
19✔
3805
                        c.graphCache.AddChannel(
×
3806
                                edgeInfo.Info, edgeInfo.Policy1,
×
3807
                                edgeInfo.Policy2,
×
3808
                        )
×
3809
                }
×
3810
        }
3811

3812
        return nil
19✔
3813
}
3814

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

5✔
3824
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3825
                edges := tx.ReadBucket(edgeBucket)
5✔
3826
                if edges == nil {
5✔
3827
                        return ErrGraphNoEdgesFound
×
3828
                }
×
3829
                zombieIndex := edges.NestedReadBucket(zombieBucket)
5✔
3830
                if zombieIndex == nil {
5✔
3831
                        return nil
×
3832
                }
×
3833

3834
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
5✔
3835
                return nil
5✔
3836
        }, func() {
5✔
3837
                isZombie = false
5✔
3838
                pubKey1 = [33]byte{}
5✔
3839
                pubKey2 = [33]byte{}
5✔
3840
        })
5✔
3841
        if err != nil {
5✔
3842
                return false, [33]byte{}, [33]byte{}
×
3843
        }
×
3844

3845
        return isZombie, pubKey1, pubKey2
5✔
3846
}
3847

3848
// isZombieEdge returns whether an entry exists for the given channel in the
3849
// zombie index. If an entry exists, then the two node public keys corresponding
3850
// to this edge are also returned.
3851
func isZombieEdge(zombieIndex kvdb.RBucket,
3852
        chanID uint64) (bool, [33]byte, [33]byte) {
202✔
3853

202✔
3854
        var k [8]byte
202✔
3855
        byteOrder.PutUint64(k[:], chanID)
202✔
3856

202✔
3857
        v := zombieIndex.Get(k[:])
202✔
3858
        if v == nil {
315✔
3859
                return false, [33]byte{}, [33]byte{}
113✔
3860
        }
113✔
3861

3862
        var pubKey1, pubKey2 [33]byte
89✔
3863
        copy(pubKey1[:], v[:33])
89✔
3864
        copy(pubKey2[:], v[33:])
89✔
3865

89✔
3866
        return true, pubKey1, pubKey2
89✔
3867
}
3868

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

3882
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3883
                        numZombies++
2✔
3884
                        return nil
2✔
3885
                })
2✔
3886
        }, func() {
4✔
3887
                numZombies = 0
4✔
3888
        })
4✔
3889
        if err != nil {
4✔
3890
                return 0, err
×
3891
        }
×
3892

3893
        return numZombies, nil
4✔
3894
}
3895

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

3906
                var k [8]byte
1✔
3907
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3908

1✔
3909
                return closedScids.Put(k[:], []byte{})
1✔
3910
        }, func() {})
1✔
3911
}
3912

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

3924
                var k [8]byte
2✔
3925
                byteOrder.PutUint64(k[:], scid.ToUint64())
2✔
3926

2✔
3927
                if closedScids.Get(k[:]) != nil {
3✔
3928
                        isClosed = true
1✔
3929
                        return nil
1✔
3930
                }
1✔
3931

3932
                return nil
1✔
3933
        }, func() {
2✔
3934
                isClosed = false
2✔
3935
        })
2✔
3936
        if err != nil {
2✔
3937
                return false, err
×
3938
        }
×
3939

3940
        return isClosed, nil
2✔
3941
}
3942

3943
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3944
        updateIndex kvdb.RwBucket, node *LightningNode) error {
972✔
3945

972✔
3946
        var (
972✔
3947
                scratch [16]byte
972✔
3948
                b       bytes.Buffer
972✔
3949
        )
972✔
3950

972✔
3951
        pub, err := node.PubKey()
972✔
3952
        if err != nil {
972✔
3953
                return err
×
3954
        }
×
3955
        nodePub := pub.SerializeCompressed()
972✔
3956

972✔
3957
        // If the node has the update time set, write it, else write 0.
972✔
3958
        updateUnix := uint64(0)
972✔
3959
        if node.LastUpdate.Unix() > 0 {
1,819✔
3960
                updateUnix = uint64(node.LastUpdate.Unix())
847✔
3961
        }
847✔
3962

3963
        byteOrder.PutUint64(scratch[:8], updateUnix)
972✔
3964
        if _, err := b.Write(scratch[:8]); err != nil {
972✔
3965
                return err
×
3966
        }
×
3967

3968
        if _, err := b.Write(nodePub); err != nil {
972✔
3969
                return err
×
3970
        }
×
3971

3972
        // If we got a node announcement for this node, we will have the rest
3973
        // of the data available. If not we don't have more data to write.
3974
        if !node.HaveNodeAnnouncement {
1,044✔
3975
                // Write HaveNodeAnnouncement=0.
72✔
3976
                byteOrder.PutUint16(scratch[:2], 0)
72✔
3977
                if _, err := b.Write(scratch[:2]); err != nil {
72✔
3978
                        return err
×
3979
                }
×
3980

3981
                return nodeBucket.Put(nodePub, b.Bytes())
72✔
3982
        }
3983

3984
        // Write HaveNodeAnnouncement=1.
3985
        byteOrder.PutUint16(scratch[:2], 1)
900✔
3986
        if _, err := b.Write(scratch[:2]); err != nil {
900✔
3987
                return err
×
3988
        }
×
3989

3990
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
900✔
3991
                return err
×
3992
        }
×
3993
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
900✔
3994
                return err
×
3995
        }
×
3996
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
900✔
3997
                return err
×
3998
        }
×
3999

4000
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
900✔
4001
                return err
×
4002
        }
×
4003

4004
        if err := node.Features.Encode(&b); err != nil {
900✔
4005
                return err
×
4006
        }
×
4007

4008
        numAddresses := uint16(len(node.Addresses))
900✔
4009
        byteOrder.PutUint16(scratch[:2], numAddresses)
900✔
4010
        if _, err := b.Write(scratch[:2]); err != nil {
900✔
4011
                return err
×
4012
        }
×
4013

4014
        for _, address := range node.Addresses {
2,030✔
4015
                if err := serializeAddr(&b, address); err != nil {
1,130✔
4016
                        return err
×
4017
                }
×
4018
        }
4019

4020
        sigLen := len(node.AuthSigBytes)
900✔
4021
        if sigLen > 80 {
900✔
4022
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4023
                        sigLen)
×
4024
        }
×
4025

4026
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
900✔
4027
        if err != nil {
900✔
4028
                return err
×
4029
        }
×
4030

4031
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
900✔
4032
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4033
        }
×
4034
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
900✔
4035
        if err != nil {
900✔
4036
                return err
×
4037
        }
×
4038

4039
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
900✔
4040
                return err
×
4041
        }
×
4042

4043
        // With the alias bucket updated, we'll now update the index that
4044
        // tracks the time series of node updates.
4045
        var indexKey [8 + 33]byte
900✔
4046
        byteOrder.PutUint64(indexKey[:8], updateUnix)
900✔
4047
        copy(indexKey[8:], nodePub)
900✔
4048

900✔
4049
        // If there was already an old index entry for this node, then we'll
900✔
4050
        // delete the old one before we write the new entry.
900✔
4051
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
1,002✔
4052
                // Extract out the old update time to we can reconstruct the
102✔
4053
                // prior index key to delete it from the index.
102✔
4054
                oldUpdateTime := nodeBytes[:8]
102✔
4055

102✔
4056
                var oldIndexKey [8 + 33]byte
102✔
4057
                copy(oldIndexKey[:8], oldUpdateTime)
102✔
4058
                copy(oldIndexKey[8:], nodePub)
102✔
4059

102✔
4060
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
102✔
4061
                        return err
×
4062
                }
×
4063
        }
4064

4065
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
900✔
4066
                return err
×
4067
        }
×
4068

4069
        return nodeBucket.Put(nodePub, b.Bytes())
900✔
4070
}
4071

4072
func fetchLightningNode(nodeBucket kvdb.RBucket,
4073
        nodePub []byte) (LightningNode, error) {
3,581✔
4074

3,581✔
4075
        nodeBytes := nodeBucket.Get(nodePub)
3,581✔
4076
        if nodeBytes == nil {
3,652✔
4077
                return LightningNode{}, ErrGraphNodeNotFound
71✔
4078
        }
71✔
4079

4080
        nodeReader := bytes.NewReader(nodeBytes)
3,510✔
4081
        return deserializeLightningNode(nodeReader)
3,510✔
4082
}
4083

4084
func deserializeLightningNodeCacheable(r io.Reader) (*graphCacheNode, error) {
120✔
4085
        // Always populate a feature vector, even if we don't have a node
120✔
4086
        // announcement and short circuit below.
120✔
4087
        node := newGraphCacheNode(
120✔
4088
                route.Vertex{},
120✔
4089
                lnwire.EmptyFeatureVector(),
120✔
4090
        )
120✔
4091

120✔
4092
        var nodeScratch [8]byte
120✔
4093

120✔
4094
        // Skip ahead:
120✔
4095
        // - LastUpdate (8 bytes)
120✔
4096
        if _, err := r.Read(nodeScratch[:]); err != nil {
120✔
4097
                return nil, err
×
4098
        }
×
4099

4100
        if _, err := io.ReadFull(r, node.pubKeyBytes[:]); err != nil {
120✔
4101
                return nil, err
×
4102
        }
×
4103

4104
        // Read the node announcement flag.
4105
        if _, err := r.Read(nodeScratch[:2]); err != nil {
120✔
4106
                return nil, err
×
4107
        }
×
4108
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
120✔
4109

120✔
4110
        // The rest of the data is optional, and will only be there if we got a
120✔
4111
        // node announcement for this node.
120✔
4112
        if hasNodeAnn == 0 {
120✔
UNCOV
4113
                return node, nil
×
UNCOV
4114
        }
×
4115

4116
        // We did get a node announcement for this node, so we'll have the rest
4117
        // of the data available.
4118
        var rgb uint8
120✔
4119
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
120✔
4120
                return nil, err
×
4121
        }
×
4122
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
120✔
4123
                return nil, err
×
4124
        }
×
4125
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
120✔
4126
                return nil, err
×
4127
        }
×
4128

4129
        if _, err := wire.ReadVarString(r, 0); err != nil {
120✔
4130
                return nil, err
×
4131
        }
×
4132

4133
        if err := node.features.Decode(r); err != nil {
120✔
4134
                return nil, err
×
4135
        }
×
4136

4137
        return node, nil
120✔
4138
}
4139

4140
func deserializeLightningNode(r io.Reader) (LightningNode, error) {
8,463✔
4141
        var (
8,463✔
4142
                node    LightningNode
8,463✔
4143
                scratch [8]byte
8,463✔
4144
                err     error
8,463✔
4145
        )
8,463✔
4146

8,463✔
4147
        // Always populate a feature vector, even if we don't have a node
8,463✔
4148
        // announcement and short circuit below.
8,463✔
4149
        node.Features = lnwire.EmptyFeatureVector()
8,463✔
4150

8,463✔
4151
        if _, err := r.Read(scratch[:]); err != nil {
8,463✔
4152
                return LightningNode{}, err
×
4153
        }
×
4154

4155
        unix := int64(byteOrder.Uint64(scratch[:]))
8,463✔
4156
        node.LastUpdate = time.Unix(unix, 0)
8,463✔
4157

8,463✔
4158
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,463✔
4159
                return LightningNode{}, err
×
4160
        }
×
4161

4162
        if _, err := r.Read(scratch[:2]); err != nil {
8,463✔
4163
                return LightningNode{}, err
×
4164
        }
×
4165

4166
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,463✔
4167
        if hasNodeAnn == 1 {
16,786✔
4168
                node.HaveNodeAnnouncement = true
8,323✔
4169
        } else {
8,463✔
4170
                node.HaveNodeAnnouncement = false
140✔
4171
        }
140✔
4172

4173
        // The rest of the data is optional, and will only be there if we got a node
4174
        // announcement for this node.
4175
        if !node.HaveNodeAnnouncement {
8,603✔
4176
                return node, nil
140✔
4177
        }
140✔
4178

4179
        // We did get a node announcement for this node, so we'll have the rest
4180
        // of the data available.
4181
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,323✔
4182
                return LightningNode{}, err
×
4183
        }
×
4184
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,323✔
4185
                return LightningNode{}, err
×
4186
        }
×
4187
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,323✔
4188
                return LightningNode{}, err
×
4189
        }
×
4190

4191
        node.Alias, err = wire.ReadVarString(r, 0)
8,323✔
4192
        if err != nil {
8,323✔
4193
                return LightningNode{}, err
×
4194
        }
×
4195

4196
        err = node.Features.Decode(r)
8,323✔
4197
        if err != nil {
8,323✔
4198
                return LightningNode{}, err
×
4199
        }
×
4200

4201
        if _, err := r.Read(scratch[:2]); err != nil {
8,323✔
4202
                return LightningNode{}, err
×
4203
        }
×
4204
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,323✔
4205

8,323✔
4206
        var addresses []net.Addr
8,323✔
4207
        for i := 0; i < numAddresses; i++ {
18,877✔
4208
                address, err := deserializeAddr(r)
10,554✔
4209
                if err != nil {
10,554✔
4210
                        return LightningNode{}, err
×
4211
                }
×
4212
                addresses = append(addresses, address)
10,554✔
4213
        }
4214
        node.Addresses = addresses
8,323✔
4215

8,323✔
4216
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,323✔
4217
        if err != nil {
8,323✔
4218
                return LightningNode{}, err
×
4219
        }
×
4220

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

4233
        return node, nil
8,323✔
4234
}
4235

4236
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4237
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,466✔
4238

1,466✔
4239
        var b bytes.Buffer
1,466✔
4240

1,466✔
4241
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,466✔
4242
                return err
×
4243
        }
×
4244
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,466✔
4245
                return err
×
4246
        }
×
4247
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,466✔
4248
                return err
×
4249
        }
×
4250
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,466✔
4251
                return err
×
4252
        }
×
4253

4254
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,466✔
4255
                return err
×
4256
        }
×
4257

4258
        authProof := edgeInfo.AuthProof
1,466✔
4259
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,466✔
4260
        if authProof != nil {
2,849✔
4261
                nodeSig1 = authProof.NodeSig1Bytes
1,383✔
4262
                nodeSig2 = authProof.NodeSig2Bytes
1,383✔
4263
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,383✔
4264
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,383✔
4265
        }
1,383✔
4266

4267
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,466✔
4268
                return err
×
4269
        }
×
4270
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,466✔
4271
                return err
×
4272
        }
×
4273
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,466✔
4274
                return err
×
4275
        }
×
4276
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,466✔
4277
                return err
×
4278
        }
×
4279

4280
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,466✔
4281
                return err
×
4282
        }
×
4283
        if err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity)); err != nil {
1,466✔
4284
                return err
×
4285
        }
×
4286
        if _, err := b.Write(chanID[:]); err != nil {
1,466✔
4287
                return err
×
4288
        }
×
4289
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,466✔
4290
                return err
×
4291
        }
×
4292

4293
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,466✔
4294
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4295
        }
×
4296
        err := wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,466✔
4297
        if err != nil {
1,466✔
4298
                return err
×
4299
        }
×
4300

4301
        return edgeIndex.Put(chanID[:], b.Bytes())
1,466✔
4302
}
4303

4304
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4305
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,175✔
4306

4,175✔
4307
        edgeInfoBytes := edgeIndex.Get(chanID)
4,175✔
4308
        if edgeInfoBytes == nil {
4,251✔
4309
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
76✔
4310
        }
76✔
4311

4312
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,099✔
4313
        return deserializeChanEdgeInfo(edgeInfoReader)
4,099✔
4314
}
4315

4316
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,731✔
4317
        var (
4,731✔
4318
                err      error
4,731✔
4319
                edgeInfo models.ChannelEdgeInfo
4,731✔
4320
        )
4,731✔
4321

4,731✔
4322
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,731✔
4323
                return models.ChannelEdgeInfo{}, err
×
4324
        }
×
4325
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,731✔
4326
                return models.ChannelEdgeInfo{}, err
×
4327
        }
×
4328
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,731✔
4329
                return models.ChannelEdgeInfo{}, err
×
4330
        }
×
4331
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,731✔
4332
                return models.ChannelEdgeInfo{}, err
×
4333
        }
×
4334

4335
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,731✔
4336
        if err != nil {
4,731✔
4337
                return models.ChannelEdgeInfo{}, err
×
4338
        }
×
4339

4340
        proof := &models.ChannelAuthProof{}
4,731✔
4341

4,731✔
4342
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,731✔
4343
        if err != nil {
4,731✔
4344
                return models.ChannelEdgeInfo{}, err
×
4345
        }
×
4346
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,731✔
4347
        if err != nil {
4,731✔
4348
                return models.ChannelEdgeInfo{}, err
×
4349
        }
×
4350
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,731✔
4351
        if err != nil {
4,731✔
4352
                return models.ChannelEdgeInfo{}, err
×
4353
        }
×
4354
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,731✔
4355
        if err != nil {
4,731✔
4356
                return models.ChannelEdgeInfo{}, err
×
4357
        }
×
4358

4359
        if !proof.IsEmpty() {
6,509✔
4360
                edgeInfo.AuthProof = proof
1,778✔
4361
        }
1,778✔
4362

4363
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,731✔
4364
        if err := readOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,731✔
4365
                return models.ChannelEdgeInfo{}, err
×
4366
        }
×
4367
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,731✔
4368
                return models.ChannelEdgeInfo{}, err
×
4369
        }
×
4370
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,731✔
4371
                return models.ChannelEdgeInfo{}, err
×
4372
        }
×
4373

4374
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,731✔
4375
                return models.ChannelEdgeInfo{}, err
×
4376
        }
×
4377

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

4390
        return edgeInfo, nil
4,731✔
4391
}
4392

4393
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4394
        from, to []byte) error {
2,628✔
4395

2,628✔
4396
        var edgeKey [33 + 8]byte
2,628✔
4397
        copy(edgeKey[:], from)
2,628✔
4398
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,628✔
4399

2,628✔
4400
        var b bytes.Buffer
2,628✔
4401
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,628✔
4402
                return err
×
4403
        }
×
4404

4405
        // Before we write out the new edge, we'll create a new entry in the
4406
        // update index in order to keep it fresh.
4407
        updateUnix := uint64(edge.LastUpdate.Unix())
2,628✔
4408
        var indexKey [8 + 8]byte
2,628✔
4409
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,628✔
4410
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,628✔
4411

2,628✔
4412
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,628✔
4413
        if err != nil {
2,628✔
4414
                return err
×
4415
        }
×
4416

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

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

4440
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
24✔
4441

24✔
4442
                var oldIndexKey [8 + 8]byte
24✔
4443
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
24✔
4444
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
24✔
4445

24✔
4446
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
24✔
4447
                        return err
×
4448
                }
×
4449
        }
4450

4451
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,628✔
4452
                return err
×
4453
        }
×
4454

4455
        updateEdgePolicyDisabledIndex(
2,628✔
4456
                edges, edge.ChannelID,
2,628✔
4457
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,628✔
4458
                edge.IsDisabled(),
2,628✔
4459
        )
2,628✔
4460

2,628✔
4461
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,628✔
4462
}
4463

4464
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4465
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4466
// one.
4467
// The direction represents the direction of the edge and disabled is used for
4468
// deciding whether to remove or add an entry to the bucket.
4469
// In general a channel is disabled if two entries for the same chanID exist
4470
// in this bucket.
4471
// Maintaining the bucket this way allows a fast retrieval of disabled
4472
// channels, for example when prune is needed.
4473
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4474
        direction bool, disabled bool) error {
2,908✔
4475

2,908✔
4476
        var disabledEdgeKey [8 + 1]byte
2,908✔
4477
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,908✔
4478
        if direction {
4,358✔
4479
                disabledEdgeKey[8] = 1
1,450✔
4480
        }
1,450✔
4481

4482
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,908✔
4483
                disabledEdgePolicyBucket,
2,908✔
4484
        )
2,908✔
4485
        if err != nil {
2,908✔
4486
                return err
×
4487
        }
×
4488

4489
        if disabled {
2,934✔
4490
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
26✔
4491
        }
26✔
4492

4493
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,882✔
4494
}
4495

4496
// putChanEdgePolicyUnknown marks the edge policy as unknown
4497
// in the edges bucket.
4498
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4499
        from []byte) error {
2,930✔
4500

2,930✔
4501
        var edgeKey [33 + 8]byte
2,930✔
4502
        copy(edgeKey[:], from)
2,930✔
4503
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,930✔
4504

2,930✔
4505
        if edges.Get(edgeKey[:]) != nil {
2,930✔
4506
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4507
                        " when there is already a policy present", channelID)
×
4508
        }
×
4509

4510
        return edges.Put(edgeKey[:], unknownPolicy)
2,930✔
4511
}
4512

4513
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4514
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,166✔
4515

8,166✔
4516
        var edgeKey [33 + 8]byte
8,166✔
4517
        copy(edgeKey[:], nodePub)
8,166✔
4518
        copy(edgeKey[33:], chanID[:])
8,166✔
4519

8,166✔
4520
        edgeBytes := edges.Get(edgeKey[:])
8,166✔
4521
        if edgeBytes == nil {
8,166✔
4522
                return nil, ErrEdgeNotFound
×
4523
        }
×
4524

4525
        // No need to deserialize unknown policy.
4526
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,541✔
4527
                return nil, nil
375✔
4528
        }
375✔
4529

4530
        edgeReader := bytes.NewReader(edgeBytes)
7,791✔
4531

7,791✔
4532
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,791✔
4533
        switch {
7,791✔
4534
        // If the db policy was missing an expected optional field, we return
4535
        // nil as if the policy was unknown.
4536
        case err == ErrEdgePolicyOptionalFieldNotFound:
1✔
4537
                return nil, nil
1✔
4538

4539
        case err != nil:
×
4540
                return nil, err
×
4541
        }
4542

4543
        return ep, nil
7,790✔
4544
}
4545

4546
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4547
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4548
        error) {
240✔
4549

240✔
4550
        edgeInfo := edgeIndex.Get(chanID)
240✔
4551
        if edgeInfo == nil {
240✔
4552
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4553
                        chanID)
×
4554
        }
×
4555

4556
        // The first node is contained within the first half of the edge
4557
        // information. We only propagate the error here and below if it's
4558
        // something other than edge non-existence.
4559
        node1Pub := edgeInfo[:33]
240✔
4560
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
240✔
4561
        if err != nil {
240✔
4562
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4563
                        node1Pub)
×
4564
        }
×
4565

4566
        // Similarly, the second node is contained within the latter
4567
        // half of the edge information.
4568
        node2Pub := edgeInfo[33:66]
240✔
4569
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
240✔
4570
        if err != nil {
240✔
4571
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4572
                        node2Pub)
×
4573
        }
×
4574

4575
        return edge1, edge2, nil
240✔
4576
}
4577

4578
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4579
        to []byte) error {
2,630✔
4580

2,630✔
4581
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,630✔
4582
        if err != nil {
2,630✔
4583
                return err
×
4584
        }
×
4585

4586
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,630✔
4587
                return err
×
4588
        }
×
4589

4590
        var scratch [8]byte
2,630✔
4591
        updateUnix := uint64(edge.LastUpdate.Unix())
2,630✔
4592
        byteOrder.PutUint64(scratch[:], updateUnix)
2,630✔
4593
        if _, err := w.Write(scratch[:]); err != nil {
2,630✔
4594
                return err
×
4595
        }
×
4596

4597
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,630✔
4598
                return err
×
4599
        }
×
4600
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,630✔
4601
                return err
×
4602
        }
×
4603
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,630✔
4604
                return err
×
4605
        }
×
4606
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,630✔
4607
                return err
×
4608
        }
×
4609
        if err := binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat)); err != nil {
2,630✔
4610
                return err
×
4611
        }
×
4612
        if err := binary.Write(w, byteOrder, uint64(edge.FeeProportionalMillionths)); err != nil {
2,630✔
4613
                return err
×
4614
        }
×
4615

4616
        if _, err := w.Write(to); err != nil {
2,630✔
4617
                return err
×
4618
        }
×
4619

4620
        // If the max_htlc field is present, we write it. To be compatible with
4621
        // older versions that wasn't aware of this field, we write it as part
4622
        // of the opaque data.
4623
        // TODO(halseth): clean up when moving to TLV.
4624
        var opaqueBuf bytes.Buffer
2,630✔
4625
        if edge.MessageFlags.HasMaxHtlc() {
4,876✔
4626
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,246✔
4627
                if err != nil {
2,246✔
4628
                        return err
×
4629
                }
×
4630
        }
4631

4632
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,630✔
4633
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4634
        }
×
4635
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,630✔
4636
                return err
×
4637
        }
×
4638

4639
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,630✔
4640
                return err
×
4641
        }
×
4642
        return nil
2,630✔
4643
}
4644

4645
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,816✔
4646
        // Deserialize the policy. Note that in case an optional field is not
7,816✔
4647
        // found, both an error and a populated policy object are returned.
7,816✔
4648
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,816✔
4649
        if deserializeErr != nil &&
7,816✔
4650
                deserializeErr != ErrEdgePolicyOptionalFieldNotFound {
7,816✔
4651

×
4652
                return nil, deserializeErr
×
4653
        }
×
4654

4655
        return edge, deserializeErr
7,816✔
4656
}
4657

4658
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4659
        error) {
8,823✔
4660

8,823✔
4661
        edge := &models.ChannelEdgePolicy{}
8,823✔
4662

8,823✔
4663
        var err error
8,823✔
4664
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,823✔
4665
        if err != nil {
8,823✔
4666
                return nil, err
×
4667
        }
×
4668

4669
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,823✔
4670
                return nil, err
×
4671
        }
×
4672

4673
        var scratch [8]byte
8,823✔
4674
        if _, err := r.Read(scratch[:]); err != nil {
8,823✔
4675
                return nil, err
×
4676
        }
×
4677
        unix := int64(byteOrder.Uint64(scratch[:]))
8,823✔
4678
        edge.LastUpdate = time.Unix(unix, 0)
8,823✔
4679

8,823✔
4680
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,823✔
4681
                return nil, err
×
4682
        }
×
4683
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,823✔
4684
                return nil, err
×
4685
        }
×
4686
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,823✔
4687
                return nil, err
×
4688
        }
×
4689

4690
        var n uint64
8,823✔
4691
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,823✔
4692
                return nil, err
×
4693
        }
×
4694
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,823✔
4695

8,823✔
4696
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,823✔
4697
                return nil, err
×
4698
        }
×
4699
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,823✔
4700

8,823✔
4701
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,823✔
4702
                return nil, err
×
4703
        }
×
4704
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,823✔
4705

8,823✔
4706
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,823✔
4707
                return nil, err
×
4708
        }
×
4709

4710
        // We'll try and see if there are any opaque bytes left, if not, then
4711
        // we'll ignore the EOF error and return the edge as is.
4712
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,823✔
4713
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,823✔
4714
        )
8,823✔
4715
        switch {
8,823✔
4716
        case err == io.ErrUnexpectedEOF:
×
4717
        case err == io.EOF:
3✔
4718
        case err != nil:
×
4719
                return nil, err
×
4720
        }
4721

4722
        // See if optional fields are present.
4723
        if edge.MessageFlags.HasMaxHtlc() {
17,266✔
4724
                // The max_htlc field should be at the beginning of the opaque
8,443✔
4725
                // bytes.
8,443✔
4726
                opq := edge.ExtraOpaqueData
8,443✔
4727

8,443✔
4728
                // If the max_htlc field is not present, it might be old data
8,443✔
4729
                // stored before this field was validated. We'll return the
8,443✔
4730
                // edge along with an error.
8,443✔
4731
                if len(opq) < 8 {
8,446✔
4732
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4733
                }
3✔
4734

4735
                maxHtlc := byteOrder.Uint64(opq[:8])
8,440✔
4736
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,440✔
4737

8,440✔
4738
                // Exclude the parsed field from the rest of the opaque data.
8,440✔
4739
                edge.ExtraOpaqueData = opq[8:]
8,440✔
4740
        }
4741

4742
        return edge, nil
8,820✔
4743
}
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