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

lightningnetwork / lnd / 12056196575

27 Nov 2024 06:23PM UTC coverage: 58.717% (-0.2%) from 58.921%
12056196575

Pull #9242

github

aakselrod
go.mod: update to latest btcwallet
Pull Request #9242: Reapply #8644

8 of 39 new or added lines in 3 files covered. (20.51%)

543 existing lines in 30 files now uncovered.

132924 of 226381 relevant lines covered (58.72%)

19504.16 hits per line

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

77.02
/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,881✔
204

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

400
        return nil
1,881✔
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) {
133✔
406
        if c.graphCache != nil {
213✔
407
                return nil, nil
80✔
408
        }
80✔
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,853✔
424

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

671
        return disabledChanIDs, nil
6✔
672
}
673

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

920
        return alias, nil
3✔
921
}
922

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1030
                f(r)
2✔
1031
        }
1032

1033
        return c.chanScheduler.Execute(r)
1,684✔
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,684✔
1040

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

1,684✔
1045
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,684✔
1046
        if err != nil {
1,684✔
1047
                return err
×
1048
        }
×
1049
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,684✔
1050
        if err != nil {
1,684✔
1051
                return err
×
1052
        }
×
1053
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,684✔
1054
        if err != nil {
1,684✔
1055
                return err
×
1056
        }
×
1057
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,684✔
1058
        if err != nil {
1,684✔
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,902✔
1065
                return ErrEdgeAlreadyExist
218✔
1066
        }
218✔
1067

1068
        if c.graphCache != nil {
2,750✔
1069
                c.graphCache.AddChannel(edge, nil, nil)
1,284✔
1070
        }
1,284✔
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,466✔
1077
        switch {
1,466✔
1078
        case node1Err == ErrGraphNodeNotFound:
20✔
1079
                node1Shell := LightningNode{
20✔
1080
                        PubKeyBytes:          edge.NodeKey1Bytes,
20✔
1081
                        HaveNodeAnnouncement: false,
20✔
1082
                }
20✔
1083
                err := addLightningNode(tx, &node1Shell)
20✔
1084
                if err != nil {
20✔
1085
                        return fmt.Errorf("unable to create shell node "+
×
NEW
1086
                                "for: %x: %w", edge.NodeKey1Bytes, err)
×
1087
                }
×
1088
        case node1Err != nil:
×
1089
                return err
×
1090
        }
1091

1092
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
1,466✔
1093
        switch {
1,466✔
1094
        case node2Err == ErrGraphNodeNotFound:
53✔
1095
                node2Shell := LightningNode{
53✔
1096
                        PubKeyBytes:          edge.NodeKey2Bytes,
53✔
1097
                        HaveNodeAnnouncement: false,
53✔
1098
                }
53✔
1099
                err := addLightningNode(tx, &node2Shell)
53✔
1100
                if err != nil {
53✔
1101
                        return fmt.Errorf("unable to create shell node "+
×
NEW
1102
                                "for: %x: %w", edge.NodeKey2Bytes, err)
×
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,466✔
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,466✔
1118
                &edge.NodeKey1Bytes,
1,466✔
1119
                &edge.NodeKey2Bytes,
1,466✔
1120
        }
1,466✔
1121
        for _, key := range keys {
4,396✔
1122
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,930✔
1123
                if err != nil {
2,930✔
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,466✔
1131
        if err := writeOutpoint(&b, &edge.ChannelPoint); err != nil {
1,466✔
1132
                return err
×
1133
        }
×
1134
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,466✔
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) {
222✔
1145

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

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

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

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

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

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

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

1202
                        return nil
102✔
1203
                }
1204

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

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

1216
                e1, e2, err := fetchChanEdgePolicies(
51✔
1217
                        edgeIndex, edges, channelID[:],
51✔
1218
                )
51✔
1219
                if err != nil {
51✔
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 {
71✔
1226
                        upd1Time = e1.LastUpdate
20✔
1227
                }
20✔
1228
                if e2 != nil {
69✔
1229
                        upd2Time = e2.LastUpdate
18✔
1230
                }
18✔
1231

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

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

151✔
1243
        return upd1Time, upd2Time, exists, isZombie, nil
151✔
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 {
3✔
1252
        // Construct the channel's primary key which is the 8-byte channel ID.
3✔
1253
        var chanKey [8]byte
3✔
1254
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
3✔
1255

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

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

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

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

1275
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
3✔
1276
        }, func() {})
3✔
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) {
239✔
1298

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

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

239✔
1304
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
478✔
1305
                // First grab the edges bucket which houses the information
239✔
1306
                // we'd like to delete
239✔
1307
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
239✔
1308
                if err != nil {
239✔
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)
239✔
1314
                if err != nil {
239✔
1315
                        return err
×
1316
                }
×
1317
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
239✔
1318
                if err != nil {
239✔
1319
                        return err
×
1320
                }
×
1321
                nodes := tx.ReadWriteBucket(nodeBucket)
239✔
1322
                if nodes == nil {
239✔
1323
                        return ErrSourceNodeNotSet
×
1324
                }
×
1325
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
239✔
1326
                if err != nil {
239✔
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 {
377✔
1334
                        // TODO(roasbeef): load channel bloom filter, continue
138✔
1335
                        // if NOT if filter
138✔
1336

138✔
1337
                        var opBytes bytes.Buffer
138✔
1338
                        if err := writeOutpoint(&opBytes, chanPoint); err != nil {
138✔
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())
138✔
1345
                        if chanID == nil {
255✔
1346
                                continue
117✔
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)
239✔
1373
                if err != nil {
239✔
1374
                        return err
×
1375
                }
×
1376

1377
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
239✔
1378
                if err != nil {
239✔
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
239✔
1386
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
239✔
1387

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

239✔
1391
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
239✔
1392
                if err != nil {
239✔
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)
239✔
1400
        }, func() {
239✔
1401
                chansClosed = nil
239✔
1402
        })
239✔
1403
        if err != nil {
239✔
1404
                return nil, err
×
1405
        }
×
1406

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

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

1417
        return chansClosed, nil
239✔
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 {
26✔
1425
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
52✔
1426
                nodes := tx.ReadWriteBucket(nodeBucket)
26✔
1427
                if nodes == nil {
26✔
1428
                        return ErrGraphNodesNotFound
×
1429
                }
×
1430
                edges := tx.ReadWriteBucket(edgeBucket)
26✔
1431
                if edges == nil {
26✔
1432
                        return ErrGraphNotFound
×
1433
                }
×
1434
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
26✔
1435
                if edgeIndex == nil {
26✔
1436
                        return ErrGraphNoEdgesFound
×
1437
                }
×
1438

1439
                return c.pruneGraphNodes(nodes, edgeIndex)
26✔
1440
        }, func() {})
26✔
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 {
263✔
1448

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

263✔
1451
        // We'll retrieve the graph's source node to ensure we don't remove it
263✔
1452
        // even if it no longer has any open channels.
263✔
1453
        sourceNode, err := c.sourceNode(nodes)
263✔
1454
        if err != nil {
263✔
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)
263✔
1462
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,552✔
1463
                // If this is the source key, then we skip this
1,289✔
1464
                // iteration as the value for this key is a pubKey
1,289✔
1465
                // rather than raw node information.
1,289✔
1466
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
2,074✔
1467
                        return nil
785✔
1468
                }
785✔
1469

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

506✔
1474
                return nil
506✔
1475
        })
1476
        if err != nil {
263✔
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
263✔
1483

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

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

202✔
1500
                return nil
202✔
1501
        })
