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

lightningnetwork / lnd / 12058234999

27 Nov 2024 09:06PM UTC coverage: 57.847% (-1.1%) from 58.921%
12058234999

Pull #9148

github

ProofOfKeags
lnwire: convert DynPropose and DynCommit to use typed tlv records
Pull Request #9148: DynComms [2/n]: lnwire: add authenticated wire messages for Dyn*

142 of 177 new or added lines in 4 files covered. (80.23%)

19365 existing lines in 251 files now uncovered.

100876 of 174383 relevant lines covered (57.85%)

25338.28 hits per line

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

75.48
/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,879✔
204

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

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

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

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

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

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

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

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

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

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

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

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

7,409✔
282
                        return nil
7,409✔
283
                }
7,409✔
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,851✔
319
                return nil, err
×
320
        }
×
321

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

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

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

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

400
        return nil
1,879✔
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,851✔
424

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

438
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,851✔
439
                if edgeIndex == nil {
1,851✔
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,346✔
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,851✔
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 {
736✔
523
                        directedChannel.OtherNode = e.NodeKey1Bytes
247✔
524
                }
247✔
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,848✔
721

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

730
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
5,664✔
731
                        // If this is the source key, then we skip this
3,816✔
732
                        // iteration as the value for this key is a pubKey
3,816✔
733
                        // rather than raw node information.
3,816✔
734
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
7,512✔
735
                                return nil
3,696✔
736
                        }
3,696✔
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,696✔
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) {
499✔
791
        selfPub := nodes.Get(sourceKey)
499✔
792
        if selfPub == nil {
500✔
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)
498✔
799
        if err != nil {
498✔
800
                return nil, err
×
801
        }
×
802

803
        return &node, nil
498✔
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 {
976✔
867
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
976✔
868
        if err != nil {
976✔
869
                return err
×
870
        }
×
871

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

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

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

887
// LookupAlias attempts to return the alias as advertised by the target node.
888
// TODO(roasbeef): currently assumes that aliases are unique...
889
func (c *ChannelGraph) LookupAlias(pub *btcec.PublicKey) (string, error) {
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 {
67✔
945

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

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

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

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

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

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

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

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

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

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

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

1025
        for _, f := range op {
1,678✔
UNCOV
1026
                if f == nil {
×
1027
                        return fmt.Errorf("nil scheduler option was used")
×
1028
                }
×
1029

UNCOV
1030
                f(r)
×
1031
        }
1032

1033
        return c.chanScheduler.Execute(r)
1,678✔
1034
}
1035

1036
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1037
// utilize an existing db transaction.
1038
func (c *ChannelGraph) addChannelEdge(tx kvdb.RwTx,
1039
        edge *models.ChannelEdgeInfo) error {
1,678✔
1040

1,678✔
1041
        // Construct the channel's primary key which is the 8-byte channel ID.
1,678✔
1042
        var chanKey [8]byte
1,678✔
1043
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,678✔
1044

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

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

1068
        if c.graphCache != nil {
2,738✔
1069
                c.graphCache.AddChannel(edge, nil, nil)
1,278✔
1070
        }
1,278✔
1071

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

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

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

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

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

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

210✔
1146
        var (
210✔
1147
                upd1Time time.Time
210✔
1148
                upd2Time time.Time
210✔
1149
                exists   bool
210✔
1150
                isZombie bool
210✔
1151
        )
210✔
1152

210✔
1153
        // We'll query the cache with the shared lock held to allow multiple
210✔
1154
        // readers to access values in the cache concurrently if they exist.
210✔
1155
        c.cacheMu.RLock()
210✔
1156
        if entry, ok := c.rejectCache.get(chanID); ok {
280✔
1157
                c.cacheMu.RUnlock()
70✔
1158
                upd1Time = time.Unix(entry.upd1Time, 0)
70✔
1159
                upd2Time = time.Unix(entry.upd2Time, 0)
70✔
1160
                exists, isZombie = entry.flags.unpack()
70✔
1161
                return upd1Time, upd2Time, exists, isZombie, nil
70✔
1162
        }
70✔
1163
        c.cacheMu.RUnlock()
140✔
1164

140✔
1165
        c.cacheMu.Lock()
140✔
1166
        defer c.cacheMu.Unlock()
140✔
1167

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

1178
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
270✔
1179
                edges := tx.ReadBucket(edgeBucket)
135✔
1180
                if edges == nil {
135✔
1181
                        return ErrGraphNoEdgesFound
×
1182
                }
×
1183
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
135✔
1184
                if edgeIndex == nil {
135✔
1185
                        return ErrGraphNoEdgesFound
×
1186
                }
×
1187

1188
                var channelID [8]byte
135✔
1189
                byteOrder.PutUint64(channelID[:], chanID)
135✔
1190

135✔
1191
                // If the edge doesn't exist, then we'll also check our zombie
135✔
1192
                // index.
135✔
1193
                if edgeIndex.Get(channelID[:]) == nil {
223✔
1194
                        exists = false
88✔
1195
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
88✔
1196
                        if zombieIndex != nil {
176✔
1197
                                isZombie, _, _ = isZombieEdge(
88✔
1198
                                        zombieIndex, chanID,
88✔
1199
                                )
88✔
1200
                        }
88✔
1201

1202
                        return nil
88✔
1203
                }
1204

1205
                exists = true
47✔
1206
                isZombie = false
47✔
1207

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

1216
                e1, e2, err := fetchChanEdgePolicies(
47✔
1217
                        edgeIndex, edges, channelID[:],
47✔
1218
                )
47✔
1219
                if err != nil {
47✔
1220
                        return err
×
1221
                }
×
1222

1223
                // As we may have only one of the edges populated, only set the
1224
                // update time if the edge was found in the database.
1225
                if e1 != nil {
65✔
1226
                        upd1Time = e1.LastUpdate
18✔
1227
                }
18✔
1228
                if e2 != nil {
63✔
1229
                        upd2Time = e2.LastUpdate
16✔
1230
                }
16✔
1231

1232
                return nil
47✔
1233
        }, func() {}); err != nil {
135✔
1234
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1235
        }
×
1236

1237
        c.rejectCache.insert(chanID, rejectCacheEntry{
135✔
1238
                upd1Time: upd1Time.Unix(),
135✔
1239
                upd2Time: upd2Time.Unix(),
135✔
1240
                flags:    packRejectFlags(exists, isZombie),
135✔
1241
        })
135✔
1242

135✔
1243
        return upd1Time, upd2Time, exists, isZombie, nil
135✔
1244
}
1245

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

1✔
1256
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
2✔
1257
                edges := tx.ReadWriteBucket(edgeBucket)
1✔
1258
                if edge == nil {
1✔
1259
                        return ErrEdgeNotFound
×
1260
                }
×
1261

1262
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
1✔
1263
                if edgeIndex == nil {
1✔
1264
                        return ErrEdgeNotFound
×
1265
                }
×
1266

1267
                if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo == nil {
1✔
1268
                        return ErrEdgeNotFound
×
1269
                }
×
1270

1271
                if c.graphCache != nil {
2✔
1272
                        c.graphCache.UpdateChannel(edge)
1✔
1273
                }
1✔
1274

1275
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
1✔
1276
        }, func() {})
