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

lightningnetwork / lnd / 12041760086

27 Nov 2024 01:02AM UTC coverage: 59.001% (+0.002%) from 58.999%
12041760086

Pull #9242

github

aakselrod
github workflow: save postgres log to zip file
Pull Request #9242: Reapply #8644

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

82 existing lines in 18 files now uncovered.

133176 of 225719 relevant lines covered (59.0%)

19559.01 hits per line

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

77.09
/channeldb/graph.go
1
package channeldb
2

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

400
        return nil
1,879✔
401
}
402

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

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

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

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

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

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

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

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

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

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

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

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

697✔
479
        if c.graphCache != nil {
1,157✔
480
                return c.graphCache.ForEachChannel(node, cb)
460✔
481
        }
460✔
482

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

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

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

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

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

493✔
522
                if node == e.NodeKey2Bytes {
744✔
523
                        directedChannel.OtherNode = e.NodeKey1Bytes
251✔
524
                }
251✔
525

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

1,126✔
536
        if c.graphCache != nil {
1,577✔
537
                return c.graphCache.GetFeatures(node), nil
451✔
538
        }
451✔
539

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1030
                f(r)
4✔
1031
        }
1032

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

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

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

1068
        if c.graphCache != nil {
2,758✔
1069
                c.graphCache.AddChannel(edge, nil, nil)
1,288✔
1070
        }
1,288✔
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,470✔
1077
        switch {
1,470✔
1078
        case node1Err == ErrGraphNodeNotFound:
22✔
1079
                node1Shell := LightningNode{
22✔
1080
                        PubKeyBytes:          edge.NodeKey1Bytes,
22✔
1081
                        HaveNodeAnnouncement: false,
22✔
1082
                }
22✔
1083
                err := addLightningNode(tx, &node1Shell)
22✔
1084
                if err != nil {
22✔
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,470✔
1093
        switch {
1,470✔
1094
        case node2Err == ErrGraphNodeNotFound:
58✔
1095
                node2Shell := LightningNode{
58✔
1096
                        PubKeyBytes:          edge.NodeKey2Bytes,
58✔
1097
                        HaveNodeAnnouncement: false,
58✔
1098
                }
58✔
1099
                err := addLightningNode(tx, &node2Shell)
58✔
1100
                if err != nil {
58✔
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,470✔
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,470✔
1118
                &edge.NodeKey1Bytes,
1,470✔
1119
                &edge.NodeKey2Bytes,
1,470✔
1120
        }
1,470✔
1121
        for _, key := range keys {
4,406✔
1122
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,936✔
1123
                if err != nil {
2,936✔
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,470✔
1131
        if err := writeOutpoint(&b, &edge.ChannelPoint); err != nil {
1,470✔
1132
                return err
×
1133
        }
×
1134
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,470✔
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) {
225✔
1145

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

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

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

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

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

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

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

1202
                        return nil
103✔
1203
                }
1204

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

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

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

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

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

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

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

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

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

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

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

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

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

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

122✔
1337
                        var opBytes bytes.Buffer
122✔
1338
                        if err := writeOutpoint(&opBytes, chanPoint); err != nil {
122✔
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())
122✔
1345
                        if chanID == nil {
221✔
1346
                                continue
99✔
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)
27✔
1353
                        if err != nil {
27✔
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(
27✔
1362
                                edges, edgeIndex, chanIndex, zombieIndex,
27✔
1363
                                chanID, false, false,
27✔
1364
                        )
27✔
1365
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
27✔
1366
                                return err
×
1367
                        }
×
1368

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

65✔
1538
                numNodesPruned++
65✔
1539
        }
1540

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

1546
        return nil
270✔
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) {
158✔
1558

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

40✔
1714
                return nil
40✔
1715
        }, func() {})
59✔
1716
        if err != nil {
82✔
1717
                return nil, 0, err
23✔
1718
        }
23✔
1719

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

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

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

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

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

1775
                return nil
87✔
1776
        }, func() {})
149✔
1777
        if err != nil {
211✔
1778
                return err
62✔
1779
        }
62✔
1780

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

1786
        return nil
87✔
1787
}
1788

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2021
                return nil
142✔
2022
        }, func() {
142✔
2023
                edgesSeen = make(map[uint64]struct{})
142✔
2024
                edgesToCache = make(map[uint64]ChannelEdge)
142✔
2025
                edgesInHorizon = nil
142✔
2026
        })