202✔
1502
        if err != nil {
263✔
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
263✔
1509
        for nodePubKey, refCount := range nodeRefCounts {
769✔
1510
                // If the ref count of the node isn't zero, then we can safely
506✔
1511
                // skip it as it still has edges to or from it within the
506✔
1512
                // graph.
506✔
1513
                if refCount != 0 {
954✔
1514
                        continue
448✔
1515
                }
1516

1517
                if c.graphCache != nil {
120✔
1518
                        c.graphCache.RemoveNode(nodePubKey)
60✔
1519
                }
60✔
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 {
60✔
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",
60✔
1536
                        nodePubKey[:])
60✔
1537

60✔
1538
                numNodesPruned++
60✔
1539
        }
1540

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

1546
        return nil
263✔
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) {
166✔
1558

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

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

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

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

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

166✔
1581
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
332✔
1582
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
166✔
1583
                if err != nil {
166✔
1584
                        return err
×
1585
                }
×
1586
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
166✔
1587
                if err != nil {
166✔
1588
                        return err
×
1589
                }
×
1590
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
166✔
1591
                if err != nil {
166✔
1592
                        return err
×
1593
                }
×
1594
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
166✔
1595
                if err != nil {
166✔
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
166✔
1606
                cursor := edgeIndex.ReadWriteCursor()
166✔
1607

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

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

1621
                for _, k := range keys {
260✔
1622
                        err = c.delChannelEdgeUnsafe(
94✔
1623
                                edges, edgeIndex, chanIndex, zombieIndex,
94✔
1624
                                k, false, false,
94✔
1625
                        )
94✔
1626
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
94✔
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)
166✔
1634
                if err != nil {
166✔
1635
                        return err
×
1636
                }
×
1637

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

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

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

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

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

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

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

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

1677
        return removedChans, nil
166✔
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) {
57✔
1685
        var (
57✔
1686
                tipHash   chainhash.Hash
57✔
1687
                tipHeight uint32
57✔
1688
        )
57✔
1689

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

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

57✔
1702
                // The prune key with the largest block height will be our
57✔
1703
                // prune tip.
57✔
1704
                k, v := pruneCursor.Last()
57✔
1705
                if k == nil {
78✔
1706
                        return ErrGraphNeverPruned
21✔
1707
                }
21✔
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[:])
38✔
1712
                tipHeight = byteOrder.Uint32(k[:])
38✔
1713

38✔
1714
                return nil
38✔
1715
        }, func() {})
57✔
1716
        if err != nil {
78✔
1717
                return nil, 0, err
21✔
1718
        }
21✔
1719

1720
        return &tipHash, tipHeight, nil
38✔
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 {
135✔
1733

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

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

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

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

1775
                return nil
73✔
1776
        }, func() {})
135✔
1777
        if err != nil {
197✔
1778
                return err
62✔
1779
        }
62✔
1780

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

1786
        return nil
73✔
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) {
3✔
1793
        var chanID uint64
3✔
1794
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1795
                var err error
3✔
1796
                chanID, err = getChanID(tx, chanPoint)
3✔
1797
                return err
3✔
1798
        }, func() {
6✔
1799
                chanID = 0
3✔
1800
        }); err != nil {
5✔
1801
                return 0, err
2✔
1802
        }
2✔
1803

1804
        return chanID, nil
3✔
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) {
3✔
1809
        var b bytes.Buffer
3✔
1810
        if err := writeOutpoint(&b, chanPoint); err != nil {
3✔
1811
                return 0, err
×
1812
        }
×
1813

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

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

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

3✔
1830
        return chanID, nil
3✔
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) {
5✔
1839
        var cid uint64
5✔
1840

5✔
1841
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
1842
                edges := tx.ReadBucket(edgeBucket)
5✔
1843
                if edges == nil {
5✔
1844
                        return ErrGraphNoEdgesFound
×
1845
                }
×
1846
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
5✔
1847
                if edgeIndex == nil {
5✔
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()
5✔
1854

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

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

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

1874
        return cid, nil
5✔
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) {
144✔
1905

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

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

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

1931
                nodes := tx.ReadBucket(nodeBucket)
144✔
1932
                if nodes == nil {
144✔
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()
144✔
1939

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

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

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

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

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

1973
                        // First, we'll fetch the static edge information.
1974
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
20✔
1975
                        if err != nil {
20✔
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(
20✔
1984
                                edgeIndex, edges, chanID,
20✔
1985
                        )
20✔
1986
                        if err != nil {
20✔
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(
20✔
1994
                                nodes, edgeInfo.NodeKey1Bytes[:],
20✔
1995
                        )
20✔
1996
                        if err != nil {
20✔
1997
                                return err
×
1998
                        }
×
1999

2000
                        node2, err := fetchLightningNode(
20✔
2001
                                nodes, edgeInfo.NodeKey2Bytes[:],
20✔
2002
                        )
20✔
2003
                        if err != nil {
20✔
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{}{}
20✔
2010
                        channel := ChannelEdge{
20✔
2011
                                Info:    &edgeInfo,
20✔
2012
                                Policy1: edge1,
20✔
2013
                                Policy2: edge2,
20✔
2014
                                Node1:   &node1,
20✔
2015
                                Node2:   &node2,
20✔
2016
                        }
20✔
2017
                        edgesInHorizon = append(edgesInHorizon, channel)
20✔
2018
                        edgesToCache[chanIDInt] = channel
20✔
2019
                }
2020

2021
                return nil
144✔
2022
        }, func() {
144✔
2023
                edgesSeen = make(map[uint64]struct{})
144✔
2024
                edgesToCache = make(map[uint64]ChannelEdge)
144✔
2025
                edgesInHorizon = nil
144✔
2026
        })
144✔
2027
        switch {
144✔
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 {
164✔
2039
                c.chanCache.insert(chanid, channel)
20✔
2040
        }
20✔
2041

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

144✔
2046
        return edgesInHorizon, nil
144✔
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) {
10✔
2055

10✔
2056
        var nodesInHorizon []LightningNode
10✔
2057

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

2064
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
10✔
2065
                if nodeUpdateIndex == nil {
10✔
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()
10✔
2072

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

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

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

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

2096
                return nil
10✔
2097
        }, func() {
10✔
2098
                nodesInHorizon = nil
10✔
2099
        })
10✔
2100
        switch {
10✔
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
10✔
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) {
125✔
2120

125✔
2121
        var newChanIDs []uint64
125✔
2122

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

125✔
2126
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
250✔
2127
                edges := tx.ReadBucket(edgeBucket)
125✔
2128
                if edges == nil {
125✔
2129
                        return ErrGraphNoEdgesFound
×
2130
                }
×
2131
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
125✔
2132
                if edgeIndex == nil {
125✔
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)
125✔
2140

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

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

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

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

110✔
2179
                                switch {
110✔
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:
22✔
2185
                                        continue
22✔
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:
19✔
2193
                                        err := c.markEdgeLiveUnsafe(tx, scid)
19✔
2194
                                        if err != nil {
19✔
2195
                                                return err
×
2196
                                        }
×
2197
                                }
2198
                        }
2199

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

2203
                return nil
125✔
2204
        }, func() {
125✔
2205
                newChanIDs = nil
125✔
2206
        })
125✔
2207
        switch {
125✔
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
125✔
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 {
220✔
2247

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

220✔
2254
        if node1Timestamp.IsZero() {
430✔
2255
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
210✔
2256
        }
210✔
2257

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

2262
        return chanInfo
220✔
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) {
13✔
2287

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

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

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

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

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

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

2329
                        if edgeInfo.AuthProof == nil {
48✔
2330
                                continue
2✔
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)
46✔
2336
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
46✔
2337

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

46✔
2342
                        if !withTimestamps {
68✔
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)
24✔
2352

24✔
2353
                        rawPolicy := edges.Get(node1Key)
24✔
2354
                        if len(rawPolicy) != 0 {
32✔
2355
                                r := bytes.NewReader(rawPolicy)
8✔
2356

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

×
2362
                                        return err
×
2363
                                }
×
2364

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

2368
                        rawPolicy = edges.Get(node2Key)
24✔
2369
                        if len(rawPolicy) != 0 {
37✔
2370
                                r := bytes.NewReader(rawPolicy)
13✔
2371

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

×
2377
                                        return err
×
2378
                                }
×
2379

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

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

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

2393
        switch {
13✔
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:
5✔
2397
                return nil, nil
5✔
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))
10✔
2405
        for block := range channelsPerBlock {
34✔
2406
                blocks = append(blocks, block)
24✔
2407
        }
24✔
2408
        sort.Slice(blocks, func(i, j int) bool {
34✔
2409
                return blocks[i] < blocks[j]
24✔
2410
        })
24✔
2411

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

2420
        return channelRanges, nil
10✔
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) {
5✔
2429
        return c.fetchChanInfos(nil, chanIDs)
5✔
2430
}
5✔
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) {
25✔
2442
        // TODO(roasbeef): sort cids?
25✔
2443

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

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

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

32✔
2466
                        // First, we'll fetch the static edge information. If
32✔
2467
                        // the edge is unknown, we will skip the edge and
32✔
2468
                        // continue gathering all known edges.
32✔
2469
                        edgeInfo, err := fetchChanEdgeInfo(
32✔
2470
                                edgeIndex, cidBytes[:],
32✔
2471
                        )
32✔
2472
                        switch {
32✔
2473
                        case errors.Is(err, ErrEdgeNotFound):
24✔
2474
                                continue
24✔
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(
10✔
2482
                                edgeIndex, edges, cidBytes[:],
10✔
2483
                        )
10✔
2484
                        if err != nil {
10✔
2485
                                return err
×
2486
                        }
×
2487

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

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

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

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

2521
                return chanEdges, nil
6✔
2522
        }
2523

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

2529
        return chanEdges, nil
19✔
2530
}
2531

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