1✔
1277
}
1278

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

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

247✔
1299
        c.cacheMu.Lock()
247✔
1300
        defer c.cacheMu.Unlock()
247✔
1301

247✔
1302
        var chansClosed []*models.ChannelEdgeInfo
247✔
1303

247✔
1304
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
494✔
1305
                // First grab the edges bucket which houses the information
247✔
1306
                // we'd like to delete
247✔
1307
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
247✔
1308
                if err != nil {
247✔
1309
                        return err
×
1310
                }
×
1311

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

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

131✔
1337
                        var opBytes bytes.Buffer
131✔
1338
                        if err := writeOutpoint(&opBytes, chanPoint); err != nil {
131✔
1339
                                return err
×
1340
                        }
×
1341

1342
                        // First attempt to see if the channel exists within
1343
                        // the database, if not, then we can exit early.
1344
                        chanID := chanIndex.Get(opBytes.Bytes())
131✔
1345
                        if chanID == nil {
239✔
1346
                                continue
108✔
1347
                        }
1348

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

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

1369
                        chansClosed = append(chansClosed, &edgeInfo)
23✔
1370
                }
1371

1372
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
247✔
1373
                if err != nil {
247✔
1374
                        return err
×
1375
                }
×
1376

1377
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
247✔
1378
                if err != nil {
247✔
1379
                        return err
×
1380
                }
×
1381

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

247✔
1388
                var newTip [pruneTipBytes]byte
247✔
1389
                copy(newTip[:], blockHash[:])
247✔
1390

247✔
1391
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
247✔
1392
                if err != nil {
247✔
1393
                        return err
×
1394
                }
×
1395

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

1407
        for _, channel := range chansClosed {
270✔
1408
                c.rejectCache.remove(channel.ChannelID)
23✔
1409
                c.chanCache.remove(channel.ChannelID)
23✔
1410
        }
23✔
1411

1412
        if c.graphCache != nil {
494✔
1413
                log.Debugf("Pruned graph, cache now has %s",
247✔
1414
                        c.graphCache.Stats())
247✔
1415
        }
247✔
1416

1417
        return chansClosed, nil
247✔
1418
}
1419

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

1439
                return c.pruneGraphNodes(nodes, edgeIndex)
24✔
1440
        }, func() {})
24✔
1441
}
1442

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

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

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

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

1470
                var nodePub [33]byte
515✔
1471
                copy(nodePub[:], pubKey)
515✔
1472
                nodeRefCounts[nodePub] = 0
515✔
1473

515✔
1474
                return nil
515✔
1475
        })
1476
        if err != nil {
271✔
1477
                return err
×
1478
        }
×
1479

1480
        // To ensure we never delete the source node, we'll start off by
1481
        // bumping its ref count to 1.
1482
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
271✔
1483

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

189✔
1495
                // With the nodes extracted, we'll increase the ref count of
189✔
1496
                // each of the nodes.
189✔
1497
                nodeRefCounts[node1]++
189✔
1498
                nodeRefCounts[node2]++
189✔
1499

189✔
1500
                return nil
189✔
1501
        })
189✔
1502
        if err != nil {
271✔
1503
                return err
×
1504
        }
×
1505

1506
        // Finally, we'll make a second pass over the set of nodes, and delete
1507
        // any nodes that have a ref count of zero.
1508
        var numNodesPruned int
271✔
1509
        for nodePubKey, refCount := range nodeRefCounts {
786✔
1510
                // If the ref count of the node isn't zero, then we can safely
515✔
1511
                // skip it as it still has edges to or from it within the
515✔
1512
                // graph.
515✔
1513
                if refCount != 0 {
966✔
1514
                        continue
451✔
1515
                }
1516

1517
                if c.graphCache != nil {
128✔
1518
                        c.graphCache.RemoveNode(nodePubKey)
64✔
1519
                }
64✔
1520

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

×
1527
                                log.Warnf("Unable to prune node %x from the "+
×
1528
                                        "graph: %v", nodePubKey, err)
×
1529
                                continue
×
1530
                        }
1531

1532
                        return err
×
1533
                }
1534

1535
                log.Infof("Pruned unconnected node %x from channel graph",
64✔
1536
                        nodePubKey[:])
64✔
1537

64✔
1538
                numNodesPruned++
64✔
1539
        }
1540

1541
        if numNodesPruned > 0 {
319✔
1542
                log.Infof("Pruned %v unconnected nodes from the channel graph",
48✔
1543
                        numNodesPruned)
48✔
1544
        }
48✔
1545

1546
        return nil
271✔
1547
}
1548

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

162✔
1559
        // Every channel having a ShortChannelID starting at 'height'
162✔
1560
        // will no longer be confirmed.
162✔
1561
        startShortChanID := lnwire.ShortChannelID{
162✔
1562
                BlockHeight: height,
162✔
1563
        }
162✔
1564

162✔
1565
        // Delete everything after this height from the db up until the
162✔
1566
        // SCID alias range.
162✔
1567
        endShortChanID := aliasmgr.StartingAlias
162✔
1568

162✔
1569
        // The block height will be the 3 first bytes of the channel IDs.
162✔
1570
        var chanIDStart [8]byte
162✔
1571
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
162✔
1572
        var chanIDEnd [8]byte
162✔
1573
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
162✔
1574

162✔
1575
        c.cacheMu.Lock()
162✔
1576
        defer c.cacheMu.Unlock()
162✔
1577

162✔
1578
        // Keep track of the channels that are removed from the graph.
162✔
1579
        var removedChans []*models.ChannelEdgeInfo
162✔
1580

162✔
1581
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
324✔
1582
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
162✔
1583
                if err != nil {
162✔
1584
                        return err
×
1585
                }
×
1586
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
162✔
1587
                if err != nil {
162✔
1588
                        return err
×
1589
                }
×
1590
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
162✔
1591
                if err != nil {
162✔
1592
                        return err
×
1593
                }
×
1594
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
162✔
1595
                if err != nil {
162✔
1596
                        return err
×
1597
                }
×
1598

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

162✔
1608
                //nolint:lll
162✔
1609
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
162✔
1610
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
247✔
1611
                        edgeInfoReader := bytes.NewReader(v)
85✔
1612
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
85✔
1613
                        if err != nil {
85✔
1614
                                return err
×
1615
                        }
×
1616

1617
                        keys = append(keys, k)
85✔
1618
                        removedChans = append(removedChans, &edgeInfo)
85✔
1619
                }
1620

1621
                for _, k := range keys {
247✔
1622
                        err = c.delChannelEdgeUnsafe(
85✔
1623
                                edges, edgeIndex, chanIndex, zombieIndex,
85✔
1624
                                k, false, false,
85✔
1625
                        )
85✔
1626
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
85✔
1627
                                return err
×
1628
                        }
×
1629
                }
1630

1631
                // Delete all the entries in the prune log having a height
1632
                // greater or equal to the block disconnected.
1633
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
162✔
1634
                if err != nil {
162✔
1635
                        return err
×
1636
                }
×
1637