142✔
2027
        switch {
142✔
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)
22✔
2040
        }
22✔
2041

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

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

12✔
2056
        var nodesInHorizon []LightningNode
12✔
2057

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

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

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

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

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

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

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

127✔
2121
        var newChanIDs []uint64
127✔
2122

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

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

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

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

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

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

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

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

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

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

222✔
2254
        if node1Timestamp.IsZero() {
434✔
2255
                chanInfo.Node1UpdateTimestamp = time.Unix(0, 0)
212✔
2256
        }
212✔
2257

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

2262
        return chanInfo
222✔
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) {
15✔
2287

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

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

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

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

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

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

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

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

48✔
2342
                        if !withTimestamps {
70✔
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)
26✔
2352

26✔
2353
                        rawPolicy := edges.Get(node1Key)
26✔
2354
                        if len(rawPolicy) != 0 {
36✔
2355
                                r := bytes.NewReader(rawPolicy)
10✔
2356

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

×
2362
                                        return err
×
2363
                                }
×
2364

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

2368
                        rawPolicy = edges.Get(node2Key)
26✔
2369
                        if len(rawPolicy) != 0 {
41✔
2370
                                r := bytes.NewReader(rawPolicy)
15✔
2371

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

×
2377
                                        return err
×
2378
                                }
×
2379

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2521
                return chanEdges, nil
8✔
2522
        }
2523

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

2529
        return chanEdges, nil
28✔
2530
}
2531

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

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

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

2567
        return nil