139✔
2535
        // First, we'll fetch the edge update index bucket which currently
139✔
2536
        // stores an entry for the channel we're about to delete.
139✔
2537
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
139✔
2538
        if updateIndex == nil {
139✔
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
139✔
2546
        byteOrder.PutUint64(indexKey[8:], chanID)
139✔
2547

139✔
2548
        // With the template constructed, we'll attempt to delete an entry that
139✔
2549
        // would have been created by both edges: we'll alternate the update
139✔
2550
        // times, as one may had overridden the other.
139✔
2551
        if edge1 != nil {
151✔
2552
                byteOrder.PutUint64(indexKey[:8], uint64(edge1.LastUpdate.Unix()))
12✔
2553
                if err := updateIndex.Delete(indexKey[:]); err != nil {
12✔
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 {
153✔
2561
                byteOrder.PutUint64(indexKey[:8], uint64(edge2.LastUpdate.Unix()))
14✔
2562
                if err := updateIndex.Delete(indexKey[:]); err != nil {
14✔
2563
                        return err
×
2564
                }
×
2565
        }
2566

2567
        return nil
139✔
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 {
201✔
2580

201✔
2581
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
201✔
2582
        if err != nil {
263✔
2583
                return err
62✔
2584
        }
62✔
2585

2586
        if c.graphCache != nil {
278✔
2587
                c.graphCache.RemoveChannel(
139✔
2588
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
139✔
2589
                        edgeInfo.ChannelID,
139✔
2590
                )
139✔
2591
        }
139✔
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)
139✔
2597
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
139✔
2598
        if err != nil {
139✔
2599
                return err
×
2600
        }
×
2601
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
139✔
2602
        if err != nil {
139✔
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
139✔
2609
        copy(edgeKey[33:], chanID)
139✔
2610

139✔
2611
        // With the latter half constructed, copy over the first public key to
139✔
2612
        // delete the edge in this direction, then the second to delete the
139✔
2613
        // edge in the opposite direction.
139✔
2614
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
139✔
2615
        if edges.Get(edgeKey[:]) != nil {
278✔
2616
                if err := edges.Delete(edgeKey[:]); err != nil {
139✔
2617
                        return err
×
2618
                }
×
2619
        }
2620
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
139✔
2621
        if edges.Get(edgeKey[:]) != nil {
278✔
2622
                if err := edges.Delete(edgeKey[:]); err != nil {
139✔
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
        err = updateEdgePolicyDisabledIndex(edges, cid, false, false)
139✔
2630
        if err != nil {
139✔
NEW
2631
                return err
×
NEW
2632
        }
×
2633
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
139✔
2634
        if err != nil {
139✔
NEW
2635
                return err
×
NEW
2636
        }
×
2637

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

2651
        // Finally, we'll mark the edge as a zombie within our index if it's
2652
        // being removed due to the channel becoming a zombie. We do this to
2653
        // ensure we don't store unnecessary data for spent channels.
2654
        if !isZombie {
256✔
2655
                return nil
117✔
2656
        }
117✔
2657

2658
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
24✔
2659
        if strictZombie {
27✔
2660
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2661
        }
3✔
2662

2663
        return markEdgeZombie(
24✔
2664
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
24✔
2665
        )
24✔
2666
}
2667

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

3✔
2687
        switch {
3✔
2688
        // If we don't have either edge policy, we'll return both pubkeys so
2689
        // that the channel can be resurrected by either party.
UNCOV
2690
        case e1 == nil && e2 == nil:
×
UNCOV
2691
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2692

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

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

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

2,633✔
2718
        var (
2,633✔
2719
                isUpdate1    bool
2,633✔
2720
                edgeNotFound bool
2,633✔
2721
        )
2,633✔
2722

2,633✔
2723
        r := &batch.Request{
2,633✔
2724
                Reset: func() {
5,266✔
2725
                        isUpdate1 = false
2,633✔
2726
                        edgeNotFound = false
2,633✔
2727
                },
2,633✔
2728
                Update: func(tx kvdb.RwTx) error {
2,633✔
2729
                        var err error
2,633✔
2730
                        isUpdate1, err = updateEdgePolicy(
2,633✔
2731
                                tx, edge, c.graphCache,
2,633✔
2732
                        )
2,633✔
2733

2,633✔
2734
                        // Silence ErrEdgeNotFound so that the batch can
2,633✔
2735
                        // succeed, but propagate the error via local state.
2,633✔
2736
                        if errors.Is(err, ErrEdgeNotFound) {
2,636✔
2737
                                edgeNotFound = true
3✔
2738
                                return nil
3✔
2739
                        }
3✔
2740

2741
                        return err
2,630✔
2742
                },
2743
                OnCommit: func(err error) error {
2,633✔
2744
                        switch {
2,633✔
2745
                        case err != nil:
×
2746
                                return err
×
2747
                        case edgeNotFound:
3✔
2748
                                return ErrEdgeNotFound
3✔
2749
                        default:
2,630✔
2750
                                c.updateEdgeCache(edge, isUpdate1)
2,630✔
2751
                                return nil
2,630✔
2752
                        }
2753
                },
2754
        }
2755

2756
        for _, f := range op {
2,635✔
2757
                f(r)
2✔
2758
        }
2✔
2759

2760
        return c.chanScheduler.Execute(r)
2,633✔
2761
}
2762

2763
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2764
        isUpdate1 bool) {
2,630✔
2765

2,630✔
2766
        // If an entry for this channel is found in reject cache, we'll modify
2,630✔
2767
        // the entry with the updated timestamp for the direction that was just
2,630✔
2768
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,630✔
2769
        // during the next query for this edge.
2,630✔
2770
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,637✔
2771
                if isUpdate1 {
12✔
2772
                        entry.upd1Time = e.LastUpdate.Unix()
5✔
2773
                } else {
9✔
2774
                        entry.upd2Time = e.LastUpdate.Unix()
4✔
2775
                }
4✔
2776
                c.rejectCache.insert(e.ChannelID, entry)
7✔
2777
        }
2778

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

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

2,633✔
2800
        edges := tx.ReadWriteBucket(edgeBucket)
2,633✔
2801
        if edges == nil {
2,633✔
2802
                return false, ErrEdgeNotFound
×
2803
        }
×
2804
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,633✔
2805
        if edgeIndex == nil {
2,633✔
2806
                return false, ErrEdgeNotFound
×
2807
        }
×
2808

2809
        // Create the channelID key be converting the channel ID
2810
        // integer into a byte slice.
2811
        var chanID [8]byte
2,633✔
2812
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,633✔
2813

2,633✔
2814
        // With the channel ID, we then fetch the value storing the two
2,633✔
2815
        // nodes which connect this channel edge.
2,633✔
2816
        nodeInfo := edgeIndex.Get(chanID[:])
2,633✔
2817
        if nodeInfo == nil {
2,636✔
2818
                return false, ErrEdgeNotFound
3✔
2819
        }
3✔
2820

2821
        // Depending on the flags value passed above, either the first
2822
        // or second edge policy is being updated.
2823
        var fromNode, toNode []byte
2,630✔
2824
        var isUpdate1 bool
2,630✔
2825
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3,950✔
2826
                fromNode = nodeInfo[:33]
1,320✔
2827
                toNode = nodeInfo[33:66]
1,320✔
2828
                isUpdate1 = true
1,320✔
2829
        } else {
2,632✔
2830
                fromNode = nodeInfo[33:66]
1,312✔
2831
                toNode = nodeInfo[:33]
1,312✔
2832
                isUpdate1 = false
1,312✔
2833
        }
1,312✔
2834

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

2842
        var (
2,630✔
2843
                fromNodePubKey route.Vertex
2,630✔
2844
                toNodePubKey   route.Vertex
2,630✔
2845
        )
2,630✔
2846
        copy(fromNodePubKey[:], fromNode)
2,630✔
2847
        copy(toNodePubKey[:], toNode)
2,630✔
2848

2,630✔
2849
        if graphCache != nil {
4,890✔
2850
                graphCache.UpdatePolicy(
2,260✔
2851
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,260✔
2852
                )
2,260✔
2853
        }
2,260✔
2854

2855
        return isUpdate1, nil
2,630✔
2856
}
2857

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

2867
        // HaveNodeAnnouncement indicates whether we received a node
2868
        // announcement for this particular node. If true, the remaining fields
2869
        // will be set, if false only the PubKey is known for this node.
2870
        HaveNodeAnnouncement bool
2871

2872
        // LastUpdate is the last time the vertex information for this node has
2873
        // been updated.
2874
        LastUpdate time.Time
2875

2876
        // Address is the TCP address this node is reachable over.
2877
        Addresses []net.Addr
2878

2879
        // Color is the selected color for the node.
2880
        Color color.RGBA
2881

2882
        // Alias is a nick-name for the node. The alias can be used to confirm
2883
        // a node's identity or to serve as a short ID for an address book.
2884
        Alias string
2885

2886
        // AuthSigBytes is the raw signature under the advertised public key
2887
        // which serves to authenticate the attributes announced by this node.
2888
        AuthSigBytes []byte
2889

2890
        // Features is the list of protocol features supported by this node.
2891
        Features *lnwire.FeatureVector
2892

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

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

2904
        // TODO(roasbeef): add update method and fetch?
2905
}
2906

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

2917
        key, err := btcec.ParsePubKey(l.PubKeyBytes[:])
973✔
2918
        if err != nil {
973✔
2919
                return nil, err
×
2920
        }
×
2921
        l.pubKey = key
973✔
2922

973✔
2923
        return key, nil
973✔
2924
}
2925

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

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