1638
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
162✔
1639
                if err != nil {
162✔
1640
                        return err
×
1641
                }
×
1642

1643
                var pruneKeyStart [4]byte
162✔
1644
                byteOrder.PutUint32(pruneKeyStart[:], height)
162✔
1645

162✔
1646
                var pruneKeyEnd [4]byte
162✔
1647
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
162✔
1648

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

101✔
1656
                        pruneKeys = append(pruneKeys, k)
101✔
1657
                }
101✔
1658

1659
                for _, k := range pruneKeys {
263✔
1660
                        if err := pruneBucket.Delete(k); err != nil {
101✔
1661
                                return err
×
1662
                        }
×
1663
                }
1664

1665
                return nil
162✔
1666
        }, func() {
162✔
1667
                removedChans = nil
162✔
1668
        }); err != nil {
162✔
1669
                return nil, err
×
1670
        }
×
1671

1672
        for _, channel := range removedChans {
247✔
1673
                c.rejectCache.remove(channel.ChannelID)
85✔
1674
                c.chanCache.remove(channel.ChannelID)
85✔
1675
        }
85✔
1676

1677
        return removedChans, nil
162✔
1678
}
1679

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

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

1700
                pruneCursor := pruneBucket.ReadCursor()
55✔
1701

55✔
1702
                // The prune key with the largest block height will be our
55✔
1703
                // prune tip.
55✔
1704
                k, v := pruneCursor.Last()
55✔
1705
                if k == nil {
74✔
1706
                        return ErrGraphNeverPruned
19✔
1707
                }
19✔
1708

1709
                // Once we have the prune tip, the value will be the block hash,
1710
                // and the key the block height.
1711
                copy(tipHash[:], v[:])
36✔
1712
                tipHeight = byteOrder.Uint32(k[:])
36✔
1713

36✔
1714
                return nil
36✔
1715
        }, func() {})
55✔
1716
        if err != nil {
74✔
1717
                return nil, 0, err
19✔
1718
        }
19✔
1719

1720
        return &tipHash, tipHeight, nil
36✔
1721
}
1722

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

147✔
1734
        // TODO(roasbeef): possibly delete from node bucket if node has no more
147✔
1735
        // channels
147✔
1736
        // TODO(roasbeef): don't delete both edges?
147✔
1737

147✔
1738
        c.cacheMu.Lock()
147✔
1739
        defer c.cacheMu.Unlock()
147✔
1740

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

1763
                var rawChanID [8]byte
147✔
1764
                for _, chanID := range chanIDs {
233✔
1765
                        byteOrder.PutUint64(rawChanID[:], chanID)
86✔
1766
                        err := c.delChannelEdgeUnsafe(
86✔
1767
                                edges, edgeIndex, chanIndex, zombieIndex,
86✔
1768
                                rawChanID[:], markZombie, strictZombiePruning,
86✔
1769
                        )
86✔
1770
                        if err != nil {
146✔
1771
                                return err
60✔
1772
                        }
60✔
1773
                }
1774

1775
                return nil
87✔
1776
        }, func() {})
147✔
1777
        if err != nil {
207✔
1778
                return err
60✔
1779
        }
60✔
1780

1781
        for _, chanID := range chanIDs {
113✔
1782
                c.rejectCache.remove(chanID)
26✔
1783
                c.chanCache.remove(chanID)
26✔
1784
        }
26✔
1785

1786
        return nil
87✔
1787
}
1788

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

1804
        return chanID, nil
1✔
1805
}
1806

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

1814
        edges := tx.ReadBucket(edgeBucket)
1✔
1815
        if edges == nil {
1✔
1816
                return 0, ErrGraphNoEdgesFound
×
1817
        }
×
1818
        chanIndex := edges.NestedReadBucket(channelPointBucket)
1✔
1819
        if chanIndex == nil {
1✔
1820
                return 0, ErrGraphNoEdgesFound
×
1821
        }
×
1822

1823
        chanIDBytes := chanIndex.Get(b.Bytes())
1✔
1824
        if chanIDBytes == nil {
1✔
UNCOV
1825
                return 0, ErrEdgeNotFound
×
UNCOV
1826
        }
×
1827

1828
        chanID := byteOrder.Uint64(chanIDBytes)
1✔
1829

1✔
1830
        return chanID, nil
1✔
1831
}
1832

1833
// TODO(roasbeef): allow updates to use Batch?
1834

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

3✔
1841
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1842
                edges := tx.ReadBucket(edgeBucket)
3✔
1843
                if edges == nil {
3✔
1844
                        return ErrGraphNoEdgesFound
×
1845
                }
×
1846
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1847
                if edgeIndex == nil {
3✔
1848
                        return ErrGraphNoEdgesFound
×
1849
                }
×
1850

1851
                // In order to find the highest chan ID, we'll fetch a cursor
1852
                // and use that to seek to the "end" of our known rage.
1853
                cidCursor := edgeIndex.ReadCursor()
3✔
1854

3✔
1855
                lastChanID, _ := cidCursor.Last()
3✔
1856

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

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

1874
        return cid, nil
3✔
1875
}
1876

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

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

1888
        // Policy2 points to the "second" edge policy of the channel containing
1889
        // the dynamic information required to properly route through the edge.
1890
        Policy2 *models.ChannelEdgePolicy
1891

1892
        // Node1 is "node 1" in the channel. This is the node that would have
1893
        // produced Policy1 if it exists.
1894
        Node1 *LightningNode
1895

1896
        // Node2 is "node 2" in the channel. This is the node that would have
1897
        // produced Policy2 if it exists.
1898
        Node2 *LightningNode
1899
}
1900

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

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

135✔
1913
        c.cacheMu.Lock()
135✔
1914
        defer c.cacheMu.Unlock()
135✔
1915

135✔
1916
        var hits int
135✔
1917
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
270✔
1918
                edges := tx.ReadBucket(edgeBucket)
135✔
1919
                if edges == nil {
135✔
1920
                        return ErrGraphNoEdgesFound
×
1921
                }
×
1922
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
135✔
1923
                if edgeIndex == nil {
135✔
1924
                        return ErrGraphNoEdgesFound
×
1925
                }
×
1926
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
135✔
1927
                if edgeUpdateIndex == nil {
135✔
1928
                        return ErrGraphNoEdgesFound
×
1929
                }
×
1930

1931
                nodes := tx.ReadBucket(nodeBucket)
135✔
1932
                if nodes == nil {
135✔
1933
                        return ErrGraphNodesNotFound
×
1934
                }
×
1935

1936
                // We'll now obtain a cursor to perform a range query within
1937
                // the index to find all channels within the horizon.
1938
                updateCursor := edgeUpdateIndex.ReadCursor()
135✔
1939

135✔
1940
                var startTimeBytes, endTimeBytes [8 + 8]byte
135✔
1941
                byteOrder.PutUint64(
135✔
1942
                        startTimeBytes[:8], uint64(startTime.Unix()),
135✔
1943
                )
135✔
1944
                byteOrder.PutUint64(
135✔
1945
                        endTimeBytes[:8], uint64(endTime.Unix()),
135✔
1946
                )
135✔
1947

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

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

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

1966
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
36✔
1967
                                hits++