144✔
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 {
206✔
2580

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

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

144✔
2611
        // With the latter half constructed, copy over the first public key to
144✔
2612
        // delete the edge in this direction, then the second to delete the
144✔
2613
        // edge in the opposite direction.
144✔
2614
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
144✔
2615
        if edges.Get(edgeKey[:]) != nil {
288✔
2616
                if err := edges.Delete(edgeKey[:]); err != nil {
144✔
2617
                        return err
×
2618
                }
×
2619
        }
2620
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
144✔
2621
        if edges.Get(edgeKey[:]) != nil {
288✔
2622
                if err := edges.Delete(edgeKey[:]); err != nil {
144✔
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)
144✔
2630
        if err != nil {
144✔
NEW
2631
                return err
×
NEW
2632
        }
×
2633
        err = updateEdgePolicyDisabledIndex(edges, cid, true, false)
144✔
2634
        if err != nil {
144✔
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 {
144✔
2641
                return err
×
2642
        }
×
2643
        var b bytes.Buffer
144✔
2644
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
144✔
2645
                return err
×
2646
        }
×
2647
        if err := chanIndex.Delete(b.Bytes()); err != nil {
144✔
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 {
264✔
2655
                return nil
120✔
2656
        }
120✔
2657

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

2663
        return markEdgeZombie(
28✔
2664
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
28✔
2665
        )
28✔
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) {
4✔
2686

4✔
2687
        switch {
4✔
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.
2690
        case e1 == nil && e2 == nil:
1✔
2691
                return info.NodeKey1Bytes, info.NodeKey2Bytes
1✔
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,635✔
2717

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

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

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

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

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

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

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

2,632✔
2766
        // If an entry for this channel is found in reject cache, we'll modify
2,632✔
2767
        // the entry with the updated timestamp for the direction that was just
2,632✔
2768
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,632✔
2769
        // during the next query for this edge.
2,632✔
2770
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,641✔
2771
                if isUpdate1 {
16✔
2772
                        entry.upd1Time = e.LastUpdate.Unix()
7✔
2773
                } else {
13✔
2774
                        entry.upd2Time = e.LastUpdate.Unix()
6✔
2775
                }
6✔
2776
                c.rejectCache.insert(e.ChannelID, entry)
9✔
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,636✔
2784
                if isUpdate1 {
8✔
2785
                        channel.Policy1 = e
4✔
2786
                } else {
8✔
2787
                        channel.Policy2 = e
4✔
2788
                }
4✔
2789
                c.chanCache.insert(e.ChannelID, channel)
4✔
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,635✔
2799

2,635✔
2800
        edges := tx.ReadWriteBucket(edgeBucket)
2,635✔
2801
        if edges == nil {
2,635✔
2802
                return false, ErrEdgeNotFound
×
2803
        }
×
2804
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,635✔
2805
        if edgeIndex == nil {
2,635✔
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,635✔
2812
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,635✔
2813

2,635✔
2814
        // With the channel ID, we then fetch the value storing the two
2,635✔
2815
        // nodes which connect this channel edge.
2,635✔
2816
        nodeInfo := edgeIndex.Get(chanID[:])
2,635✔
2817
        if nodeInfo == nil {
2,638✔
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,632✔
2824
        var isUpdate1 bool
2,632✔
2825
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3,952✔
2826
                fromNode = nodeInfo[:33]
1,320✔
2827
                toNode = nodeInfo[33:66]
1,320✔
2828
                isUpdate1 = true
1,320✔
2829
        } else {
2,636✔
2830
                fromNode = nodeInfo[33:66]
1,316✔
2831
                toNode = nodeInfo[:33]
1,316✔
2832
                isUpdate1 = false
1,316✔
2833
        }
1,316✔
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,632✔
2838
        if err != nil {
2,632✔
2839
                return false, err
×
2840
        }
×
2841

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

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

2855
        return isUpdate1, nil
2,632✔
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,463✔
2913
        if l.pubKey != nil {
1,952✔
2914
                return l.pubKey, nil
489✔
2915
        }
489✔
2916

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

978✔
2923
        return key, nil
978✔
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) {
64✔
2938
        l.pubKey = key
64✔
2939
        copy(l.PubKeyBytes[:], key.SerializeCompressed())
64✔
2940
}
64✔
2941

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

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

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

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

18✔
2965
        if !signed {
22✔
2966
                return nodeAnn, nil
4✔
2967
        }
4✔
2968

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

2974
        nodeAnn.Signature = sig
18✔
2975

18✔
2976
        return nodeAnn, nil
18✔
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) {
17✔
2984

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

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

7✔
3002
                        nodeIsPublic = true
7✔
3003
                        return errDone
7✔
3004
                }
7✔
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 {
21✔
3009
                        nodeIsPublic = true
10✔
3010
                        return errDone
10✔
3011
                }
10✔
3012

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

3020
        return nodeIsPublic, nil
17✔
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) {
830✔
3038

830✔
3039
        return c.fetchLightningNode(nil, nodePub)
830✔
3040
}
830✔
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,774✔
3048

3,774✔
3049
        var node *LightningNode
3,774✔
3050
        fetch := func(tx kvdb.RTx) error {
7,548✔
3051
                // First grab the nodes bucket which stores the mapping from
3,774✔
3052
                // pubKey to node information.
3,774✔
3053
                nodes := tx.ReadBucket(nodeBucket)
3,774✔
3054
                if nodes == nil {
3,774✔
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,774✔
3061
                if nodeBytes == nil {
3,786✔
3062
                        return ErrGraphNodeNotFound
12✔
3063
                }
12✔
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,766✔
3068
                n, err := deserializeLightningNode(nodeReader)
3,766✔
3069
                if err != nil {
3,766✔
3070
                        return err
×
3071
                }
×
3072

3073
                node = &n
3,766✔
3074

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

3078
        if tx == nil {
4,604✔
3079
                err := kvdb.View(
830✔
3080
                        c.db, fetch, func() {
1,660✔
3081
                                node = nil
830✔
3082
                        },
830✔
3083
                )
3084
                if err != nil {
842✔
3085
                        return nil, err
12✔
3086
                }
12✔
3087

3088
                return node, nil
822✔
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 {
729✔
3109

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

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

3121
// Features returns the node's features.
3122
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
709✔
3123
        return n.features
709✔
3124
}
709✔
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 {
629✔
3137

629✔
3138
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
629✔
3139
}
629✔
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) {
20✔
3149
        var (
20✔
3150
                updateTime time.Time
20✔
3151
                exists     bool
20✔
3152
        )
20✔
3153

20✔
3154
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
40✔
3155
                // First grab the nodes bucket which stores the mapping from
20✔
3156
                // pubKey to node information.
20✔
3157
                nodes := tx.ReadBucket(nodeBucket)
20✔
3158
                if nodes == nil {
20✔
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[:])
20✔
3165
                if nodeBytes == nil {
27✔
3166
                        exists = false
7✔
3167
                        return nil
7✔
3168
                }
7✔
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)
17✔
3174
                node, err := deserializeLightningNode(nodeReader)
17✔
3175
                if err != nil {
17✔
3176
                        return err
×
3177
                }
×
3178

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

3190
        return updateTime, exists, nil
20✔
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,870✔
3198

1,870✔
3199
        traversal := func(tx kvdb.RTx) error {
3,740✔
3200
                edges := tx.ReadBucket(edgeBucket)
1,870✔
3201
                if edges == nil {
1,870✔
3202
                        return ErrGraphNotFound
×
3203
                }
×
3204
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,870✔
3205
                if edgeIndex == nil {
1,870✔
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,870✔
3217
                copy(nodeStart[:], nodePub)
1,870✔
3218
                copy(nodeStart[33:], chanStart[:])
1,870✔
3219

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

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

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

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

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

3262
                return nil
1,861✔
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,883✔
3268
                return kvdb.View(db, traversal, func() {})
26✔
3269
        }
3270

3271
        // Otherwise, we re-use the existing transaction to execute the graph
3272
        // traversal.
3273
        return traversal(tx)
1,861✔
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 {
10✔
3287

10✔
3288
        return nodeTraversal(nil, nodePub[:], c.db, cb)
10✔
3289
}
10✔
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,002✔
3308

1,002✔
3309
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,002✔
3310
}
1,002✔
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) {
4✔
3319

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

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

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

3345
                targetNode = &node
4✔
3346

4✔
3347
                return nil
4✔
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
4✔
3353
        if tx == nil {
4✔
3354
                err = kvdb.View(c.db, fetchNodeFunc, func() { targetNode = nil })
×
3355
        } else {
4✔
3356
                err = fetchNodeFunc(tx)
4✔
3357
        }
4✔
3358

3359
        return targetNode, err
4✔
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) {
26✔
3366
        var (
26✔
3367
                node1Key [33 + 8]byte
26✔
3368
                node2Key [33 + 8]byte
26✔
3369
        )
26✔
3370

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

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

26✔
3377
        return node1Key[:], node2Key[:]
26✔
3378
}
26✔
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) {
15✔
3388

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

15✔
3395
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
30✔
3396
                // First, grab the node bucket. This will be used to populate
15✔
3397
                // the Node pointers in each edge read from disk.
15✔
3398
                nodes := tx.ReadBucket(nodeBucket)
15✔
3399
                if nodes == nil {
15✔
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)
15✔
3407
                if edges == nil {
15✔
3408
                        return ErrGraphNoEdgesFound
×
3409
                }
×
3410
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
15✔
3411
                if edgeIndex == nil {
15✔
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)
15✔
3418
                if chanIndex == nil {
15✔
3419
                        return ErrGraphNoEdgesFound
×
3420
                }
×
3421
                var b bytes.Buffer
15✔
3422
                if err := writeOutpoint(&b, op); err != nil {
15✔
3423
                        return err
×
3424
                }
×
3425
                chanID := chanIndex.Get(b.Bytes())
15✔
3426
                if chanID == nil {
29✔
3427
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
14✔
3428
                }
14✔
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)
5✔
3433
                if err != nil {
5✔
3434
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3435
                }
×
3436
                edgeInfo = &edge
5✔
3437

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

3446
                policy1 = e1
5✔
3447
                policy2 = e2
5✔
3448
                return nil
5✔
3449
        }, func() {
15✔
3450
                edgeInfo = nil
15✔
3451
                policy1 = nil
15✔
3452
                policy2 = nil
15✔
3453
        })