2942
// NodeAnnouncement retrieves the latest node announcement of the node.
2943
func (l *LightningNode) NodeAnnouncement(signed bool) (*lnwire.NodeAnnouncement,
2944
        error) {
16✔
2945

16✔
2946
        if !l.HaveNodeAnnouncement {
18✔
2947
                return nil, fmt.Errorf("node does not have node announcement")
2✔
2948
        }
2✔
2949

2950
        alias, err := lnwire.NewNodeAlias(l.Alias)
16✔
2951
        if err != nil {
16✔
2952
                return nil, err
×
2953
        }
×
2954

2955
        nodeAnn := &lnwire.NodeAnnouncement{
16✔
2956
                Features:        l.Features.RawFeatureVector,
16✔
2957
                NodeID:          l.PubKeyBytes,
16✔
2958
                RGBColor:        l.Color,
16✔
2959
                Alias:           alias,
16✔
2960
                Addresses:       l.Addresses,
16✔
2961
                Timestamp:       uint32(l.LastUpdate.Unix()),
16✔
2962
                ExtraOpaqueData: l.ExtraOpaqueData,
16✔
2963
        }
16✔
2964

16✔
2965
        if !signed {
18✔
2966
                return nodeAnn, nil
2✔
2967
        }
2✔
2968

2969
        sig, err := lnwire.NewSigFromECDSARawSignature(l.AuthSigBytes)
16✔
2970
        if err != nil {
16✔
2971
                return nil, err
×
2972
        }
×
2973

2974
        nodeAnn.Signature = sig
16✔
2975

16✔
2976
        return nodeAnn, nil
16✔
2977
}
2978

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

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

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

5✔
3002
                        nodeIsPublic = true
5✔
3003
                        return errDone
5✔
3004
                }
5✔
3005

3006
                // Since the edge _does_ extend to the source node, we'll also
3007
                // need to ensure that this is a public edge.
3008
                if info.AuthProof != nil {
17✔
3009
                        nodeIsPublic = true
8✔
3010
                        return errDone
8✔
3011
                }
8✔
3012

3013
                // Otherwise, we'll continue our search.
3014
                return nil
3✔
3015
        })
3016
        if err != nil && err != errDone {
15✔
3017
                return false, err
×
3018
        }
×
3019

3020
        return nodeIsPublic, nil
15✔
3021
}
3022

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

2,944✔
3030
        return c.fetchLightningNode(tx, nodePub)
2,944✔
3031
}
2,944✔
3032

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

829✔
3039
        return c.fetchLightningNode(nil, nodePub)
829✔
3040
}
829✔
3041

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

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

3058
                // If a key for this serialized public key isn't found, then
3059
                // the target node doesn't exist within the database.
3060
                nodeBytes := nodes.Get(nodePub[:])
3,773✔
3061
                if nodeBytes == nil {
3,783✔
3062
                        return ErrGraphNodeNotFound
10✔
3063
                }
10✔
3064

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

3073
                node = &n
3,765✔
3074

3,765✔
3075
                return nil
3,765✔
3076
        }
3077

3078
        if tx == nil {
4,602✔
3079
                err := kvdb.View(
829✔
3080
                        c.db, fetch, func() {
1,658✔
3081
                                node = nil
829✔
3082
                        },
829✔
3083
                )
3084
                if err != nil {
839✔
3085
                        return nil, err
10✔
3086
                }
10✔
3087

3088
                return node, nil
821✔
3089
        }
3090

3091
        err := fetch(tx)
2,944✔
3092
        if err != nil {
2,944✔
3093
                return nil, err
×
3094
        }
×
3095

3096
        return node, nil
2,944✔
3097
}
3098

3099
// graphCacheNode is a struct that wraps a LightningNode in a way that it can be
3100
// cached in the graph cache.
3101
type graphCacheNode struct {
3102
        pubKeyBytes route.Vertex
3103
        features    *lnwire.FeatureVector
3104
}
3105

3106
// newGraphCacheNode returns a new cache optimized node.
3107
func newGraphCacheNode(pubKey route.Vertex,
3108
        features *lnwire.FeatureVector) *graphCacheNode {
727✔
3109

727✔
3110
        return &graphCacheNode{
727✔
3111
                pubKeyBytes: pubKey,
727✔
3112
                features:    features,
727✔
3113
        }
727✔
3114
}
727✔
3115

3116
// PubKey returns the node's public identity key.
3117
func (n *graphCacheNode) PubKey() route.Vertex {
727✔
3118
        return n.pubKeyBytes
727✔
3119
}
727✔
3120