9✔
1968
                                edgesSeen[chanIDInt] = struct{}{}
9✔
1969
                                edgesInHorizon = append(edgesInHorizon, channel)
9✔
1970
                                continue
9✔
1971
                        }
1972

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

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

1993
                        node1, err := fetchLightningNode(
18✔
1994
                                nodes, edgeInfo.NodeKey1Bytes[:],
18✔
1995
                        )
18✔
1996
                        if err != nil {
18✔
1997
                                return err
×
1998
                        }
×
1999

2000
                        node2, err := fetchLightningNode(
18✔
2001
                                nodes, edgeInfo.NodeKey2Bytes[:],
18✔
2002
                        )
18✔
2003
                        if err != nil {
18✔
2004
                                return err
×
2005
                        }
×
2006

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

2021
                return nil
135✔
2022
        }, func() {
135✔
2023
                edgesSeen = make(map[uint64]struct{})
135✔
2024
                edgesToCache = make(map[uint64]ChannelEdge)
135✔
2025
                edgesInHorizon = nil
135✔
2026
        })
135✔
2027
        switch {
135✔
2028
        case err == ErrGraphNoEdgesFound:
×
2029
                fallthrough
×
2030
        case err == ErrGraphNodesNotFound:
×
2031
                break
×
2032

2033
        case err != nil:
×
2034
                return nil, err
×
2035
        }
2036

2037
        // Insert any edges loaded from disk into the cache.
2038
        for chanid, channel := range edgesToCache {
153✔
2039
                c.chanCache.insert(chanid, channel)
18✔
2040
        }
18✔
2041

2042
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
135✔
2043
                float64(hits)/float64(len(edgesInHorizon)), hits,
135✔
2044
                len(edgesInHorizon))
135✔
2045

135✔
2046
        return edgesInHorizon, nil
135✔
2047
}
2048

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

8✔
2056
        var nodesInHorizon []LightningNode
8✔
2057

8✔
2058
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
16✔
2059
                nodes := tx.ReadBucket(nodeBucket)
8✔
2060
                if nodes == nil {
8✔
2061
                        return ErrGraphNodesNotFound
×
2062
                }
×
2063

2064
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
8✔
2065
                if nodeUpdateIndex == nil {
8✔
2066
                        return ErrGraphNodesNotFound
×
2067
                }
×
2068

2069
                // We'll now obtain a cursor to perform a range query within
2070
                // the index to find all node announcements within the horizon.
2071
                updateCursor := nodeUpdateIndex.ReadCursor()
8✔
2072

8✔
2073
                var startTimeBytes, endTimeBytes [8 + 33]byte
8✔
2074
                byteOrder.PutUint64(
8✔
2075
                        startTimeBytes[:8], uint64(startTime.Unix()),
8✔
2076
                )
8✔
2077
                byteOrder.PutUint64(
8✔
2078
                        endTimeBytes[:8], uint64(endTime.Unix()),
8✔
2079
                )
8✔
2080

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

29✔
2087
                        nodePub := indexKey[8:]
29✔
2088
                        node, err := fetchLightningNode(nodes, nodePub)
29✔
2089
                        if err != nil {
29✔
2090
                                return err
×
2091
                        }
×
2092

2093
                        nodesInHorizon = append(nodesInHorizon, node)
29✔
2094
                }
2095

2096
                return nil
8✔
2097
        }, func() {
8✔
2098
                nodesInHorizon = nil
8✔
2099
        })
8✔
2100
        switch {
8✔
2101
        case err == ErrGraphNoEdgesFound:
×
2102
                fallthrough
×
2103
        case err == ErrGraphNodesNotFound:
×
2104
                break
×
2105

2106
        case err != nil:
×
2107
                return nil, err
×
2108
        }
2109

2110
        return nodesInHorizon, nil
8✔
2111
}
2112

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

129✔
2121
        var newChanIDs []uint64
129✔
2122

129✔
2123
        c.cacheMu.Lock()
129✔
2124
        defer c.cacheMu.Unlock()
129✔
2125

129✔
2126
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
258✔
2127
                edges := tx.ReadBucket(edgeBucket)
129✔
2128
                if edges == nil {
129✔
2129
                        return ErrGraphNoEdgesFound
×
2130
                }
×
2131
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
129✔
2132
                if edgeIndex == nil {
129✔
2133
                        return ErrGraphNoEdgesFound
×
2134
                }
×
2135

2136
                // Fetch the zombie index, it may not exist if no edges have
2137
                // ever been marked as zombies. If the index has been
2138
                // initialized, we will use it later to skip known zombie edges.
2139
                zombieIndex := edges.NestedReadBucket(zombieBucket)
129✔
2140

129✔
2141
                // We'll run through the set of chanIDs and collate only the
129✔
2142
                // set of channel that are unable to be found within our db.
129✔
2143
                var cidBytes [8]byte
129✔
2144
                for _, info := range chansInfo {
239✔
2145
                        scid := info.ShortChannelID.ToUint64()
110✔
2146
                        byteOrder.PutUint64(cidBytes[:], scid)
110✔
2147

110✔
2148
                        // If the edge is already known, skip it.
110✔
2149
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
124✔
2150
                                continue
14✔
2151
                        }
2152

2153
                        // If the edge is a known zombie, skip it.
2154
                        if zombieIndex != nil {
192✔
2155
                                isZombie, _, _ := isZombieEdge(
96✔
2156
                                        zombieIndex, scid,
96✔
2157
                                )
96✔
2158

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

96✔
2179
                                switch {
96✔
2180
                                // If the edge is a known zombie and if we
2181
                                // would still consider it a zombie given the
2182
                                // latest update timestamps, then we skip this
2183
                                // channel.
2184
                                case isZombie && isStillZombie:
30✔
2185
                                        continue
30✔
2186

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

2200
                        newChanIDs = append(newChanIDs, scid)
66✔
2201
                }
2202

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

2216
                return ogChanIDs, nil
×
2217

2218
        case err != nil:
×
2219
                return nil, err
×
2220
        }
2221

2222
        return newChanIDs, nil
129✔
2223
}
2224

2225
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2226
// latest received channel updates for the channel.
2227
type ChannelUpdateInfo struct {
2228
        // ShortChannelID is the SCID identifier of the channel.
2229
        ShortChannelID lnwire.ShortChannelID
2230

2231
        // Node1UpdateTimestamp is the timestamp of the latest received update
2232
        // from the node 1 channel peer. This will be set to zero time if no
2233
        // update has yet been received from this node.
2234
        Node1UpdateTimestamp time.Time
2235

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

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

218✔
2248
        chanInfo := ChannelUpdateInfo{
218✔
2249
                ShortChannelID:       scid,
218✔
2250
                Node1UpdateTimestamp: node1Timestamp,
218✔
2251
                Node2UpdateTimestamp: node2Timestamp,
218✔
2252
        }
218✔
2253

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

2258
        if node2Timestamp.IsZero() {
426✔
2259
                chanInfo.Node2UpdateTimestamp = time.Unix(0, 0)
208✔
2260
        }
208✔
2261

2262
        return chanInfo
218✔
2263
}
2264