15✔
3454
        if err != nil {
29✔
3455
                return nil, nil, nil, err
14✔
3456
        }
14✔
3457

3458
        return edgeInfo, policy1, policy2, nil
5✔
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) {
29✔
3473

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

29✔
3481
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
58✔
3482
                // First, grab the node bucket. This will be used to populate
29✔
3483
                // the Node pointers in each edge read from disk.
29✔
3484
                nodes := tx.ReadBucket(nodeBucket)
29✔
3485
                if nodes == nil {
29✔
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)
29✔
3493
                if edges == nil {
29✔
3494
                        return ErrGraphNoEdgesFound
×
3495
                }
×
3496
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
29✔
3497
                if edgeIndex == nil {
29✔
3498
                        return ErrGraphNoEdgesFound
×
3499
                }
×
3500

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

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

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

3517
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
5✔
3518
                                zombieIndex, chanID,
5✔
3519
                        )
5✔
3520
                        if !isZombie {
9✔
3521
                                return ErrEdgeNotFound
4✔
3522
                        }
4✔
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{
5✔
3529
                                NodeKey1Bytes: pubKey1,
5✔
3530
                                NodeKey2Bytes: pubKey2,
5✔
3531
                        }
5✔
3532
                        return ErrZombieEdge
5✔
3533
                }