3121
// Features returns the node's features.
3122
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
707✔
3123
        return n.features
707✔
3124
}
707✔
3125

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

627✔
3138
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
627✔
3139
}
627✔
3140

3141
var _ GraphCacheNode = (*graphCacheNode)(nil)
3142

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

18✔
3154
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
36✔
3155
                // First grab the nodes bucket which stores the mapping from
18✔
3156
                // pubKey to node information.
18✔
3157
                nodes := tx.ReadBucket(nodeBucket)
18✔
3158
                if nodes == nil {
18✔
3159
                        return ErrGraphNotFound
×
3160
                }
×
3161

3162
                // If a key for this serialized public key isn't found, we can
3163
                // exit early.
3164
                nodeBytes := nodes.Get(nodePub[:])
18✔
3165
                if nodeBytes == nil {
23✔
3166
                        exists = false
5✔
3167
                        return nil
5✔
3168
                }
5✔
3169

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

3179
                exists = true
15✔
3180
                updateTime = node.LastUpdate
15✔
3181
                return nil
15✔
3182
        }, func() {
18✔
3183
                updateTime = time.Time{}
18✔
3184
                exists = false
18✔
3185
        })
18✔
3186
        if err != nil {
18✔
3187
                return time.Time{}, exists, err
×
3188
        }
×
3189

3190
        return updateTime, exists, nil
18✔
3191
}
3192

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

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

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

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

3236
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,846✔
3237
                                edges, chanID, nodePub,
3,846✔
3238
                        )
3,846✔
3239
                        if err != nil {
3,846✔
3240
                                return err
×
3241
                        }
×
3242

3243
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,846✔
3244
                        if err != nil {
3,846✔
3245
                                return err
×
3246
                        }
×
3247

3248
                        incomingPolicy, err := fetchChanEdgePolicy(
3,846✔
3249
                                edges, chanID, otherNode[:],
3,846✔
3250
                        )
3,846✔
3251
                        if err != nil {
3,846✔
3252
                                return err
×
3253
                        }
×
3254

3255
                        // Finally, we execute the callback.
3256
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,846✔
3257
                        if err != nil {
3,857✔
3258
                                return err
11✔
3259
                        }
11✔
3260
                }
3261

3262
                return nil
1,860✔
3263
        }
3264

3265
        // If no transaction was provided, then we'll create a new transaction
3266
        // to execute the transaction within.
3267
        if tx == nil {
1,880✔
3268
                return kvdb.View(db, traversal, func() {})
22✔
3269
        }
3270

3271
        // Otherwise, we re-use the existing transaction to execute the graph
3272
        // traversal.
3273
        return traversal(tx)
1,860✔
3274
}
3275

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

8✔
3288
        return nodeTraversal(nil, nodePub[:], c.db, cb)
8✔
3289
}
8✔
3290

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

1,000✔
3309
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,000✔
3310
}
1,000✔
3311

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

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

3331
        var targetNode *LightningNode
2✔
3332
        fetchNodeFunc := func(tx kvdb.RTx) error {
4✔
3333
                // First grab the nodes bucket which stores the mapping from
2✔
3334
                // pubKey to node information.
2✔
3335
                nodes := tx.ReadBucket(nodeBucket)
2✔
3336
                if nodes == nil {
2✔
3337
                        return ErrGraphNotFound
×
3338
                }
×
3339

3340
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
2✔
3341
                if err != nil {
2✔
3342
                        return err
×
3343
                }
×
3344

3345
                targetNode = &node
2✔
3346

2✔
3347
                return nil
2✔
3348
        }
3349

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

3359
        return targetNode, err
2✔
3360
}
3361

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

24✔
3371
        copy(node1Key[:], info.NodeKey1Bytes[:])
24✔
3372
        copy(node2Key[:], info.NodeKey2Bytes[:])
24✔
3373

24✔
3374
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
24✔
3375
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
24✔
3376

24✔
3377
        return node1Key[:], node2Key[:]
24✔
3378
}
24✔
3379

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

13✔
3389
        var (
13✔
3390
                edgeInfo *models.ChannelEdgeInfo
13✔
3391
                policy1  *models.ChannelEdgePolicy
13✔
3392
                policy2  *models.ChannelEdgePolicy
13✔
3393
        )
13✔
3394

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

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

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

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

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

3446
                policy1 = e1
3✔
3447
                policy2 = e2
3✔
3448
                return nil
3✔
3449
        }, func() {
13✔
3450
                edgeInfo = nil
13✔
3451
                policy1 = nil
13✔
3452
                policy2 = nil
13✔
3453
        })
13✔
3454
        if err != nil {
25✔
3455
                return nil, nil, nil, err
12✔
3456
        }
12✔
3457

3458
        return edgeInfo, policy1, policy2, nil
3✔
3459
}
3460

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

27✔
3474
        var (
27✔
3475
                edgeInfo  *models.ChannelEdgeInfo
27✔
3476
                policy1   *models.ChannelEdgePolicy
27✔
3477
                policy2   *models.ChannelEdgePolicy
27✔
3478
                channelID [8]byte
27✔
3479
        )
27✔
3480

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

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

3501
                byteOrder.PutUint64(channelID[:], chanID)
27✔
3502

27✔
3503
                // Now, attempt to fetch edge.
27✔
3504
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
27✔
3505

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

3517
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3518
                                zombieIndex, chanID,
3✔
3519
                        )
3✔
3520
                        if !isZombie {
5✔
3521
                                return ErrEdgeNotFound
2✔
3522
                        }
2✔
3523

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

3535
                // Otherwise, we'll just return the error if any.
3536
                if err != nil {
26✔
3537
                        return err
×
3538
                }
×
3539

3540
                edgeInfo = &edge
26✔
3541

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

3551
                policy1 = e1
26✔
3552
                policy2 = e2
26✔
3553
                return nil
26✔
3554
        }, func() {
27✔
3555
                edgeInfo = nil
27✔
3556
                policy1 = nil
27✔
3557
                policy2 = nil
27✔
3558
        })
27✔
3559
        if err == ErrZombieEdge {
30✔
3560
                return edgeInfo, nil, nil, err
3✔
3561
        }
3✔
3562
        if err != nil {
28✔
3563
                return nil, nil, nil, err
2✔
3564
        }
2✔
3565

3566
        return edgeInfo, policy1, policy2, nil
26✔
3567
}
3568

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

3588
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
15✔
3589
                return err
15✔
3590
        }, func() {
15✔
3591
                nodeIsPublic = false
15✔
3592
        })
15✔
3593
        if err != nil {
15✔
3594
                return false, err
×
3595
        }
×
3596

3597
        return nodeIsPublic, nil
15✔
3598
}
3599

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

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

48✔
3617
        return bldr.Script()
48✔
3618
}
3619

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

3628
        // OutPoint is the outpoint of the target channel.
3629
        OutPoint wire.OutPoint
3630
}
3631

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

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

3661
                // Once we have the proper bucket, we'll range over each key
3662
                // (which is the channel point for the channel) and decode it,
3663
                // accumulating each entry.
3664
                return chanIndex.ForEach(func(chanPointBytes, chanID []byte) error {
69✔
3665
                        chanPointReader := bytes.NewReader(chanPointBytes)
44✔
3666

44✔
3667
                        var chanPoint wire.OutPoint
44✔
3668
                        err := readOutpoint(chanPointReader, &chanPoint)
44✔
3669
                        if err != nil {
44✔
3670
                                return err
×
3671
                        }
×
3672

3673
                        edgeInfo, err := fetchChanEdgeInfo(
44✔
3674
                                edgeIndex, chanID,
44✔
3675
                        )
44✔
3676
                        if err != nil {
44✔
3677
                                return err
×
3678
                        }
×
3679

3680
                        pkScript, err := genMultiSigP2WSH(
44✔
3681
                                edgeInfo.BitcoinKey1Bytes[:],
44✔
3682
                                edgeInfo.BitcoinKey2Bytes[:],
44✔
3683
                        )
44✔
3684
                        if err != nil {
44✔
3685
                                return err
×
3686
                        }
×
3687

3688
                        edgePoints = append(edgePoints, EdgePoint{
44✔
3689
                                FundingPkScript: pkScript,
44✔
3690
                                OutPoint:        chanPoint,
44✔
3691
                        })
44✔
3692

44✔
3693
                        return nil
44✔
3694
                })