2265
// BlockChannelRange represents a range of channels for a given block height.
2266
type BlockChannelRange struct {
2267
        // Height is the height of the block all of the channels below were
2268
        // included in.
2269
        Height uint32
2270

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

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

11✔
2288
        startChanID := &lnwire.ShortChannelID{
11✔
2289
                BlockHeight: startHeight,
11✔
2290
        }
11✔
2291

11✔
2292
        endChanID := lnwire.ShortChannelID{
11✔
2293
                BlockHeight: endHeight,
11✔
2294
                TxIndex:     math.MaxUint32 & 0x00ffffff,
11✔
2295
                TxPosition:  math.MaxUint16,
11✔
2296
        }
11✔
2297

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

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

2316
                cursor := edgeIndex.ReadCursor()
11✔
2317

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

2329
                        if edgeInfo.AuthProof == nil {
44✔
UNCOV
2330
                                continue
×
2331
                        }
2332

2333
                        // This channel ID rests within the target range, so
2334
                        // we'll add it to our returned set.
2335
                        rawCid := byteOrder.Uint64(k)
44✔
2336
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
44✔
2337

44✔
2338
                        chanInfo := NewChannelUpdateInfo(
44✔
2339
                                cid, time.Time{}, time.Time{},
44✔
2340
                        )
44✔
2341

44✔
2342
                        if !withTimestamps {
66✔
2343
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2344
                                        channelsPerBlock[cid.BlockHeight],
22✔
2345
                                        chanInfo,
22✔
2346
                                )
22✔
2347

22✔
2348
                                continue
22✔
2349
                        }
2350

2351
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
22✔
2352

22✔
2353
                        rawPolicy := edges.Get(node1Key)
22✔
2354
                        if len(rawPolicy) != 0 {
28✔
2355
                                r := bytes.NewReader(rawPolicy)
6✔
2356

6✔
2357
                                edge, err := deserializeChanEdgePolicyRaw(r)
6✔
2358
                                if err != nil && !errors.Is(
6✔
2359
                                        err, ErrEdgePolicyOptionalFieldNotFound,
6✔
2360
                                ) {
6✔
2361

×
2362
                                        return err
×
2363
                                }
×
2364

2365
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
6✔
2366
                        }
2367

2368
                        rawPolicy = edges.Get(node2Key)
22✔
2369
                        if len(rawPolicy) != 0 {
33✔
2370
                                r := bytes.NewReader(rawPolicy)
11✔
2371

11✔
2372
                                edge, err := deserializeChanEdgePolicyRaw(r)
11✔
2373
                                if err != nil && !errors.Is(
11✔
2374
                                        err, ErrEdgePolicyOptionalFieldNotFound,
11✔
2375
                                ) {
11✔
2376

×
2377
                                        return err
×
2378
                                }
×
2379

2380
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
11✔
2381
                        }
2382

2383
                        channelsPerBlock[cid.BlockHeight] = append(
22✔
2384
                                channelsPerBlock[cid.BlockHeight], chanInfo,
22✔
2385
                        )
22✔
2386
                }
2387

2388
                return nil
11✔
2389
        }, func() {
11✔
2390
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
11✔
2391
        })
11✔
2392

2393
        switch {
11✔
2394
        // If we don't know of any channels yet, then there's nothing to
2395
        // filter, so we'll return an empty slice.
2396
        case err == ErrGraphNoEdgesFound || len(channelsPerBlock) == 0:
3✔
2397
                return nil, nil
3✔
2398

2399
        case err != nil:
×
2400
                return nil, err
×
2401
        }
2402

2403
        // Return the channel ranges in ascending block height order.
2404
        blocks := make([]uint32, 0, len(channelsPerBlock))
8✔
2405
        for block := range channelsPerBlock {
30✔
2406
                blocks = append(blocks, block)
22✔
2407
        }
22✔
2408
        sort.Slice(blocks, func(i, j int) bool {
27✔
2409
                return blocks[i] < blocks[j]
19✔
2410
        })
19✔
2411

2412
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
8✔
2413
        for _, block := range blocks {
30✔
2414
                channelRanges = append(channelRanges, BlockChannelRange{
22✔
2415
                        Height:   block,
22✔
2416
                        Channels: channelsPerBlock[block],
22✔
2417
                })
22✔
2418
        }
22✔
2419

2420
        return channelRanges, nil
8✔
2421
}
2422

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

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

26✔
2444
        var (
26✔
2445
                chanEdges []ChannelEdge
26✔
2446
                cidBytes  [8]byte
26✔
2447
        )
26✔
2448

26✔
2449
        fetchChanInfos := func(tx kvdb.RTx) error {
52✔
2450
                edges := tx.ReadBucket(edgeBucket)
26✔
2451
                if edges == nil {
26✔
2452
                        return ErrGraphNoEdgesFound
×
2453
                }
×
2454
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
26✔
2455
                if edgeIndex == nil {
26✔
2456
                        return ErrGraphNoEdgesFound
×
2457
                }
×
2458
                nodes := tx.ReadBucket(nodeBucket)
26✔
2459
                if nodes == nil {
26✔
2460
                        return ErrGraphNotFound
×
2461
                }
×
2462

2463
                for _, cid := range chanIDs {
59✔
2464
                        byteOrder.PutUint64(cidBytes[:], cid)
33✔
2465

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

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

2488
                        node1, err := fetchLightningNode(
8✔
2489
                                nodes, edgeInfo.NodeKey1Bytes[:],
8✔
2490
                        )
8✔
2491
                        if err != nil {
8✔
2492
                                return err
×
2493
                        }
×
2494

2495
                        node2, err := fetchLightningNode(
8✔
2496
                                nodes, edgeInfo.NodeKey2Bytes[:],
8✔
2497
                        )
8✔
2498
                        if err != nil {
8✔
2499
                                return err
×
2500
                        }
×
2501

2502
                        chanEdges = append(chanEdges, ChannelEdge{
8✔
2503
                                Info:    &edgeInfo,
8✔
2504
                                Policy1: edge1,
8✔
2505
                                Policy2: edge2,
8✔
2506
                                Node1:   &node1,
8✔
2507
                                Node2:   &node2,
8✔
2508
                        })
8✔
2509
                }
2510
                return nil
26✔
2511
        }
2512

2513
        if tx == nil {
30✔
2514
                err := kvdb.View(c.db, fetchChanInfos, func() {
8✔
2515
                        chanEdges = nil
4✔
2516
                })
4✔
2517
                if err != nil {
4✔
2518
                        return nil, err
×
2519
                }
×
2520

2521
                return chanEdges, nil
4✔
2522
        }
2523

2524
        err := fetchChanInfos(tx)
22✔
2525
        if err != nil {
22✔
2526
                return nil, err
×
2527
        }
×
2528

2529
        return chanEdges, nil
22✔
2530
}
2531

2532
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2533
        edge1, edge2 *models.ChannelEdgePolicy) error {
134✔
2534

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

2543
        // Now that we have the bucket, we'll attempt to construct a template
2544
        // for the index key: updateTime || chanid.
2545
        var indexKey [8 + 8]byte
134✔
2546
        byteOrder.PutUint64(indexKey[8:], chanID)
134✔
2547

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

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

2567
        return nil
134✔
2568
}
2569

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