3534

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

3540
                edgeInfo = &edge
28✔
3541

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

3551
                policy1 = e1
28✔
3552
                policy2 = e2
28✔
3553
                return nil
28✔
3554
        }, func() {
29✔
3555
                edgeInfo = nil
29✔
3556
                policy1 = nil
29✔
3557
                policy2 = nil
29✔
3558
        })
29✔
3559
        if err == ErrZombieEdge {
34✔
3560
                return edgeInfo, nil, nil, err
5✔
3561
        }
5✔
3562
        if err != nil {
32✔
3563
                return nil, nil, nil, err
4✔
3564
        }
4✔
3565

3566
        return edgeInfo, policy1, policy2, nil
28✔
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) {
17✔
3573
        var nodeIsPublic bool
17✔
3574
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
34✔
3575
                nodes := tx.ReadBucket(nodeBucket)
17✔
3576
                if nodes == nil {
17✔
3577
                        return ErrGraphNodesNotFound
×
3578
                }
×
3579
                ourPubKey := nodes.Get(sourceKey)
17✔
3580
                if ourPubKey == nil {
17✔
3581
                        return ErrSourceNodeNotSet
×
3582
                }
×
3583
                node, err := fetchLightningNode(nodes, pubKey[:])
17✔
3584
                if err != nil {
17✔
3585
                        return err
×
3586
                }
×
3587

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

3597
        return nodeIsPublic, nil
17✔
3598
}
3599

3600
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3601
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
50✔
3602
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
50✔
3603
        if err != nil {
50✔
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(
50✔
3611
                txscript.WithScriptAllocSize(input.P2WSHSize),
50✔
3612
        )
50✔
3613
        bldr.AddOp(txscript.OP_0)
50✔
3614
        scriptHash := sha256.Sum256(witnessScript)
50✔
3615
        bldr.AddData(scriptHash[:])
50✔
3616

50✔
3617
        return bldr.Script()
50✔
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) {
27✔
3643
        var edgePoints []EdgePoint
27✔
3644
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
54✔
3645
                // We're going to iterate over the entire channel index, so
27✔
3646
                // we'll need to fetch the edgeBucket to get to the index as
27✔
3647
                // it's a sub-bucket.
27✔
3648
                edges := tx.ReadBucket(edgeBucket)
27✔
3649
                if edges == nil {
27✔
3650
                        return ErrGraphNoEdgesFound
×
3651
                }
×
3652
                chanIndex := edges.NestedReadBucket(channelPointBucket)
27✔
3653
                if chanIndex == nil {
27✔
3654
                        return ErrGraphNoEdgesFound
×
3655
                }
×
3656
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
27✔
3657
                if edgeIndex == nil {
27✔
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 {
73✔
3665
                        chanPointReader := bytes.NewReader(chanPointBytes)
46✔
3666

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

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

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

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

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

3701
        return edgePoints, nil
27✔
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 {
122✔
3709

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

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

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

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

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

122✔
3737
        return nil
122✔
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 {
150✔
3745

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

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

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

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

6✔
3761
        return c.markEdgeLiveUnsafe(nil, chanID)
6✔
3762
}
6✔
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 {
34✔
3771
        dbFn := func(tx kvdb.RwTx) error {
68✔
3772
                edges := tx.ReadWriteBucket(edgeBucket)
34✔
3773
                if edges == nil {
34✔
3774
                        return ErrGraphNoEdgesFound
×
3775
                }
×
3776
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
34✔
3777
                if zombieIndex == nil {
34✔
3778
                        return nil
×
3779
                }
×
3780

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

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

3788
                return zombieIndex.Delete(k[:])
33✔
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
34✔
3794
        if tx == nil {
40✔
3795
                err = kvdb.Update(c.db, dbFn, func() {})
12✔
3796
        } else {
28✔
3797
                err = dbFn(tx)
28✔
3798
        }
28✔
3799
        if err != nil {
35✔
3800
                return err
1✔
3801
        }
1✔
3802

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

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

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

3822
        return nil
33✔
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) {
218✔
3863

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

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

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

94✔
3876
        return true, pubKey1, pubKey2
94✔
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) {
6✔
3927
        var isClosed bool
6✔
3928
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
3929
                closedScids := tx.ReadBucket(closedScidBucket)
6✔
3930
                if closedScids == nil {
6✔
3931
                        return ErrClosedScidsNotFound
×
3932
                }
×
3933

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

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

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

3950
        return isClosed, nil
6✔
3951
}
3952

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

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

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

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

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

3978
        if _, err := b.Write(nodePub); err != nil {
977✔
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,054✔
3985
                // Write HaveNodeAnnouncement=0.
77✔
3986
                byteOrder.PutUint16(scratch[:2], 0)
77✔
3987
                if _, err := b.Write(scratch[:2]); err != nil {
77✔
3988
                        return err
×
3989
                }
×
3990

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

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

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

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

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

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

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

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

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

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

4049
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
904✔
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
904✔
4056
        byteOrder.PutUint64(indexKey[:8], updateUnix)
904✔
4057
        copy(indexKey[8:], nodePub)
904✔
4058

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

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

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

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

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

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

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

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

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

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

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

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

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

124✔
4120
        // The rest of the data is optional, and will only be there if we got a
124✔
4121
        // node announcement for this node.
124✔
4122
        if hasNodeAnn == 0 {
128✔
4123
                return node, nil
4✔
4124
        }
4✔
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
124✔
4129
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
124✔
4130
                return nil, err
×
4131
        }
×
4132
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
124✔
4133
                return nil, err
×
4134
        }
×
4135
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
124✔
4136
                return nil, err
×
4137
        }
×
4138

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

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

4147
        return node, nil
124✔
4148
}
4149

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

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

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

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

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

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

4176
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,468✔
4177
        if hasNodeAnn == 1 {
16,795✔
4178
                node.HaveNodeAnnouncement = true
8,327✔
4179
        } else {
8,472✔
4180
                node.HaveNodeAnnouncement = false
145✔
4181
        }
145✔
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,613✔
4186
                return node, nil
145✔
4187
        }
145✔
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,327✔
4192
                return LightningNode{}, err
×
4193
        }