3695
        }, func() {
25✔
3696
                edgePoints = nil
25✔
3697
        }); err != nil {
25✔
3698
                return nil, err
×
3699
        }
×
3700

3701
        return edgePoints, nil
25✔
3702
}
3703

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

129✔
3710
        c.cacheMu.Lock()
129✔
3711
        defer c.cacheMu.Unlock()
129✔
3712

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

3724
                if c.graphCache != nil {
258✔
3725
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
129✔
3726
                }
129✔
3727

3728
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
129✔
3729
        })
3730
        if err != nil {
129✔
3731
                return err
×
3732
        }
×
3733

3734
        c.rejectCache.remove(chanID)
129✔
3735
        c.chanCache.remove(chanID)
129✔
3736

129✔
3737
        return nil
129✔
3738
}
3739

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

153✔
3746
        var k [8]byte
153✔
3747
        byteOrder.PutUint64(k[:], chanID)
153✔
3748

153✔
3749
        var v [66]byte
153✔
3750
        copy(v[:33], pubKey1[:])
153✔
3751
        copy(v[33:], pubKey2[:])
153✔
3752

153✔
3753
        return zombieIndex.Put(k[:], v[:])
153✔
3754
}
153✔
3755

3756
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3757
func (c *ChannelGraph) MarkEdgeLive(chanID uint64) error {
4✔
3758
        c.cacheMu.Lock()
4✔
3759
        defer c.cacheMu.Unlock()
4✔
3760

4✔
3761
        return c.markEdgeLiveUnsafe(nil, chanID)
4✔
3762
}
4✔
3763

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

3781
                var k [8]byte
23✔
3782
                byteOrder.PutUint64(k[:], chanID)
23✔
3783

23✔
3784
                if len(zombieIndex.Get(k[:])) == 0 {
24✔
3785
                        return ErrZombieEdgeNotFound
1✔
3786
                }
1✔
3787

3788
                return zombieIndex.Delete(k[:])
22✔
3789
        }
3790

3791
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3792
        // the existing transaction
3793
        var err error
23✔
3794
        if tx == nil {
27✔
3795
                err = kvdb.Update(c.db, dbFn, func() {})
8✔
3796
        } else {
19✔
3797
                err = dbFn(tx)
19✔
3798
        }
19✔
3799
        if err != nil {
24✔
3800
                return err
1✔
3801
        }
1✔
3802

3803
        c.rejectCache.remove(chanID)
22✔
3804
        c.chanCache.remove(chanID)
22✔
3805

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

3814
                for _, edgeInfo := range edgeInfos {
22✔
3815
                        c.graphCache.AddChannel(
×
3816
                                edgeInfo.Info, edgeInfo.Policy1,
×
3817
                                edgeInfo.Policy2,
×
3818
                        )
×
3819
                }
×
3820
        }
3821

3822
        return nil
22✔
3823
}
3824

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

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

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

3855
        return isZombie, pubKey1, pubKey2
5✔
3856
}
3857

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

216✔
3864
        var k [8]byte
216✔
3865
        byteOrder.PutUint64(k[:], chanID)
216✔
3866

216✔
3867
        v := zombieIndex.Get(k[:])
216✔
3868
        if v == nil {
349✔
3869
                return false, [33]byte{}, [33]byte{}
133✔
3870
        }
133✔
3871

3872
        var pubKey1, pubKey2 [33]byte
85✔
3873
        copy(pubKey1[:], v[:33])
85✔
3874
        copy(pubKey2[:], v[33:])
85✔
3875

85✔
3876
        return true, pubKey1, pubKey2
85✔
3877
}
3878

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

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

3903
        return numZombies, nil
4✔
3904
}
3905

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

3916
                var k [8]byte
1✔
3917
                byteOrder.PutUint64(k[:], scid.ToUint64())
1✔
3918

1✔
3919
                return closedScids.Put(k[:], []byte{})
1✔
3920
        }, func() {})
1✔
3921
}
3922

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

3934
                var k [8]byte
4✔
3935
                byteOrder.PutUint64(k[:], scid.ToUint64())
4✔
3936

4✔
3937
                if closedScids.Get(k[:]) != nil {
5✔
3938
                        isClosed = true
1✔
3939
                        return nil
1✔
3940
                }
1✔
3941

3942
                return nil
3✔
3943
        }, func() {
4✔
3944
                isClosed = false
4✔
3945
        })
4✔
3946
        if err != nil {
4✔
3947
                return false, err
×
3948
        }
×
3949

3950
        return isClosed, nil
4✔
3951
}
3952

3953
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3954
        updateIndex kvdb.RwBucket, node *LightningNode) error {
972✔
3955

972✔
3956
        var (
972✔
3957
                scratch [16]byte
972✔
3958
                b       bytes.Buffer
972✔
3959
        )
972✔
3960

972✔
3961
        pub, err := node.PubKey()
972✔
3962
        if err != nil {
972✔
3963
                return err
×
3964
        }
×
3965
        nodePub := pub.SerializeCompressed()
972✔
3966

972✔
3967
        // If the node has the update time set, write it, else write 0.
972✔
3968
        updateUnix := uint64(0)
972✔
3969
        if node.LastUpdate.Unix() > 0 {
1,821✔
3970
                updateUnix = uint64(node.LastUpdate.Unix())
849✔
3971
        }
849✔
3972

3973
        byteOrder.PutUint64(scratch[:8], updateUnix)
972✔
3974
        if _, err := b.Write(scratch[:8]); err != nil {
972✔
3975
                return err
×
3976
        }
×
3977

3978
        if _, err := b.Write(nodePub); err != nil {
972✔
3979
                return err
×
3980
        }
×
3981

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

3991
                return nodeBucket.Put(nodePub, b.Bytes())
72✔
3992
        }
3993

3994
        // Write HaveNodeAnnouncement=1.
3995
        byteOrder.PutUint16(scratch[:2], 1)
902✔
3996
        if _, err := b.Write(scratch[:2]); err != nil {
902✔
3997
                return err
×
3998
        }
×
3999

4000
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
902✔
4001
                return err
×
4002
        }
×
4003
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
902✔
4004
                return err
×
4005
        }
×
4006
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
902✔
4007
                return err
×
4008
        }
×
4009

4010
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
902✔
4011
                return err
×
4012
        }
×
4013

4014
        if err := node.Features.Encode(&b); err != nil {
902✔
4015
                return err
×
4016
        }
×
4017

4018
        numAddresses := uint16(len(node.Addresses))
902✔
4019
        byteOrder.PutUint16(scratch[:2], numAddresses)
902✔
4020
        if _, err := b.Write(scratch[:2]); err != nil {
902✔
4021
                return err
×
4022
        }
×
4023

4024
        for _, address := range node.Addresses {
2,034✔
4025
                if err := serializeAddr(&b, address); err != nil {
1,132✔
4026
                        return err
×
4027
                }
×
4028
        }
4029

4030
        sigLen := len(node.AuthSigBytes)
902✔
4031
        if sigLen > 80 {
902✔
4032
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
4033
                        sigLen)
×
4034
        }
×
4035

4036
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
902✔
4037
        if err != nil {
902✔
4038
                return err
×
4039
        }
×
4040

4041
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
902✔
4042
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
4043
        }
×
4044
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
902✔
4045
        if err != nil {
902✔
4046
                return err
×
4047
        }
×
4048

4049
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
902✔
4050
                return err