194✔
2581
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
194✔
2582
        if err != nil {
254✔
2583
                return err
60✔
2584
        }
60✔
2585

2586
        if c.graphCache != nil {
268✔
2587
                c.graphCache.RemoveChannel(
134✔
2588
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
134✔
2589
                        edgeInfo.ChannelID,
134✔
2590
                )
134✔
2591
        }
134✔
2592

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

2606
        // The edge key is of the format pubKey || chanID. First we construct
2607
        // the latter half, populating the channel ID.
2608
        var edgeKey [33 + 8]byte
134✔
2609
        copy(edgeKey[33:], chanID)
134✔
2610

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

2627
        // As part of deleting the edge we also remove all disabled entries
2628
        // from the edgePolicyDisabledIndex bucket. We do that for both directions.
2629
        updateEdgePolicyDisabledIndex(edges, cid, false, false)
134✔
2630
        updateEdgePolicyDisabledIndex(edges, cid, true, false)
134✔
2631

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

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

2652
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
23✔
2653
        if strictZombie {
26✔
2654
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2655
        }
3✔
2656

2657
        return markEdgeZombie(
23✔
2658
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
23✔
2659
        )
23✔
2660
}
2661

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

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

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

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

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

2,631✔
2712
        var (
2,631✔
2713
                isUpdate1    bool
2,631✔
2714
                edgeNotFound bool
2,631✔
2715
        )
2,631✔
2716

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

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

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

2750
        for _, f := range op {
2,631✔
UNCOV
2751
                f(r)
×
UNCOV
2752
        }
×
2753

2754
        return c.chanScheduler.Execute(r)
2,631✔
2755
}
2756

2757
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2758
        isUpdate1 bool) {
2,628✔
2759

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

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

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

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

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

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

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

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

2836
        var (
2,628✔
2837
                fromNodePubKey route.Vertex
2,628✔
2838
                toNodePubKey   route.Vertex
2,628✔
2839
        )
2,628✔
2840
        copy(fromNodePubKey[:], fromNode)
2,628✔
2841
        copy(toNodePubKey[:], toNode)
2,628✔
2842

2,628✔
2843
        if graphCache != nil {
4,886✔
2844
                graphCache.UpdatePolicy(
2,258✔
2845
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,258✔
2846
                )
2,258✔
2847
        }
2,258✔
2848

2849
        return isUpdate1, nil
2,628✔
2850
}
2851

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

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

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

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

2873
        // Color is the selected color for the node.
2874
        Color color.RGBA
2875

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

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

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

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

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

2898
        // TODO(roasbeef): add update method and fetch?
2899
}
2900

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

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

977✔
2917
        return key, nil
977✔
2918
}
2919

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

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

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

14✔
2940
        if !l.HaveNodeAnnouncement {
14✔
UNCOV
2941
                return nil, fmt.Errorf("node does not have node announcement")
×
UNCOV
2942
        }
×
2943

2944
        alias, err := lnwire.NewNodeAlias(l.Alias)
14✔
2945
        if err != nil {
14✔
2946
                return nil, err
×
2947
        }
×
2948

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

14✔
2959
        if !signed {
14✔
UNCOV
2960
                return nodeAnn, nil
×
UNCOV
2961
        }
×
2962

2963
        sig, err := lnwire.NewSigFromECDSARawSignature(l.AuthSigBytes)
14✔
2964
        if err != nil {
14✔
2965
                return nil, err
×
2966
        }
×
2967

2968
        nodeAnn.Signature = sig
14✔
2969

14✔
2970
        return nodeAnn, nil
14✔
2971
}
2972

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

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

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

3✔
2996
                        nodeIsPublic = true
3✔
2997
                        return errDone
3✔
2998
                }
3✔
2999

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

3007
                // Otherwise, we'll continue our search.
3008
                return nil
1✔
3009
        })
3010
        if err != nil && err != errDone {
13✔
3011
                return false, err
×
3012
        }
×
3013

3014
        return nodeIsPublic, nil
13✔
3015
}
3016

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

2,944✔
3024
        return c.fetchLightningNode(tx, nodePub)
2,944✔
3025
}
2,944✔
3026

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

826✔
3033
        return c.fetchLightningNode(nil, nodePub)
826✔
3034
}
826✔
3035

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

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

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

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

3067
                node = &n
3,762✔
3068

3,762✔
3069
                return nil
3,762✔
3070
        }
3071

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

3082
                return node, nil
818✔
3083
        }
3084

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

3090
        return node, nil
2,944✔
3091
}
3092

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

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

725✔
3104
        return &graphCacheNode{
725✔
3105
                pubKeyBytes: pubKey,
725✔
3106
                features:    features,
725✔
3107
        }
725✔
3108
}
725✔
3109

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

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

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

625✔
3132
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
625✔
3133
}
625✔
3134

3135
var _ GraphCacheNode = (*graphCacheNode)(nil)
3136

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

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

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

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

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

3184
        return updateTime, exists, nil
16✔
3185
}
3186

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

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

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

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

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

3237
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,843✔
3238
                        if err != nil {
3,843✔
3239
                                return err
×
3240
                        }
×
3241

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

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

3256
                return nil
1,857✔
3257
        }
3258

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

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

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

6✔
3282
        return nodeTraversal(nil, nodePub[:], c.db, cb)
6✔
3283
}
6✔
3284

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

998✔
3303
        return nodeTraversal(tx, nodePub[:], c.db, cb)
998✔
3304
}
998✔
3305

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

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

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

UNCOV
3334
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
×
UNCOV
3335
                if err != nil {
×
3336
                        return err
×
3337
                }
×
3338

UNCOV
3339
                targetNode = &node
×
UNCOV
3340

×
UNCOV
3341
                return nil
×
3342
        }
3343

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

UNCOV
3353
        return targetNode, err
×
3354
}
3355

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

22✔
3365
        copy(node1Key[:], info.NodeKey1Bytes[:])
22✔
3366
        copy(node2Key[:], info.NodeKey2Bytes[:])
22✔
3367

22✔
3368
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
22✔
3369
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
22✔
3370

22✔
3371
        return node1Key[:], node2Key[:]
22✔
3372
}
22✔
3373

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

11✔
3383
        var (
11✔
3384
                edgeInfo *models.ChannelEdgeInfo
11✔
3385
                policy1  *models.ChannelEdgePolicy
11✔
3386
                policy2  *models.ChannelEdgePolicy
11✔
3387
        )
11✔
3388

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

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

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

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

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

3440
                policy1 = e1
1✔
3441
                policy2 = e2
1✔
3442
                return nil
1✔
3443
        }, func() {
11✔
3444
                edgeInfo = nil
11✔
3445
                policy1 = nil
11✔
3446
                policy2 = nil
11✔
3447
        })
11✔
3448
        if err != nil {
21✔
3449
                return nil, nil, nil, err
10✔
3450
        }
10✔
3451

3452
        return edgeInfo, policy1, policy2, nil
1✔
3453
}
3454

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