×
4194
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,327✔
4195
                return LightningNode{}, err
×
4196
        }
×
4197
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,327✔
4198
                return LightningNode{}, err
×
4199
        }
×
4200

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

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

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

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

8,327✔
4226
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,327✔
4227
        if err != nil {
8,327✔
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,327✔
4234
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,327✔
4235
        )
8,327✔
4236
        switch {
8,327✔
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,327✔
4244
}
4245

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

4384
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,731✔
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,731✔
4391
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
4,731✔
4392
        )
4,731✔
4393
        switch {
4,731✔
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,731✔
4401
}
4402

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

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

2,632✔
4410
        var b bytes.Buffer
2,632✔
4411
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,632✔
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,632✔
4418
        var indexKey [8 + 8]byte
2,632✔
4419
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,632✔
4420
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,632✔
4421

2,632✔
4422
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,632✔
4423
        if err != nil {
2,632✔
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,632✔
4432
                !bytes.Equal(edgeBytes[:], unknownPolicy) {
2,660✔
4433

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

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

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

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

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

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

4474
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,632✔
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,912✔
4488

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

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

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

4506
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,886✔
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,936✔
4513

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

2,936✔
4518
        if edges.Get(edgeKey[:]) != nil {
2,936✔
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,936✔
4524
}
4525

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

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

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

4538
        // No need to deserialize unknown policy.
4539
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,549✔
4540
                return nil, nil
379✔
4541
        }
379✔
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) {
244✔
4562

244✔
4563
        edgeInfo := edgeIndex.Get(chanID)
244✔
4564
        if edgeInfo == nil {
244✔
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]
244✔
4573
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
244✔
4574
        if err != nil {
244✔
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]
244✔
4582
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
244✔
4583
        if err != nil {
244✔
4584
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4585
                        node2Pub)
×
4586
        }
×
4587

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

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

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

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

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

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

4629
        if _, err := w.Write(to); err != nil {
2,634✔
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,634✔
4638
        if edge.MessageFlags.HasMaxHtlc() {
4,884✔
4639
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,250✔
4640
                if err != nil {
2,250✔
4641
                        return err
×
4642
                }
×
4643
        }
4644

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

4652
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,634✔
4653
                return err
×
4654
        }
×
4655
        return nil
2,634✔
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