×
4051
        }
×
4052

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

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

104✔
4066
                var oldIndexKey [8 + 33]byte
104✔
4067
                copy(oldIndexKey[:8], oldUpdateTime)
104✔
4068
                copy(oldIndexKey[8:], nodePub)
104✔
4069

104✔
4070
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
104✔
4071
                        return err
×
4072
                }
×
4073
        }
4074

4075
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
902✔
4076
                return err
×
4077
        }
×
4078

4079
        return nodeBucket.Put(nodePub, b.Bytes())
902✔
4080
}
4081

4082
func fetchLightningNode(nodeBucket kvdb.RBucket,
4083
        nodePub []byte) (LightningNode, error) {
3,573✔
4084

3,573✔
4085
        nodeBytes := nodeBucket.Get(nodePub)
3,573✔
4086
        if nodeBytes == nil {
3,644✔
4087
                return LightningNode{}, ErrGraphNodeNotFound
71✔
4088
        }
71✔
4089

4090
        nodeReader := bytes.NewReader(nodeBytes)
3,504✔
4091
        return deserializeLightningNode(nodeReader)
3,504✔
4092
}
4093

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

122✔
4102
        var nodeScratch [8]byte
122✔
4103

122✔
4104
        // Skip ahead:
122✔
4105
        // - LastUpdate (8 bytes)
122✔
4106
        if _, err := r.Read(nodeScratch[:]); err != nil {
122✔
4107
                return nil, err
×
4108
        }
×
4109

4110
        if _, err := io.ReadFull(r, node.pubKeyBytes[:]); err != nil {
122✔
4111
                return nil, err
×
4112
        }
×
4113

4114
        // Read the node announcement flag.
4115
        if _, err := r.Read(nodeScratch[:2]); err != nil {
122✔
4116
                return nil, err
×
4117
        }
×
4118
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
122✔
4119

122✔
4120
        // The rest of the data is optional, and will only be there if we got a
122✔
4121
        // node announcement for this node.
122✔
4122
        if hasNodeAnn == 0 {
124✔
4123
                return node, nil
2✔
4124
        }
2✔
4125

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

4139
        if _, err := wire.ReadVarString(r, 0); err != nil {
122✔
4140
                return nil, err
×
4141
        }
×
4142

4143
        if err := node.features.Decode(r); err != nil {
122✔
4144
                return nil, err
×
4145
        }
×
4146

4147
        return node, nil
122✔
4148
}
4149

4150
func deserializeLightningNode(r io.Reader) (LightningNode, error) {
8,458✔
4151
        var (
8,458✔
4152
                node    LightningNode
8,458✔
4153
                scratch [8]byte
8,458✔
4154
                err     error
8,458✔
4155
        )
8,458✔
4156

8,458✔
4157
        // Always populate a feature vector, even if we don't have a node
8,458✔
4158
        // announcement and short circuit below.
8,458✔
4159
        node.Features = lnwire.EmptyFeatureVector()
8,458✔
4160

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

4165
        unix := int64(byteOrder.Uint64(scratch[:]))
8,458✔
4166
        node.LastUpdate = time.Unix(unix, 0)
8,458✔
4167

8,458✔
4168
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,458✔
4169
                return LightningNode{}, err
×
4170
        }
×
4171

4172
        if _, err := r.Read(scratch[:2]); err != nil {
8,458✔
4173
                return LightningNode{}, err
×
4174
        }
×
4175

4176
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,458✔
4177
        if hasNodeAnn == 1 {
16,777✔
4178
                node.HaveNodeAnnouncement = true
8,319✔
4179
        } else {
8,460✔
4180
                node.HaveNodeAnnouncement = false
141✔
4181
        }
141✔
4182

4183
        // The rest of the data is optional, and will only be there if we got a node
4184
        // announcement for this node.
4185
        if !node.HaveNodeAnnouncement {
8,599✔
4186
                return node, nil
141✔
4187
        }
141✔
4188

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

4201
        node.Alias, err = wire.ReadVarString(r, 0)
8,319✔
4202
        if err != nil {
8,319✔
4203
                return LightningNode{}, err
×
4204
        }
×
4205

4206
        err = node.Features.Decode(r)
8,319✔
4207
        if err != nil {
8,319✔
4208
                return LightningNode{}, err
×
4209
        }
×
4210

4211
        if _, err := r.Read(scratch[:2]); err != nil {
8,319✔
4212
                return LightningNode{}, err
×
4213
        }
×
4214
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,319✔
4215

8,319✔
4216
        var addresses []net.Addr
8,319✔
4217
        for i := 0; i < numAddresses; i++ {
18,862✔
4218
                address, err := deserializeAddr(r)
10,543✔
4219
                if err != nil {
10,543✔
4220
                        return LightningNode{}, err
×
4221
                }
×
4222
                addresses = append(addresses, address)
10,543✔
4223
        }
4224
        node.Addresses = addresses
8,319✔
4225

8,319✔
4226
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,319✔
4227
        if err != nil {
8,319✔
4228
                return LightningNode{}, err
×
4229
        }
×
4230

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

4243
        return node, nil
8,319✔
4244
}
4245

4246
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4247
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,467✔
4248

1,467✔
4249
        var b bytes.Buffer
1,467✔
4250

1,467✔
4251
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,467✔
4252
                return err
×
4253
        }
×
4254
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,467✔
4255
                return err
×
4256
        }
×
4257
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,467✔
4258
                return err
×
4259
        }
×
4260
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,467✔
4261
                return err
×
4262
        }
×
4263

4264
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,467✔
4265
                return err
×
4266
        }
×
4267

4268
        authProof := edgeInfo.AuthProof
1,467✔
4269
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,467✔
4270
        if authProof != nil {
2,851✔
4271
                nodeSig1 = authProof.NodeSig1Bytes
1,384✔
4272
                nodeSig2 = authProof.NodeSig2Bytes
1,384✔
4273
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,384✔
4274
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,384✔
4275
        }
1,384✔
4276

4277
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,467✔
4278
                return err
×
4279
        }
×
4280
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,467✔
4281
                return err
×
4282
        }
×
4283
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,467✔
4284
                return err
×
4285
        }
×
4286
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,467✔
4287
                return err
×
4288
        }
×
4289

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

4303
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,467✔
4304
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4305
        }
×
4306
        err := wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,467✔
4307
        if err != nil {
1,467✔
4308
                return err
×
4309
        }
×
4310

4311
        return edgeIndex.Put(chanID[:], b.Bytes())
1,467✔
4312
}
4313

4314
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4315
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,182✔
4316

4,182✔
4317
        edgeInfoBytes := edgeIndex.Get(chanID)
4,182✔
4318
        if edgeInfoBytes == nil {
4,269✔
4319
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
87✔
4320
        }
87✔
4321

4322
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,097✔
4323
        return deserializeChanEdgeInfo(edgeInfoReader)
4,097✔
4324
}
4325

4326
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,728✔
4327
        var (
4,728✔
4328
                err      error
4,728✔
4329
                edgeInfo models.ChannelEdgeInfo
4,728✔
4330
        )
4,728✔
4331

4,728✔
4332
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,728✔
4333
                return models.ChannelEdgeInfo{}, err
×
4334
        }
×
4335
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,728✔
4336
                return models.ChannelEdgeInfo{}, err
×
4337
        }
×
4338
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,728✔
4339
                return models.ChannelEdgeInfo{}, err
×
4340
        }
×
4341
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,728✔
4342
                return models.ChannelEdgeInfo{}, err
×
4343
        }
×
4344

4345
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,728✔
4346
        if err != nil {
4,728✔
4347
                return models.ChannelEdgeInfo{}, err
×
4348
        }
×
4349

4350
        proof := &models.ChannelAuthProof{}
4,728✔
4351

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

4369
        if !proof.IsEmpty() {
6,503✔
4370
                edgeInfo.AuthProof = proof
1,775✔
4371
        }