25✔
3468
        var (
25✔
3469
                edgeInfo  *models.ChannelEdgeInfo
25✔
3470
                policy1   *models.ChannelEdgePolicy
25✔
3471
                policy2   *models.ChannelEdgePolicy
25✔
3472
                channelID [8]byte
25✔
3473
        )
25✔
3474

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

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

3495
                byteOrder.PutUint64(channelID[:], chanID)
25✔
3496

25✔
3497
                // Now, attempt to fetch edge.
25✔
3498
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
25✔
3499

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

3511
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
1✔
3512
                                zombieIndex, chanID,
1✔
3513
                        )
1✔
3514
                        if !isZombie {
1✔
UNCOV
3515
                                return ErrEdgeNotFound
×
UNCOV
3516
                        }
×
3517

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

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

3534
                edgeInfo = &edge
24✔
3535

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

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

3560
        return edgeInfo, policy1, policy2, nil
24✔
3561
}
3562

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

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

3591
        return nodeIsPublic, nil
13✔
3592
}
3593

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

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

46✔
3611
        return bldr.Script()
46✔
3612
}
3613

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

3622
        // OutPoint is the outpoint of the target channel.
3623
        OutPoint wire.OutPoint
3624
}
3625

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

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

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

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

3667
                        edgeInfo, err := fetchChanEdgeInfo(
42✔
3668
                                edgeIndex, chanID,
42✔
3669
                        )
42✔
3670
                        if err != nil {
42✔
3671
                                return err
×
3672
                        }
×
3673

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

3682
                        edgePoints = append(edgePoints, EdgePoint{
42✔
3683
                                FundingPkScript: pkScript,
42✔
3684
                                OutPoint:        chanPoint,
42✔
3685
                        })
42✔
3686

42✔
3687
                        return nil
42✔
3688
                })
3689
        }, func() {
23✔
3690
                edgePoints = nil
23✔
3691
        }); err != nil {
23✔
3692
                return nil, err
×
3693
        }
×
3694

3695
        return edgePoints, nil
23✔
3696
}
3697

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

123✔
3704
        c.cacheMu.Lock()
123✔
3705
        defer c.cacheMu.Unlock()
123✔
3706

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

3718
                if c.graphCache != nil {
246✔
3719
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
123✔
3720
                }
123✔
3721

3722
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
123✔
3723
        })
3724
        if err != nil {
123✔
3725
                return err
×
3726
        }
×
3727

3728
        c.rejectCache.remove(chanID)
123✔
3729
        c.chanCache.remove(chanID)
123✔
3730

123✔
3731
        return nil
123✔
3732
}
3733

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

146✔
3740
        var k [8]byte
146✔
3741
        byteOrder.PutUint64(k[:], chanID)
146✔
3742

146✔
3743
        var v [66]byte
146✔
3744
        copy(v[:33], pubKey1[:])
146✔
3745
        copy(v[33:], pubKey2[:])
146✔
3746

146✔
3747
        return zombieIndex.Put(k[:], v[:])
146✔
3748
}
146✔
3749

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

2✔
3755
        return c.markEdgeLiveUnsafe(nil, chanID)
2✔
3756
}
2✔
3757

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

3775
                var k [8]byte
24✔
3776
                byteOrder.PutUint64(k[:], chanID)
24✔
3777

24✔
3778
                if len(zombieIndex.Get(k[:])) == 0 {
25✔
3779
                        return ErrZombieEdgeNotFound
1✔
3780
                }
1✔
3781

3782
                return zombieIndex.Delete(k[:])
23✔
3783
        }
3784

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

3797
        c.rejectCache.remove(chanID)
23✔
3798
        c.chanCache.remove(chanID)
23✔
3799

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

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

3816
        return nil
23✔
3817
}
3818

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

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

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

3849
        return isZombie, pubKey1, pubKey2
5✔
3850
}
3851

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

190✔
3858
        var k [8]byte
190✔
3859
        byteOrder.PutUint64(k[:], chanID)
190✔
3860

190✔
3861
        v := zombieIndex.Get(k[:])
190✔
3862
        if v == nil {
292✔
3863
                return false, [33]byte{}, [33]byte{}
102✔
3864
        }
102✔
3865

3866
        var pubKey1, pubKey2 [33]byte
88✔
3867
        copy(pubKey1[:], v[:33])
88✔
3868
        copy(pubKey2[:], v[33:])
88✔
3869

88✔
3870
        return true, pubKey1, pubKey2
88✔
3871
}
3872

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

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

3897
        return numZombies, nil
4✔
3898
}
3899

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

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

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

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

3928
                var k [8]byte
2✔
3929
                byteOrder.PutUint64(k[:], scid.ToUint64())
2✔
3930

2✔
3931
                if closedScids.Get(k[:]) != nil {
3✔
3932
                        isClosed = true
1✔
3933
                        return nil
1✔
3934
                }
1✔
3935

3936
                return nil
1✔
3937
        }, func() {
2✔
3938
                isClosed = false
2✔
3939
        })
2✔
3940
        if err != nil {
2✔
3941
                return false, err
×
3942
        }
×
3943

3944
        return isClosed, nil
2✔
3945
}
3946

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

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

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

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

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

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

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

3985
                return nodeBucket.Put(nodePub, b.Bytes())
76✔
3986
        }
3987

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

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

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

4008
        if err := node.Features.Encode(&b); err != nil {
900✔
4009
                return err
×
4010
        }
×
4011

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

4018
        for _, address := range node.Addresses {
2,030✔
4019
                if err := serializeAddr(&b, address); err != nil {
1,130✔
4020
                        return err
×
4021
                }
×
4022
        }
4023

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

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

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

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

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

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

102✔
4060
                var oldIndexKey [8 + 33]byte
102✔
4061
                copy(oldIndexKey[:8], oldUpdateTime)
102✔
4062
                copy(oldIndexKey[8:], nodePub)
102✔
4063

102✔
4064
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
102✔
4065
                        return err
×
4066
                }
×
4067
        }
4068

4069
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
900✔
4070
                return err
×
4071
        }
×
4072

4073
        return nodeBucket.Put(nodePub, b.Bytes())
900✔
4074
}
4075

4076
func fetchLightningNode(nodeBucket kvdb.RBucket,
4077
        nodePub []byte) (LightningNode, error) {
3,579✔
4078

3,579✔
4079
        nodeBytes := nodeBucket.Get(nodePub)
3,579✔
4080
        if nodeBytes == nil {
3,654✔
4081
                return LightningNode{}, ErrGraphNodeNotFound
75✔
4082
        }
75✔
4083

4084
        nodeReader := bytes.NewReader(nodeBytes)
3,504✔
4085
        return deserializeLightningNode(nodeReader)
3,504✔
4086
}
4087

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

120✔
4096
        var nodeScratch [8]byte
120✔
4097

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

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

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

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

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

4133
        if _, err := wire.ReadVarString(r, 0); err != nil {
120✔
4134
                return nil, err
×
4135
        }
×
4136

4137
        if err := node.features.Decode(r); err != nil {
120✔
4138
                return nil, err
×
4139
        }
×
4140

4141
        return node, nil
120✔
4142
}
4143

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

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

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