1,775✔
4372

4373
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,728✔
4374
        if err := readOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,728✔
4375
                return models.ChannelEdgeInfo{}, err
×
4376
        }
×
4377
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,728✔
4378
                return models.ChannelEdgeInfo{}, err
×
4379
        }
×
4380
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,728✔
4381
                return models.ChannelEdgeInfo{}, err
×
4382
        }
×
4383

4384
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,728✔
4385
                return models.ChannelEdgeInfo{}, err
×
4386
        }
×
4387

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

4400
        return edgeInfo, nil
4,728✔
4401
}
4402

4403
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4404
        from, to []byte) error {
2,630✔
4405

2,630✔
4406
        var edgeKey [33 + 8]byte
2,630✔
4407
        copy(edgeKey[:], from)
2,630✔
4408
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,630✔
4409

2,630✔
4410
        var b bytes.Buffer
2,630✔
4411
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,630✔
4412
                return err
×
4413
        }
×
4414

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

2,630✔
4422
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,630✔
4423
        if err != nil {
2,630✔
4424
                return err
×
4425
        }
×
4426

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

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

4450
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
26✔
4451

26✔
4452
                var oldIndexKey [8 + 8]byte
26✔
4453
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
26✔
4454
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
26✔
4455

26✔
4456
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
26✔
4457
                        return err
×
4458
                }
×
4459
        }
4460

4461
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,630✔
4462
                return err
×
4463
        }
×
4464

4465
        err = updateEdgePolicyDisabledIndex(
2,630✔
4466
                edges, edge.ChannelID,
2,630✔
4467
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,630✔
4468
                edge.IsDisabled(),
2,630✔
4469
        )
2,630✔
4470
        if err != nil {
2,630✔
NEW
4471
                return err
×
NEW
4472
        }
×
4473

4474
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,630✔
4475
}
4476

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

2,904✔
4489
        var disabledEdgeKey [8 + 1]byte
2,904✔
4490
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,904✔
4491
        if direction {
4,353✔
4492
                disabledEdgeKey[8] = 1
1,449✔
4493
        }
1,449✔
4494

4495
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,904✔
4496
                disabledEdgePolicyBucket,
2,904✔
4497
        )
2,904✔
4498
        if err != nil {
2,904✔
4499
                return err
×
4500
        }
×
4501

4502
        if disabled {
2,932✔
4503
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
28✔
4504
        }
28✔
4505

4506
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,878✔
4507
}
4508

4509
// putChanEdgePolicyUnknown marks the edge policy as unknown
4510
// in the edges bucket.
4511
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4512
        from []byte) error {
2,930✔
4513

2,930✔
4514
        var edgeKey [33 + 8]byte
2,930✔
4515
        copy(edgeKey[:], from)
2,930✔
4516
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,930✔
4517

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

4523
        return edges.Put(edgeKey[:], unknownPolicy)
2,930✔
4524
}
4525

4526
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4527
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,164✔
4528

8,164✔
4529
        var edgeKey [33 + 8]byte
8,164✔
4530
        copy(edgeKey[:], nodePub)
8,164✔
4531
        copy(edgeKey[33:], chanID[:])
8,164✔
4532

8,164✔
4533
        edgeBytes := edges.Get(edgeKey[:])
8,164✔
4534
        if edgeBytes == nil {
8,164✔
4535
                return nil, ErrEdgeNotFound
×
4536
        }
×
4537

4538
        // No need to deserialize unknown policy.
4539
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,535✔
4540
                return nil, nil
371✔
4541
        }
371✔
4542

4543
        edgeReader := bytes.NewReader(edgeBytes)
7,795✔
4544

7,795✔
4545
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,795✔
4546
        switch {
7,795✔
4547
        // If the db policy was missing an expected optional field, we return
4548
        // nil as if the policy was unknown.
4549
        case err == ErrEdgePolicyOptionalFieldNotFound:
1✔
4550
                return nil, nil
1✔
4551

4552
        case err != nil:
×
4553
                return nil, err
×
4554
        }
4555

4556
        return ep, nil
7,794✔
4557
}
4558

4559
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4560
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4561
        error) {
239✔
4562

239✔
4563
        edgeInfo := edgeIndex.Get(chanID)
239✔
4564
        if edgeInfo == nil {
239✔
4565
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4566
                        chanID)
×
4567
        }
×
4568

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

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

4588
        return edge1, edge2, nil
239✔
4589
}
4590

4591
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4592
        to []byte) error {
2,632✔
4593

2,632✔
4594
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,632✔
4595
        if err != nil {
2,632✔
4596
                return err
×
4597
        }
×
4598

4599
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,632✔
4600
                return err
×
4601
        }
×
4602

4603
        var scratch [8]byte
2,632✔
4604
        updateUnix := uint64(edge.LastUpdate.Unix())
2,632✔
4605
        byteOrder.PutUint64(scratch[:], updateUnix)
2,632✔
4606
        if _, err := w.Write(scratch[:]); err != nil {
2,632✔
4607
                return err
×
4608
        }
×
4609

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

4629
        if _, err := w.Write(to); err != nil {
2,632✔
4630
                return err
×
4631
        }
×
4632

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

4645
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,632✔
4646
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4647
        }
×
4648
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,632✔
4649
                return err
×
4650
        }
×
4651

4652
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,632✔
4653
                return err
×
4654
        }
×
4655
        return nil
2,632✔
4656
}
4657

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

×
4665
                return nil, deserializeErr
×
4666
        }
×
4667

4668
        return edge, deserializeErr
7,820✔
4669
}
4670

4671
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4672
        error) {
8,827✔
4673

8,827✔
4674
        edge := &models.ChannelEdgePolicy{}
8,827✔
4675

8,827✔
4676
        var err error
8,827✔
4677
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,827✔
4678
        if err != nil {
8,827✔
4679
                return nil, err
×
4680
        }
×
4681

4682
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,827✔
4683
                return nil, err
×
4684
        }
×
4685

4686
        var scratch [8]byte
8,827✔
4687
        if _, err := r.Read(scratch[:]); err != nil {
8,827✔
4688
                return nil, err
×
4689
        }
×
4690
        unix := int64(byteOrder.Uint64(scratch[:]))
8,827✔
4691
        edge.LastUpdate = time.Unix(unix, 0)
8,827✔
4692

8,827✔
4693
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,827✔
4694
                return nil, err
×
4695
        }
×
4696
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,827✔
4697
                return nil, err
×
4698
        }
×
4699
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,827✔
4700
                return nil, err
×
4701
        }
×
4702

4703
        var n uint64
8,827✔
4704
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,827✔
4705
                return nil, err
×
4706
        }
×
4707
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,827✔
4708

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

8,827✔
4714
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,827✔
4715
                return nil, err
×
4716
        }
×
4717
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,827✔
4718

8,827✔
4719
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,827✔
4720
                return nil, err
×
4721
        }
×
4722

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

4735
        // See if optional fields are present.
4736
        if edge.MessageFlags.HasMaxHtlc() {
17,274✔
4737
                // The max_htlc field should be at the beginning of the opaque
8,447✔
4738
                // bytes.
8,447✔
4739
                opq := edge.ExtraOpaqueData
8,447✔
4740

8,447✔
4741
                // If the max_htlc field is not present, it might be old data
8,447✔
4742
                // stored before this field was validated. We'll return the
8,447✔
4743
                // edge along with an error.
8,447✔
4744
                if len(opq) < 8 {
8,450✔
4745
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4746
                }
3✔
4747

4748
                maxHtlc := byteOrder.Uint64(opq[:8])
8,444✔
4749
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,444✔
4750

8,444✔
4751
                // Exclude the parsed field from the rest of the opaque data.
8,444✔
4752
                edge.ExtraOpaqueData = opq[8:]
8,444✔
4753
        }
4754

4755
        return edge, nil
8,824✔
4756
}
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