4159
        unix := int64(byteOrder.Uint64(scratch[:]))
8,457✔
4160
        node.LastUpdate = time.Unix(unix, 0)
8,457✔
4161

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

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

4170
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,457✔
4171
        if hasNodeAnn == 1 {
16,779✔
4172
                node.HaveNodeAnnouncement = true
8,322✔
4173
        } else {
8,457✔
4174
                node.HaveNodeAnnouncement = false
135✔
4175
        }
135✔
4176

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

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

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

4200
        err = node.Features.Decode(r)
8,322✔
4201
        if err != nil {
8,322✔
4202
                return LightningNode{}, err
×
4203
        }
×
4204

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

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

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

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

4237
        return node, nil
8,322✔
4238
}
4239

4240
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4241
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,461✔
4242

1,461✔
4243
        var b bytes.Buffer
1,461✔
4244

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

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

4262
        authProof := edgeInfo.AuthProof
1,461✔
4263
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,461✔
4264
        if authProof != nil {
2,839✔
4265
                nodeSig1 = authProof.NodeSig1Bytes
1,378✔
4266
                nodeSig2 = authProof.NodeSig2Bytes
1,378✔
4267
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,378✔
4268
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,378✔
4269
        }
1,378✔
4270

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

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

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

4305
        return edgeIndex.Put(chanID[:], b.Bytes())
1,461✔
4306
}
4307

4308
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4309
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,179✔
4310

4,179✔
4311
        edgeInfoBytes := edgeIndex.Get(chanID)
4,179✔
4312
        if edgeInfoBytes == nil {
4,265✔
4313
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
86✔
4314
        }
86✔
4315

4316
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,093✔
4317
        return deserializeChanEdgeInfo(edgeInfoReader)
4,093✔
4318
}
4319

4320
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,717✔
4321
        var (
4,717✔
4322
                err      error
4,717✔
4323
                edgeInfo models.ChannelEdgeInfo
4,717✔
4324
        )
4,717✔
4325

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

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

4344
        proof := &models.ChannelAuthProof{}
4,717✔
4345

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

4363
        if !proof.IsEmpty() {
6,481✔
4364
                edgeInfo.AuthProof = proof
1,764✔
4365
        }
1,764✔
4366

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

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

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

4394
        return edgeInfo, nil
4,717✔
4395
}
4396

4397
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4398
        from, to []byte) error {
2,628✔
4399

2,628✔
4400
        var edgeKey [33 + 8]byte
2,628✔
4401
        copy(edgeKey[:], from)
2,628✔
4402
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,628✔
4403

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

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

2,628✔
4416
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,628✔
4417
        if err != nil {
2,628✔
4418
                return err
×
4419
        }
×
4420

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

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

4444
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
24✔
4445

24✔
4446
                var oldIndexKey [8 + 8]byte
24✔
4447
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
24✔
4448
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
24✔
4449

24✔
4450
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
24✔
4451
                        return err
×
4452
                }
×
4453
        }
4454

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

4459
        updateEdgePolicyDisabledIndex(
2,628✔
4460
                edges, edge.ChannelID,
2,628✔
4461
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,628✔
4462
                edge.IsDisabled(),
2,628✔
4463
        )
2,628✔
4464

2,628✔
4465
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,628✔
4466
}
4467

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

2,896✔
4480
        var disabledEdgeKey [8 + 1]byte
2,896✔
4481
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,896✔
4482
        if direction {
4,342✔
4483
                disabledEdgeKey[8] = 1
1,446✔
4484
        }
1,446✔
4485

4486
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,896✔
4487
                disabledEdgePolicyBucket,
2,896✔
4488
        )
2,896✔
4489
        if err != nil {
2,896✔
4490
                return err
×
4491
        }
×
4492

4493
        if disabled {
2,922✔
4494
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
26✔
4495
        }
26✔
4496

4497
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,870✔
4498
}
4499

4500
// putChanEdgePolicyUnknown marks the edge policy as unknown
4501
// in the edges bucket.
4502
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4503
        from []byte) error {
2,920✔
4504

2,920✔
4505
        var edgeKey [33 + 8]byte
2,920✔
4506
        copy(edgeKey[:], from)
2,920✔
4507
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,920✔
4508

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

4514
        return edges.Put(edgeKey[:], unknownPolicy)
2,920✔
4515
}
4516

4517
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4518
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,150✔
4519

8,150✔
4520
        var edgeKey [33 + 8]byte
8,150✔
4521
        copy(edgeKey[:], nodePub)
8,150✔
4522
        copy(edgeKey[33:], chanID[:])
8,150✔
4523

8,150✔
4524
        edgeBytes := edges.Get(edgeKey[:])
8,150✔
4525
        if edgeBytes == nil {
8,150✔
4526
                return nil, ErrEdgeNotFound
×
4527
        }
×
4528

4529
        // No need to deserialize unknown policy.
4530
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,509✔
4531
                return nil, nil
359✔
4532
        }
359✔
4533

4534
        edgeReader := bytes.NewReader(edgeBytes)
7,791✔
4535

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

4543
        case err != nil:
×
4544
                return nil, err
×
4545
        }
4546

4547
        return ep, nil
7,790✔
4548
}
4549

4550
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4551
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4552
        error) {
232✔
4553

232✔
4554
        edgeInfo := edgeIndex.Get(chanID)
232✔
4555
        if edgeInfo == nil {
232✔
4556
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4557
                        chanID)
×
4558
        }
×
4559

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

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

4579
        return edge1, edge2, nil
232✔
4580
}
4581

4582
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4583
        to []byte) error {
2,630✔
4584

2,630✔
4585
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,630✔
4586
        if err != nil {
2,630✔
4587
                return err
×
4588
        }
×
4589

4590
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,630✔
4591
                return err
×
4592
        }
×
4593

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

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

4620
        if _, err := w.Write(to); err != nil {
2,630✔
4621
                return err
×
4622
        }
×
4623

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

4636
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,630✔
4637
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4638
        }
×
4639
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,630✔
4640
                return err
×
4641
        }
×
4642

4643
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,630✔
4644
                return err
×
4645
        }
×
4646
        return nil
2,630✔
4647
}
4648

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

×
4656
                return nil, deserializeErr
×
4657
        }
×
4658

4659
        return edge, deserializeErr
7,816✔
4660
}
4661

4662
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4663
        error) {
8,823✔
4664

8,823✔
4665
        edge := &models.ChannelEdgePolicy{}
8,823✔
4666

8,823✔
4667
        var err error
8,823✔
4668
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,823✔
4669
        if err != nil {
8,823✔
4670
                return nil, err
×
4671
        }
×
4672

4673
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,823✔
4674
                return nil, err
×
4675
        }
×
4676

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

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

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

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

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

8,823✔
4710
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,823✔
4711
                return nil, err
×
4712
        }
×
4713

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

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

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

4739
                maxHtlc := byteOrder.Uint64(opq[:8])
8,440✔
4740
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,440✔
4741

8,440✔
4742
                // Exclude the parsed field from the rest of the opaque data.
8,440✔
4743
                edge.ExtraOpaqueData = opq[8:]
8,440✔
4744
        }
4745

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