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

lightningnetwork / lnd / 9617502354

21 Jun 2024 05:27PM UTC coverage: 58.414% (+0.004%) from 58.41%
9617502354

Pull #8856

github

web-flow
[docs] Update go instructions

Building current lnd `0.18` fails with older go (`1.19.7`).

* Updated go download path to 1.22.4
* Updated hashes
* Added `rm -rf` instructions as per [go.dev instructions](https://go.dev/doc/install)
Pull Request #8856: [docs] Update go instructions

123389 of 211233 relevant lines covered (58.41%)

28572.17 hits per line

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

76.84
/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

158
const (
159
        // MaxAllowedExtraOpaqueBytes is the largest amount of opaque bytes that
160
        // we'll permit to be written to disk. We limit this as otherwise, it
161
        // would be possible for a node to create a ton of updates and slowly
162
        // fill our disk, and also waste bandwidth due to relaying.
163
        MaxAllowedExtraOpaqueBytes = 10000
164
)
165

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

179
        // cacheMu guards all caches (rejectCache, chanCache, graphCache). If
180
        // this mutex will be acquired at the same time as the DB mutex then
181
        // the cacheMu MUST be acquired first to prevent deadlock.
182
        cacheMu     sync.RWMutex
183
        rejectCache *rejectCache
184
        chanCache   *channelCache
185
        graphCache  *GraphCache
186

187
        chanScheduler batch.Scheduler
188
        nodeScheduler batch.Scheduler
189
}
190

191
// NewChannelGraph allocates a new ChannelGraph backed by a DB instance. The
192
// returned instance has its own unique reject cache and channel cache.
193
func NewChannelGraph(db kvdb.Backend, rejectCacheSize, chanCacheSize int,
194
        batchCommitInterval time.Duration, preAllocCacheNumNodes int,
195
        useGraphCache, noMigrations bool) (*ChannelGraph, error) {
1,844✔
196

1,844✔
197
        if !noMigrations {
3,688✔
198
                if err := initChannelGraph(db); err != nil {
1,844✔
199
                        return nil, err
×
200
                }
×
201
        }
202

203
        g := &ChannelGraph{
1,844✔
204
                db:          db,
1,844✔
205
                rejectCache: newRejectCache(rejectCacheSize),
1,844✔
206
                chanCache:   newChannelCache(chanCacheSize),
1,844✔
207
        }
1,844✔
208
        g.chanScheduler = batch.NewTimeScheduler(
1,844✔
209
                db, &g.cacheMu, batchCommitInterval,
1,844✔
210
        )
1,844✔
211
        g.nodeScheduler = batch.NewTimeScheduler(
1,844✔
212
                db, nil, batchCommitInterval,
1,844✔
213
        )
1,844✔
214

1,844✔
215
        // The graph cache can be turned off (e.g. for mobile users) for a
1,844✔
216
        // speed/memory usage tradeoff.
1,844✔
217
        if useGraphCache {
3,655✔
218
                g.graphCache = NewGraphCache(preAllocCacheNumNodes)
1,811✔
219
                startTime := time.Now()
1,811✔
220
                log.Debugf("Populating in-memory channel graph, this might " +
1,811✔
221
                        "take a while...")
1,811✔
222

1,811✔
223
                err := g.ForEachNodeCacheable(
1,811✔
224
                        func(tx kvdb.RTx, node GraphCacheNode) error {
1,915✔
225
                                g.graphCache.AddNodeFeatures(node)
104✔
226

104✔
227
                                return nil
104✔
228
                        },
104✔
229
                )
230
                if err != nil {
1,811✔
231
                        return nil, err
×
232
                }
×
233

234
                err = g.ForEachChannel(func(info *models.ChannelEdgeInfo,
1,811✔
235
                        policy1, policy2 *models.ChannelEdgePolicy) error {
2,211✔
236

400✔
237
                        g.graphCache.AddChannel(info, policy1, policy2)
400✔
238

400✔
239
                        return nil
400✔
240
                })
400✔
241
                if err != nil {
1,811✔
242
                        return nil, err
×
243
                }
×
244

245
                log.Debugf("Finished populating in-memory channel graph (took "+
1,811✔
246
                        "%v, %s)", time.Since(startTime), g.graphCache.Stats())
1,811✔
247
        }
248

249
        return g, nil
1,844✔
250
}
251

252
// channelMapKey is the key structure used for storing channel edge policies.
253
type channelMapKey struct {
254
        nodeKey route.Vertex
255
        chanID  [8]byte
256
}
257

258
// getChannelMap loads all channel edge policies from the database and stores
259
// them in a map.
260
func (c *ChannelGraph) getChannelMap(edges kvdb.RBucket) (
261
        map[channelMapKey]*models.ChannelEdgePolicy, error) {
1,815✔
262

1,815✔
263
        // Create a map to store all channel edge policies.
1,815✔
264
        channelMap := make(map[channelMapKey]*models.ChannelEdgePolicy)
1,815✔
265

1,815✔
266
        err := kvdb.ForAll(edges, func(k, edgeBytes []byte) error {
10,058✔
267
                // Skip embedded buckets.
8,243✔
268
                if bytes.Equal(k, edgeIndexBucket) ||
8,243✔
269
                        bytes.Equal(k, edgeUpdateIndexBucket) ||
8,243✔
270
                        bytes.Equal(k, zombieBucket) ||
8,243✔
271
                        bytes.Equal(k, disabledEdgePolicyBucket) ||
8,243✔
272
                        bytes.Equal(k, channelPointBucket) {
15,496✔
273

7,253✔
274
                        return nil
7,253✔
275
                }
7,253✔
276

277
                // Validate key length.
278
                if len(k) != 33+8 {
994✔
279
                        return fmt.Errorf("invalid edge key %x encountered", k)
×
280
                }
×
281

282
                var key channelMapKey
994✔
283
                copy(key.nodeKey[:], k[:33])
994✔
284
                copy(key.chanID[:], k[33:])
994✔
285

994✔
286
                // No need to deserialize unknown policy.
994✔
287
                if bytes.Equal(edgeBytes, unknownPolicy) {
994✔
288
                        return nil
×
289
                }
×
290

291
                edgeReader := bytes.NewReader(edgeBytes)
994✔
292
                edge, err := deserializeChanEdgePolicyRaw(
994✔
293
                        edgeReader,
994✔
294
                )
994✔
295

994✔
296
                switch {
994✔
297
                // If the db policy was missing an expected optional field, we
298
                // return nil as if the policy was unknown.
299
                case err == ErrEdgePolicyOptionalFieldNotFound:
×
300
                        return nil
×
301

302
                case err != nil:
×
303
                        return err
×
304
                }
305

306
                channelMap[key] = edge
994✔
307

994✔
308
                return nil
994✔
309
        })
310
        if err != nil {
1,815✔
311
                return nil, err
×
312
        }
×
313

314
        return channelMap, nil
1,815✔
315
}
316

317
var graphTopLevelBuckets = [][]byte{
318
        nodeBucket,
319
        edgeBucket,
320
        graphMetaBucket,
321
}
322

323
// Wipe completely deletes all saved state within all used buckets within the
324
// database. The deletion is done in a single transaction, therefore this
325
// operation is fully atomic.
326
func (c *ChannelGraph) Wipe() error {
×
327
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
328
                for _, tlb := range graphTopLevelBuckets {
×
329
                        err := tx.DeleteTopLevelBucket(tlb)
×
330
                        if err != nil && err != kvdb.ErrBucketNotFound {
×
331
                                return err
×
332
                        }
×
333
                }
334
                return nil
×
335
        }, func() {})
×
336
        if err != nil {
×
337
                return err
×
338
        }
×
339

340
        return initChannelGraph(c.db)
×
341
}
342

343
// createChannelDB creates and initializes a fresh version of channeldb. In
344
// the case that the target path has not yet been created or doesn't yet exist,
345
// then the path is created. Additionally, all required top-level buckets used
346
// within the database are created.
347
func initChannelGraph(db kvdb.Backend) error {
1,844✔
348
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
3,688✔
349
                for _, tlb := range graphTopLevelBuckets {
7,368✔
350
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
5,524✔
351
                                return err
×
352
                        }
×
353
                }
354

355
                nodes := tx.ReadWriteBucket(nodeBucket)
1,844✔
356
                _, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
1,844✔
357
                if err != nil {
1,844✔
358
                        return err
×
359
                }
×
360
                _, err = nodes.CreateBucketIfNotExists(nodeUpdateIndexBucket)
1,844✔
361
                if err != nil {
1,844✔
362
                        return err
×
363
                }
×
364

365
                edges := tx.ReadWriteBucket(edgeBucket)
1,844✔
366
                _, err = edges.CreateBucketIfNotExists(edgeIndexBucket)
1,844✔
367
                if err != nil {
1,844✔
368
                        return err
×
369
                }
×
370
                _, err = edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
1,844✔
371
                if err != nil {
1,844✔
372
                        return err
×
373
                }
×
374
                _, err = edges.CreateBucketIfNotExists(channelPointBucket)
1,844✔
375
                if err != nil {
1,844✔
376
                        return err
×
377
                }
×
378
                _, err = edges.CreateBucketIfNotExists(zombieBucket)
1,844✔
379
                if err != nil {
1,844✔
380
                        return err
×
381
                }
×
382

383
                graphMeta := tx.ReadWriteBucket(graphMetaBucket)
1,844✔
384
                _, err = graphMeta.CreateBucketIfNotExists(pruneLogBucket)
1,844✔
385
                return err
1,844✔
386
        }, func() {})
1,844✔
387
        if err != nil {
1,844✔
388
                return fmt.Errorf("unable to create new channel graph: %w", err)
×
389
        }
×
390

391
        return nil
1,844✔
392
}
393

394
// NewPathFindTx returns a new read transaction that can be used for a single
395
// path finding session. Will return nil if the graph cache is enabled.
396
func (c *ChannelGraph) NewPathFindTx() (kvdb.RTx, error) {
151✔
397
        if c.graphCache != nil {
241✔
398
                return nil, nil
90✔
399
        }
90✔
400

401
        return c.db.BeginReadTx()
61✔
402
}
403

404
// ForEachChannel iterates through all the channel edges stored within the
405
// graph and invokes the passed callback for each edge. The callback takes two
406
// edges as since this is a directed graph, both the in/out edges are visited.
407
// If the callback returns an error, then the transaction is aborted and the
408
// iteration stops early.
409
//
410
// NOTE: If an edge can't be found, or wasn't advertised, then a nil pointer
411
// for that particular channel edge routing policy will be passed into the
412
// callback.
413
func (c *ChannelGraph) ForEachChannel(cb func(*models.ChannelEdgeInfo,
414
        *models.ChannelEdgePolicy, *models.ChannelEdgePolicy) error) error {
1,815✔
415

1,815✔
416
        return c.db.View(func(tx kvdb.RTx) error {
3,630✔
417
                edges := tx.ReadBucket(edgeBucket)
1,815✔
418
                if edges == nil {
1,815✔
419
                        return ErrGraphNoEdgesFound
×
420
                }
×
421

422
                // First, load all edges in memory indexed by node and channel
423
                // id.
424
                channelMap, err := c.getChannelMap(edges)
1,815✔
425
                if err != nil {
1,815✔
426
                        return err
×
427
                }
×
428

429
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,815✔
430
                if edgeIndex == nil {
1,815✔
431
                        return ErrGraphNoEdgesFound
×
432
                }
×
433

434
                // Load edge index, recombine each channel with the policies
435
                // loaded above and invoke the callback.
436
                return kvdb.ForAll(edgeIndex, func(k, edgeInfoBytes []byte) error {
2,314✔
437
                        var chanID [8]byte
499✔
438
                        copy(chanID[:], k)
499✔
439

499✔
440
                        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
499✔
441
                        info, err := deserializeChanEdgeInfo(edgeInfoReader)
499✔
442
                        if err != nil {
499✔
443
                                return err
×
444
                        }
×
445

446
                        policy1 := channelMap[channelMapKey{
499✔
447
                                nodeKey: info.NodeKey1Bytes,
499✔
448
                                chanID:  chanID,
499✔
449
                        }]
499✔
450

499✔
451
                        policy2 := channelMap[channelMapKey{
499✔
452
                                nodeKey: info.NodeKey2Bytes,
499✔
453
                                chanID:  chanID,
499✔
454
                        }]
499✔
455

499✔
456
                        return cb(&info, policy1, policy2)
499✔
457
                })
458
        }, func() {})
1,815✔
459
}
460

461
// ForEachNodeDirectedChannel iterates through all channels of a given node,
462
// executing the passed callback on the directed edge representing the channel
463
// and its incoming policy. If the callback returns an error, then the iteration
464
// is halted with the error propagated back up to the caller.
465
//
466
// Unknown policies are passed into the callback as nil values.
467
func (c *ChannelGraph) ForEachNodeDirectedChannel(tx kvdb.RTx,
468
        node route.Vertex, cb func(channel *DirectedChannel) error) error {
592✔
469

592✔
470
        if c.graphCache != nil {
960✔
471
                return c.graphCache.ForEachChannel(node, cb)
368✔
472
        }
368✔
473

474
        // Fallback that uses the database.
475
        toNodeCallback := func() route.Vertex {
359✔
476
                return node
131✔
477
        }
131✔
478
        toNodeFeatures, err := c.FetchNodeFeatures(node)
228✔
479
        if err != nil {
228✔
480
                return err
×
481
        }
×
482

483
        dbCallback := func(tx kvdb.RTx, e *models.ChannelEdgeInfo, p1,
228✔
484
                p2 *models.ChannelEdgePolicy) error {
697✔
485

469✔
486
                var cachedInPolicy *models.CachedEdgePolicy
469✔
487
                if p2 != nil {
935✔
488
                        cachedInPolicy = models.NewCachedPolicy(p2)
466✔
489
                        cachedInPolicy.ToNodePubKey = toNodeCallback
466✔
490
                        cachedInPolicy.ToNodeFeatures = toNodeFeatures
466✔
491
                }
466✔
492

493
                var inboundFee lnwire.Fee
469✔
494
                if p1 != nil {
937✔
495
                        // Extract inbound fee. If there is a decoding error,
468✔
496
                        // skip this edge.
468✔
497
                        _, err := p1.ExtraOpaqueData.ExtractRecords(&inboundFee)
468✔
498
                        if err != nil {
469✔
499
                                return nil
1✔
500
                        }
1✔
501
                }
502

503
                directedChannel := &DirectedChannel{
468✔
504
                        ChannelID:    e.ChannelID,
468✔
505
                        IsNode1:      node == e.NodeKey1Bytes,
468✔
506
                        OtherNode:    e.NodeKey2Bytes,
468✔
507
                        Capacity:     e.Capacity,
468✔
508
                        OutPolicySet: p1 != nil,
468✔
509
                        InPolicy:     cachedInPolicy,
468✔
510
                        InboundFee:   inboundFee,
468✔
511
                }
468✔
512

468✔
513
                if node == e.NodeKey2Bytes {
710✔
514
                        directedChannel.OtherNode = e.NodeKey1Bytes
242✔
515
                }
242✔
516

517
                return cb(directedChannel)
468✔
518
        }
519
        return nodeTraversal(tx, node[:], c.db, dbCallback)
228✔
520
}
521

522
// FetchNodeFeatures returns the features of a given node. If no features are
523
// known for the node, an empty feature vector is returned.
524
func (c *ChannelGraph) FetchNodeFeatures(
525
        node route.Vertex) (*lnwire.FeatureVector, error) {
1,032✔
526

1,032✔
527
        if c.graphCache != nil {
1,412✔
528
                return c.graphCache.GetFeatures(node), nil
380✔
529
        }
380✔
530

531
        // Fallback that uses the database.
532
        targetNode, err := c.FetchLightningNode(nil, node)
656✔
533
        switch err {
656✔
534
        // If the node exists and has features, return them directly.
535
        case nil:
648✔
536
                return targetNode.Features, nil
648✔
537

538
        // If we couldn't find a node announcement, populate a blank feature
539
        // vector.
540
        case ErrGraphNodeNotFound:
8✔
541
                return lnwire.EmptyFeatureVector(), nil
8✔
542

543
        // Otherwise, bubble the error up.
544
        default:
×
545
                return nil, err
×
546
        }
547
}
548

549
// ForEachNodeCached is similar to ForEachNode, but it utilizes the channel
550
// graph cache instead. Note that this doesn't return all the information the
551
// regular ForEachNode method does.
552
//
553
// NOTE: The callback contents MUST not be modified.
554
func (c *ChannelGraph) ForEachNodeCached(cb func(node route.Vertex,
555
        chans map[uint64]*DirectedChannel) error) error {
1✔
556

1✔
557
        if c.graphCache != nil {
1✔
558
                return c.graphCache.ForEachNode(cb)
×
559
        }
×
560

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

20✔
568
                err := c.ForEachNodeChannel(tx, node.PubKeyBytes,
20✔
569
                        func(tx kvdb.RTx, e *models.ChannelEdgeInfo,
20✔
570
                                p1 *models.ChannelEdgePolicy,
20✔
571
                                p2 *models.ChannelEdgePolicy) error {
210✔
572

190✔
573
                                toNodeCallback := func() route.Vertex {
190✔
574
                                        return node.PubKeyBytes
×
575
                                }
×
576
                                toNodeFeatures, err := c.FetchNodeFeatures(
190✔
577
                                        node.PubKeyBytes,
190✔
578
                                )
190✔
579
                                if err != nil {
190✔
580
                                        return err
×
581
                                }
×
582

583
                                var cachedInPolicy *models.CachedEdgePolicy
190✔
584
                                if p2 != nil {
380✔
585
                                        cachedInPolicy =
190✔
586
                                                models.NewCachedPolicy(p2)
190✔
587
                                        cachedInPolicy.ToNodePubKey =
190✔
588
                                                toNodeCallback
190✔
589
                                        cachedInPolicy.ToNodeFeatures =
190✔
590
                                                toNodeFeatures
190✔
591
                                }
190✔
592

593
                                directedChannel := &DirectedChannel{
190✔
594
                                        ChannelID: e.ChannelID,
190✔
595
                                        IsNode1: node.PubKeyBytes ==
190✔
596
                                                e.NodeKey1Bytes,
190✔
597
                                        OtherNode:    e.NodeKey2Bytes,
190✔
598
                                        Capacity:     e.Capacity,
190✔
599
                                        OutPolicySet: p1 != nil,
190✔
600
                                        InPolicy:     cachedInPolicy,
190✔
601
                                }
190✔
602

190✔
603
                                if node.PubKeyBytes == e.NodeKey2Bytes {
285✔
604
                                        directedChannel.OtherNode =
95✔
605
                                                e.NodeKey1Bytes
95✔
606
                                }
95✔
607

608
                                channels[e.ChannelID] = directedChannel
190✔
609

190✔
610
                                return nil
190✔
611
                        })
612
                if err != nil {
20✔
613
                        return err
×
614
                }
×
615

616
                return cb(node.PubKeyBytes, channels)
20✔
617
        })
618
}
619

620
// DisabledChannelIDs returns the channel ids of disabled channels.
621
// A channel is disabled when two of the associated ChanelEdgePolicies
622
// have their disabled bit on.
623
func (c *ChannelGraph) DisabledChannelIDs() ([]uint64, error) {
6✔
624
        var disabledChanIDs []uint64
6✔
625
        var chanEdgeFound map[uint64]struct{}
6✔
626

6✔
627
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
628
                edges := tx.ReadBucket(edgeBucket)
6✔
629
                if edges == nil {
6✔
630
                        return ErrGraphNoEdgesFound
×
631
                }
×
632

633
                disabledEdgePolicyIndex := edges.NestedReadBucket(
6✔
634
                        disabledEdgePolicyBucket,
6✔
635
                )
6✔
636
                if disabledEdgePolicyIndex == nil {
7✔
637
                        return nil
1✔
638
                }
1✔
639

640
                // We iterate over all disabled policies and we add each channel that
641
                // has more than one disabled policy to disabledChanIDs array.
642
                return disabledEdgePolicyIndex.ForEach(func(k, v []byte) error {
16✔
643
                        chanID := byteOrder.Uint64(k[:8])
11✔
644
                        _, edgeFound := chanEdgeFound[chanID]
11✔
645
                        if edgeFound {
15✔
646
                                delete(chanEdgeFound, chanID)
4✔
647
                                disabledChanIDs = append(disabledChanIDs, chanID)
4✔
648
                                return nil
4✔
649
                        }
4✔
650

651
                        chanEdgeFound[chanID] = struct{}{}
7✔
652
                        return nil
7✔
653
                })
654
        }, func() {
6✔
655
                disabledChanIDs = nil
6✔
656
                chanEdgeFound = make(map[uint64]struct{})
6✔
657
        })
6✔
658
        if err != nil {
6✔
659
                return nil, err
×
660
        }
×
661

662
        return disabledChanIDs, nil
6✔
663
}
664

665
// ForEachNode iterates through all the stored vertices/nodes in the graph,
666
// executing the passed callback with each node encountered. If the callback
667
// returns an error, then the transaction is aborted and the iteration stops
668
// early.
669
//
670
// TODO(roasbeef): add iterator interface to allow for memory efficient graph
671
// traversal when graph gets mega
672
func (c *ChannelGraph) ForEachNode(
673
        cb func(kvdb.RTx, *LightningNode) error) error {
133✔
674

133✔
675
        traversal := func(tx kvdb.RTx) error {
266✔
676
                // First grab the nodes bucket which stores the mapping from
133✔
677
                // pubKey to node information.
133✔
678
                nodes := tx.ReadBucket(nodeBucket)
133✔
679
                if nodes == nil {
133✔
680
                        return ErrGraphNotFound
×
681
                }
×
682

683
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,576✔
684
                        // If this is the source key, then we skip this
1,443✔
685
                        // iteration as the value for this key is a pubKey
1,443✔
686
                        // rather than raw node information.
1,443✔
687
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
1,708✔
688
                                return nil
265✔
689
                        }
265✔
690

691
                        nodeReader := bytes.NewReader(nodeBytes)
1,182✔
692
                        node, err := deserializeLightningNode(nodeReader)
1,182✔
693
                        if err != nil {
1,182✔
694
                                return err
×
695
                        }
×
696

697
                        // Execute the callback, the transaction will abort if
698
                        // this returns an error.
699
                        return cb(tx, &node)
1,182✔
700
                })
701
        }
702

703
        return kvdb.View(c.db, traversal, func() {})
266✔
704
}
705

706
// ForEachNodeCacheable iterates through all the stored vertices/nodes in the
707
// graph, executing the passed callback with each node encountered. If the
708
// callback returns an error, then the transaction is aborted and the iteration
709
// stops early.
710
func (c *ChannelGraph) ForEachNodeCacheable(cb func(kvdb.RTx,
711
        GraphCacheNode) error) error {
1,812✔
712

1,812✔
713
        traversal := func(tx kvdb.RTx) error {
3,624✔
714
                // First grab the nodes bucket which stores the mapping from
1,812✔
715
                // pubKey to node information.
1,812✔
716
                nodes := tx.ReadBucket(nodeBucket)
1,812✔
717
                if nodes == nil {
1,812✔
718
                        return ErrGraphNotFound
×
719
                }
×
720

721
                return nodes.ForEach(func(pubKey, nodeBytes []byte) error {
5,552✔
722
                        // If this is the source key, then we skip this
3,740✔
723
                        // iteration as the value for this key is a pubKey
3,740✔
724
                        // rather than raw node information.
3,740✔
725
                        if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
7,360✔
726
                                return nil
3,620✔
727
                        }
3,620✔
728

729
                        nodeReader := bytes.NewReader(nodeBytes)
124✔
730
                        cacheableNode, err := deserializeLightningNodeCacheable(
124✔
731
                                nodeReader,
124✔
732
                        )
124✔
733
                        if err != nil {
124✔
734
                                return err
×
735
                        }
×
736

737
                        // Execute the callback, the transaction will abort if
738
                        // this returns an error.
739
                        return cb(tx, cacheableNode)
124✔
740
                })
741
        }
742

743
        return kvdb.View(c.db, traversal, func() {})
3,624✔
744
}
745

746
// SourceNode returns the source node of the graph. The source node is treated
747
// as the center node within a star-graph. This method may be used to kick off
748
// a path finding algorithm in order to explore the reachability of another
749
// node based off the source node.
750
func (c *ChannelGraph) SourceNode() (*LightningNode, error) {
281✔
751
        var source *LightningNode
281✔
752
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
562✔
753
                // First grab the nodes bucket which stores the mapping from
281✔
754
                // pubKey to node information.
281✔
755
                nodes := tx.ReadBucket(nodeBucket)
281✔
756
                if nodes == nil {
281✔
757
                        return ErrGraphNotFound
×
758
                }
×
759

760
                node, err := c.sourceNode(nodes)
281✔
761
                if err != nil {
282✔
762
                        return err
1✔
763
                }
1✔
764
                source = node
280✔
765

280✔
766
                return nil
280✔
767
        }, func() {
281✔
768
                source = nil
281✔
769
        })
281✔
770
        if err != nil {
282✔
771
                return nil, err
1✔
772
        }
1✔
773

774
        return source, nil
280✔
775
}
776

777
// sourceNode uses an existing database transaction and returns the source node
778
// of the graph. The source node is treated as the center node within a
779
// star-graph. This method may be used to kick off a path finding algorithm in
780
// order to explore the reachability of another node based off the source node.
781
func (c *ChannelGraph) sourceNode(nodes kvdb.RBucket) (*LightningNode, error) {
574✔
782
        selfPub := nodes.Get(sourceKey)
574✔
783
        if selfPub == nil {
575✔
784
                return nil, ErrSourceNodeNotSet
1✔
785
        }
1✔
786

787
        // With the pubKey of the source node retrieved, we're able to
788
        // fetch the full node information.
789
        node, err := fetchLightningNode(nodes, selfPub)
573✔
790
        if err != nil {
573✔
791
                return nil, err
×
792
        }
×
793

794
        return &node, nil
573✔
795
}
796

797
// SetSourceNode sets the source node within the graph database. The source
798
// node is to be used as the center of a star-graph within path finding
799
// algorithms.
800
func (c *ChannelGraph) SetSourceNode(node *LightningNode) error {
123✔
801
        nodePubBytes := node.PubKeyBytes[:]
123✔
802

123✔
803
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
246✔
804
                // First grab the nodes bucket which stores the mapping from
123✔
805
                // pubKey to node information.
123✔
806
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
123✔
807
                if err != nil {
123✔
808
                        return err
×
809
                }
×
810

811
                // Next we create the mapping from source to the targeted
812
                // public key.
813
                if err := nodes.Put(sourceKey, nodePubBytes); err != nil {
123✔
814
                        return err
×
815
                }
×
816

817
                // Finally, we commit the information of the lightning node
818
                // itself.
819
                return addLightningNode(tx, node)
123✔
820
        }, func() {})
123✔
821
}
822

823
// AddLightningNode adds a vertex/node to the graph database. If the node is not
824
// in the database from before, this will add a new, unconnected one to the
825
// graph. If it is present from before, this will update that node's
826
// information. Note that this method is expected to only be called to update an
827
// already present node from a node announcement, or to insert a node found in a
828
// channel update.
829
//
830
// TODO(roasbeef): also need sig of announcement
831
func (c *ChannelGraph) AddLightningNode(node *LightningNode,
832
        op ...batch.SchedulerOption) error {
784✔
833

784✔
834
        r := &batch.Request{
784✔
835
                Update: func(tx kvdb.RwTx) error {
1,568✔
836
                        if c.graphCache != nil {
1,386✔
837
                                cNode := newGraphCacheNode(
602✔
838
                                        node.PubKeyBytes, node.Features,
602✔
839
                                )
602✔
840
                                err := c.graphCache.AddNode(tx, cNode)
602✔
841
                                if err != nil {
602✔
842
                                        return err
×
843
                                }
×
844
                        }
845

846
                        return addLightningNode(tx, node)
784✔
847
                },
848
        }
849

850
        for _, f := range op {
788✔
851
                f(r)
4✔
852
        }
4✔
853

854
        return c.nodeScheduler.Execute(r)
784✔
855
}
856

857
func addLightningNode(tx kvdb.RwTx, node *LightningNode) error {
971✔
858
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
971✔
859
        if err != nil {
971✔
860
                return err
×
861
        }
×
862

863
        aliases, err := nodes.CreateBucketIfNotExists(aliasIndexBucket)
971✔
864
        if err != nil {
971✔
865
                return err
×
866
        }
×
867

868
        updateIndex, err := nodes.CreateBucketIfNotExists(
971✔
869
                nodeUpdateIndexBucket,
971✔
870
        )
971✔
871
        if err != nil {
971✔
872
                return err
×
873
        }
×
874

875
        return putLightningNode(nodes, aliases, updateIndex, node)
971✔
876
}
877

878
// LookupAlias attempts to return the alias as advertised by the target node.
879
// TODO(roasbeef): currently assumes that aliases are unique...
880
func (c *ChannelGraph) LookupAlias(pub *btcec.PublicKey) (string, error) {
6✔
881
        var alias string
6✔
882

6✔
883
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
12✔
884
                nodes := tx.ReadBucket(nodeBucket)
6✔
885
                if nodes == nil {
6✔
886
                        return ErrGraphNodesNotFound
×
887
                }
×
888

889
                aliases := nodes.NestedReadBucket(aliasIndexBucket)
6✔
890
                if aliases == nil {
6✔
891
                        return ErrGraphNodesNotFound
×
892
                }
×
893

894
                nodePub := pub.SerializeCompressed()
6✔
895
                a := aliases.Get(nodePub)
6✔
896
                if a == nil {
7✔
897
                        return ErrNodeAliasNotFound
1✔
898
                }
1✔
899

900
                // TODO(roasbeef): should actually be using the utf-8
901
                // package...
902
                alias = string(a)
5✔
903
                return nil
5✔
904
        }, func() {
6✔
905
                alias = ""
6✔
906
        })
6✔
907
        if err != nil {
7✔
908
                return "", err
1✔
909
        }
1✔
910

911
        return alias, nil
5✔
912
}
913

914
// DeleteLightningNode starts a new database transaction to remove a vertex/node
915
// from the database according to the node's public key.
916
func (c *ChannelGraph) DeleteLightningNode(nodePub route.Vertex) error {
3✔
917
        // TODO(roasbeef): ensure dangling edges are removed...
3✔
918
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
919
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
920
                if nodes == nil {
3✔
921
                        return ErrGraphNodeNotFound
×
922
                }
×
923

924
                if c.graphCache != nil {
6✔
925
                        c.graphCache.RemoveNode(nodePub)
3✔
926
                }
3✔
927

928
                return c.deleteLightningNode(nodes, nodePub[:])
3✔
929
        }, func() {})
3✔
930
}
931

932
// deleteLightningNode uses an existing database transaction to remove a
933
// vertex/node from the database according to the node's public key.
934
func (c *ChannelGraph) deleteLightningNode(nodes kvdb.RwBucket,
935
        compressedPubKey []byte) error {
64✔
936

64✔
937
        aliases := nodes.NestedReadWriteBucket(aliasIndexBucket)
64✔
938
        if aliases == nil {
64✔
939
                return ErrGraphNodesNotFound
×
940
        }
×
941

942
        if err := aliases.Delete(compressedPubKey); err != nil {
64✔
943
                return err
×
944
        }
×
945

946
        // Before we delete the node, we'll fetch its current state so we can
947
        // determine when its last update was to clear out the node update
948
        // index.
949
        node, err := fetchLightningNode(nodes, compressedPubKey)
64✔
950
        if err != nil {
64✔
951
                return err
×
952
        }
×
953

954
        if err := nodes.Delete(compressedPubKey); err != nil {
64✔
955
                return err
×
956
        }
×
957

958
        // Finally, we'll delete the index entry for the node within the
959
        // nodeUpdateIndexBucket as this node is no longer active, so we don't
960
        // need to track its last update.
961
        nodeUpdateIndex := nodes.NestedReadWriteBucket(nodeUpdateIndexBucket)
64✔
962
        if nodeUpdateIndex == nil {
64✔
963
                return ErrGraphNodesNotFound
×
964
        }
×
965

966
        // In order to delete the entry, we'll need to reconstruct the key for
967
        // its last update.
968
        updateUnix := uint64(node.LastUpdate.Unix())
64✔
969
        var indexKey [8 + 33]byte
64✔
970
        byteOrder.PutUint64(indexKey[:8], updateUnix)
64✔
971
        copy(indexKey[8:], compressedPubKey)
64✔
972

64✔
973
        return nodeUpdateIndex.Delete(indexKey[:])
64✔
974
}
975

976
// AddChannelEdge adds a new (undirected, blank) edge to the graph database. An
977
// undirected edge from the two target nodes are created. The information stored
978
// denotes the static attributes of the channel, such as the channelID, the keys
979
// involved in creation of the channel, and the set of features that the channel
980
// supports. The chanPoint and chanID are used to uniquely identify the edge
981
// globally within the database.
982
func (c *ChannelGraph) AddChannelEdge(edge *models.ChannelEdgeInfo,
983
        op ...batch.SchedulerOption) error {
1,705✔
984

1,705✔
985
        var alreadyExists bool
1,705✔
986
        r := &batch.Request{
1,705✔
987
                Reset: func() {
3,410✔
988
                        alreadyExists = false
1,705✔
989
                },
1,705✔
990
                Update: func(tx kvdb.RwTx) error {
1,705✔
991
                        err := c.addChannelEdge(tx, edge)
1,705✔
992

1,705✔
993
                        // Silence ErrEdgeAlreadyExist so that the batch can
1,705✔
994
                        // succeed, but propagate the error via local state.
1,705✔
995
                        if err == ErrEdgeAlreadyExist {
1,947✔
996
                                alreadyExists = true
242✔
997
                                return nil
242✔
998
                        }
242✔
999

1000
                        return err
1,463✔
1001
                },
1002
                OnCommit: func(err error) error {
1,705✔
1003
                        switch {
1,705✔
1004
                        case err != nil:
×
1005
                                return err
×
1006
                        case alreadyExists:
242✔
1007
                                return ErrEdgeAlreadyExist
242✔
1008
                        default:
1,463✔
1009
                                c.rejectCache.remove(edge.ChannelID)
1,463✔
1010
                                c.chanCache.remove(edge.ChannelID)
1,463✔
1011
                                return nil
1,463✔
1012
                        }
1013
                },
1014
        }
1015

1016
        for _, f := range op {
1,709✔
1017
                f(r)
4✔
1018
        }
4✔
1019

1020
        return c.chanScheduler.Execute(r)
1,705✔
1021
}
1022

1023
// addChannelEdge is the private form of AddChannelEdge that allows callers to
1024
// utilize an existing db transaction.
1025
func (c *ChannelGraph) addChannelEdge(tx kvdb.RwTx,
1026
        edge *models.ChannelEdgeInfo) error {
1,705✔
1027

1,705✔
1028
        // Construct the channel's primary key which is the 8-byte channel ID.
1,705✔
1029
        var chanKey [8]byte
1,705✔
1030
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
1,705✔
1031

1,705✔
1032
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
1,705✔
1033
        if err != nil {
1,705✔
1034
                return err
×
1035
        }
×
1036
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
1,705✔
1037
        if err != nil {
1,705✔
1038
                return err
×
1039
        }
×
1040
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
1,705✔
1041
        if err != nil {
1,705✔
1042
                return err
×
1043
        }
×
1044
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
1,705✔
1045
        if err != nil {
1,705✔
1046
                return err
×
1047
        }
×
1048

1049
        // First, attempt to check if this edge has already been created. If
1050
        // so, then we can exit early as this method is meant to be idempotent.
1051
        if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo != nil {
1,947✔
1052
                return ErrEdgeAlreadyExist
242✔
1053
        }
242✔
1054

1055
        if c.graphCache != nil {
2,741✔
1056
                c.graphCache.AddChannel(edge, nil, nil)
1,278✔
1057
        }
1,278✔
1058

1059
        // Before we insert the channel into the database, we'll ensure that
1060
        // both nodes already exist in the channel graph. If either node
1061
        // doesn't, then we'll insert a "shell" node that just includes its
1062
        // public key, so subsequent validation and queries can work properly.
1063
        _, node1Err := fetchLightningNode(nodes, edge.NodeKey1Bytes[:])
1,463✔
1064
        switch {
1,463✔
1065
        case node1Err == ErrGraphNodeNotFound:
22✔
1066
                node1Shell := LightningNode{
22✔
1067
                        PubKeyBytes:          edge.NodeKey1Bytes,
22✔
1068
                        HaveNodeAnnouncement: false,
22✔
1069
                }
22✔
1070
                err := addLightningNode(tx, &node1Shell)
22✔
1071
                if err != nil {
22✔
1072
                        return fmt.Errorf("unable to create shell node "+
×
1073
                                "for: %x", edge.NodeKey1Bytes)
×
1074
                }
×
1075
        case node1Err != nil:
×
1076
                return err
×
1077
        }
1078

1079
        _, node2Err := fetchLightningNode(nodes, edge.NodeKey2Bytes[:])
1,463✔
1080
        switch {
1,463✔
1081
        case node2Err == ErrGraphNodeNotFound:
54✔
1082
                node2Shell := LightningNode{
54✔
1083
                        PubKeyBytes:          edge.NodeKey2Bytes,
54✔
1084
                        HaveNodeAnnouncement: false,
54✔
1085
                }
54✔
1086
                err := addLightningNode(tx, &node2Shell)
54✔
1087
                if err != nil {
54✔
1088
                        return fmt.Errorf("unable to create shell node "+
×
1089
                                "for: %x", edge.NodeKey2Bytes)
×
1090
                }
×
1091
        case node2Err != nil:
×
1092
                return err
×
1093
        }
1094

1095
        // If the edge hasn't been created yet, then we'll first add it to the
1096
        // edge index in order to associate the edge between two nodes and also
1097
        // store the static components of the channel.
1098
        if err := putChanEdgeInfo(edgeIndex, edge, chanKey); err != nil {
1,463✔
1099
                return err
×
1100
        }
×
1101

1102
        // Mark edge policies for both sides as unknown. This is to enable
1103
        // efficient incoming channel lookup for a node.
1104
        keys := []*[33]byte{
1,463✔
1105
                &edge.NodeKey1Bytes,
1,463✔
1106
                &edge.NodeKey2Bytes,
1,463✔
1107
        }
1,463✔
1108
        for _, key := range keys {
4,385✔
1109
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
2,922✔
1110
                if err != nil {
2,922✔
1111
                        return err
×
1112
                }
×
1113
        }
1114

1115
        // Finally we add it to the channel index which maps channel points
1116
        // (outpoints) to the shorter channel ID's.
1117
        var b bytes.Buffer
1,463✔
1118
        if err := writeOutpoint(&b, &edge.ChannelPoint); err != nil {
1,463✔
1119
                return err
×
1120
        }
×
1121
        return chanIndex.Put(b.Bytes(), chanKey[:])
1,463✔
1122
}
1123

1124
// HasChannelEdge returns true if the database knows of a channel edge with the
1125
// passed channel ID, and false otherwise. If an edge with that ID is found
1126
// within the graph, then two time stamps representing the last time the edge
1127
// was updated for both directed edges are returned along with the boolean. If
1128
// it is not found, then the zombie index is checked and its result is returned
1129
// as the second boolean.
1130
func (c *ChannelGraph) HasChannelEdge(
1131
        chanID uint64) (time.Time, time.Time, bool, bool, error) {
231✔
1132

231✔
1133
        var (
231✔
1134
                upd1Time time.Time
231✔
1135
                upd2Time time.Time
231✔
1136
                exists   bool
231✔
1137
                isZombie bool
231✔
1138
        )
231✔
1139

231✔
1140
        // We'll query the cache with the shared lock held to allow multiple
231✔
1141
        // readers to access values in the cache concurrently if they exist.
231✔
1142
        c.cacheMu.RLock()
231✔
1143
        if entry, ok := c.rejectCache.get(chanID); ok {
306✔
1144
                c.cacheMu.RUnlock()
75✔
1145
                upd1Time = time.Unix(entry.upd1Time, 0)
75✔
1146
                upd2Time = time.Unix(entry.upd2Time, 0)
75✔
1147
                exists, isZombie = entry.flags.unpack()
75✔
1148
                return upd1Time, upd2Time, exists, isZombie, nil
75✔
1149
        }
75✔
1150
        c.cacheMu.RUnlock()
160✔
1151

160✔
1152
        c.cacheMu.Lock()
160✔
1153
        defer c.cacheMu.Unlock()
160✔
1154

160✔
1155
        // The item was not found with the shared lock, so we'll acquire the
160✔
1156
        // exclusive lock and check the cache again in case another method added
160✔
1157
        // the entry to the cache while no lock was held.
160✔
1158
        if entry, ok := c.rejectCache.get(chanID); ok {
171✔
1159
                upd1Time = time.Unix(entry.upd1Time, 0)
11✔
1160
                upd2Time = time.Unix(entry.upd2Time, 0)
11✔
1161
                exists, isZombie = entry.flags.unpack()
11✔
1162
                return upd1Time, upd2Time, exists, isZombie, nil
11✔
1163
        }
11✔
1164

1165
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
306✔
1166
                edges := tx.ReadBucket(edgeBucket)
153✔
1167
                if edges == nil {
153✔
1168
                        return ErrGraphNoEdgesFound
×
1169
                }
×
1170
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
153✔
1171
                if edgeIndex == nil {
153✔
1172
                        return ErrGraphNoEdgesFound
×
1173
                }
×
1174

1175
                var channelID [8]byte
153✔
1176
                byteOrder.PutUint64(channelID[:], chanID)
153✔
1177

153✔
1178
                // If the edge doesn't exist, then we'll also check our zombie
153✔
1179
                // index.
153✔
1180
                if edgeIndex.Get(channelID[:]) == nil {
257✔
1181
                        exists = false
104✔
1182
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
104✔
1183
                        if zombieIndex != nil {
208✔
1184
                                isZombie, _, _ = isZombieEdge(
104✔
1185
                                        zombieIndex, chanID,
104✔
1186
                                )
104✔
1187
                        }
104✔
1188

1189
                        return nil
104✔
1190
                }
1191

1192
                exists = true
53✔
1193
                isZombie = false
53✔
1194

53✔
1195
                // If the channel has been found in the graph, then retrieve
53✔
1196
                // the edges itself so we can return the last updated
53✔
1197
                // timestamps.
53✔
1198
                nodes := tx.ReadBucket(nodeBucket)
53✔
1199
                if nodes == nil {
53✔
1200
                        return ErrGraphNodeNotFound
×
1201
                }
×
1202

1203
                e1, e2, err := fetchChanEdgePolicies(
53✔
1204
                        edgeIndex, edges, channelID[:],
53✔
1205
                )
53✔
1206
                if err != nil {
53✔
1207
                        return err
×
1208
                }
×
1209

1210
                // As we may have only one of the edges populated, only set the
1211
                // update time if the edge was found in the database.
1212
                if e1 != nil {
76✔
1213
                        upd1Time = e1.LastUpdate
23✔
1214
                }
23✔
1215
                if e2 != nil {
74✔
1216
                        upd2Time = e2.LastUpdate
21✔
1217
                }
21✔
1218

1219
                return nil
53✔
1220
        }, func() {}); err != nil {
153✔
1221
                return time.Time{}, time.Time{}, exists, isZombie, err
×
1222
        }
×
1223

1224
        c.rejectCache.insert(chanID, rejectCacheEntry{
153✔
1225
                upd1Time: upd1Time.Unix(),
153✔
1226
                upd2Time: upd2Time.Unix(),
153✔
1227
                flags:    packRejectFlags(exists, isZombie),
153✔
1228
        })
153✔
1229

153✔
1230
        return upd1Time, upd2Time, exists, isZombie, nil
153✔
1231
}
1232

1233
// UpdateChannelEdge retrieves and update edge of the graph database. Method
1234
// only reserved for updating an edge info after its already been created.
1235
// In order to maintain this constraints, we return an error in the scenario
1236
// that an edge info hasn't yet been created yet, but someone attempts to update
1237
// it.
1238
func (c *ChannelGraph) UpdateChannelEdge(edge *models.ChannelEdgeInfo) error {
5✔
1239
        // Construct the channel's primary key which is the 8-byte channel ID.
5✔
1240
        var chanKey [8]byte
5✔
1241
        binary.BigEndian.PutUint64(chanKey[:], edge.ChannelID)
5✔
1242

5✔
1243
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
10✔
1244
                edges := tx.ReadWriteBucket(edgeBucket)
5✔
1245
                if edge == nil {
5✔
1246
                        return ErrEdgeNotFound
×
1247
                }
×
1248

1249
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
5✔
1250
                if edgeIndex == nil {
5✔
1251
                        return ErrEdgeNotFound
×
1252
                }
×
1253

1254
                if edgeInfo := edgeIndex.Get(chanKey[:]); edgeInfo == nil {
5✔
1255
                        return ErrEdgeNotFound
×
1256
                }
×
1257

1258
                if c.graphCache != nil {
10✔
1259
                        c.graphCache.UpdateChannel(edge)
5✔
1260
                }
5✔
1261

1262
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
5✔
1263
        }, func() {})
5✔
1264
}
1265

1266
const (
1267
        // pruneTipBytes is the total size of the value which stores a prune
1268
        // entry of the graph in the prune log. The "prune tip" is the last
1269
        // entry in the prune log, and indicates if the channel graph is in
1270
        // sync with the current UTXO state. The structure of the value
1271
        // is: blockHash, taking 32 bytes total.
1272
        pruneTipBytes = 32
1273
)
1274

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

256✔
1286
        c.cacheMu.Lock()
256✔
1287
        defer c.cacheMu.Unlock()
256✔
1288

256✔
1289
        var chansClosed []*models.ChannelEdgeInfo
256✔
1290

256✔
1291
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
512✔
1292
                // First grab the edges bucket which houses the information
256✔
1293
                // we'd like to delete
256✔
1294
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
256✔
1295
                if err != nil {
256✔
1296
                        return err
×
1297
                }
×
1298

1299
                // Next grab the two edge indexes which will also need to be updated.
1300
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
256✔
1301
                if err != nil {
256✔
1302
                        return err
×
1303
                }
×
1304
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
256✔
1305
                if err != nil {
256✔
1306
                        return err
×
1307
                }
×
1308
                nodes := tx.ReadWriteBucket(nodeBucket)
256✔
1309
                if nodes == nil {
256✔
1310
                        return ErrSourceNodeNotSet
×
1311
                }
×
1312
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
256✔
1313
                if err != nil {
256✔
1314
                        return err
×
1315
                }
×
1316

1317
                // For each of the outpoints that have been spent within the
1318
                // block, we attempt to delete them from the graph as if that
1319
                // outpoint was a channel, then it has now been closed.
1320
                for _, chanPoint := range spentOutputs {
383✔
1321
                        // TODO(roasbeef): load channel bloom filter, continue
127✔
1322
                        // if NOT if filter
127✔
1323

127✔
1324
                        var opBytes bytes.Buffer
127✔
1325
                        if err := writeOutpoint(&opBytes, chanPoint); err != nil {
127✔
1326
                                return err
×
1327
                        }
×
1328

1329
                        // First attempt to see if the channel exists within
1330
                        // the database, if not, then we can exit early.
1331
                        chanID := chanIndex.Get(opBytes.Bytes())
127✔
1332
                        if chanID == nil {
232✔
1333
                                continue
105✔
1334
                        }
1335

1336
                        // However, if it does, then we'll read out the full
1337
                        // version so we can add it to the set of deleted
1338
                        // channels.
1339
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
26✔
1340
                        if err != nil {
26✔
1341
                                return err
×
1342
                        }
×
1343

1344
                        // Attempt to delete the channel, an ErrEdgeNotFound
1345
                        // will be returned if that outpoint isn't known to be
1346
                        // a channel. If no error is returned, then a channel
1347
                        // was successfully pruned.
1348
                        err = c.delChannelEdgeUnsafe(
26✔
1349
                                edges, edgeIndex, chanIndex, zombieIndex,
26✔
1350
                                chanID, false, false,
26✔
1351
                        )
26✔
1352
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
26✔
1353
                                return err
×
1354
                        }
×
1355

1356
                        chansClosed = append(chansClosed, &edgeInfo)
26✔
1357
                }
1358

1359
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
256✔
1360
                if err != nil {
256✔
1361
                        return err
×
1362
                }
×
1363

1364
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
256✔
1365
                if err != nil {
256✔
1366
                        return err
×
1367
                }
×
1368

1369
                // With the graph pruned, add a new entry to the prune log,
1370
                // which can be used to check if the graph is fully synced with
1371
                // the current UTXO state.
1372
                var blockHeightBytes [4]byte
256✔
1373
                byteOrder.PutUint32(blockHeightBytes[:], blockHeight)
256✔
1374

256✔
1375
                var newTip [pruneTipBytes]byte
256✔
1376
                copy(newTip[:], blockHash[:])
256✔
1377

256✔
1378
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
256✔
1379
                if err != nil {
256✔
1380
                        return err
×
1381
                }
×
1382

1383
                // Now that the graph has been pruned, we'll also attempt to
1384
                // prune any nodes that have had a channel closed within the
1385
                // latest block.
1386
                return c.pruneGraphNodes(nodes, edgeIndex)
256✔
1387
        }, func() {
256✔
1388
                chansClosed = nil
256✔
1389
        })
256✔
1390
        if err != nil {
256✔
1391
                return nil, err
×
1392
        }
×
1393

1394
        for _, channel := range chansClosed {
282✔
1395
                c.rejectCache.remove(channel.ChannelID)
26✔
1396
                c.chanCache.remove(channel.ChannelID)
26✔
1397
        }
26✔
1398

1399
        if c.graphCache != nil {
512✔
1400
                log.Debugf("Pruned graph, cache now has %s",
256✔
1401
                        c.graphCache.Stats())
256✔
1402
        }
256✔
1403

1404
        return chansClosed, nil
256✔
1405
}
1406

1407
// PruneGraphNodes is a garbage collection method which attempts to prune out
1408
// any nodes from the channel graph that are currently unconnected. This ensure
1409
// that we only maintain a graph of reachable nodes. In the event that a pruned
1410
// node gains more channels, it will be re-added back to the graph.
1411
func (c *ChannelGraph) PruneGraphNodes() error {
45✔
1412
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
90✔
1413
                nodes := tx.ReadWriteBucket(nodeBucket)
45✔
1414
                if nodes == nil {
45✔
1415
                        return ErrGraphNodesNotFound
×
1416
                }
×
1417
                edges := tx.ReadWriteBucket(edgeBucket)
45✔
1418
                if edges == nil {
45✔
1419
                        return ErrGraphNotFound
×
1420
                }
×
1421
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
45✔
1422
                if edgeIndex == nil {
45✔
1423
                        return ErrGraphNoEdgesFound
×
1424
                }
×
1425

1426
                return c.pruneGraphNodes(nodes, edgeIndex)
45✔
1427
        }, func() {})
45✔
1428
}
1429

1430
// pruneGraphNodes attempts to remove any nodes from the graph who have had a
1431
// channel closed within the current block. If the node still has existing
1432
// channels in the graph, this will act as a no-op.
1433
func (c *ChannelGraph) pruneGraphNodes(nodes kvdb.RwBucket,
1434
        edgeIndex kvdb.RwBucket) error {
297✔
1435

297✔
1436
        log.Trace("Pruning nodes from graph with no open channels")
297✔
1437

297✔
1438
        // We'll retrieve the graph's source node to ensure we don't remove it
297✔
1439
        // even if it no longer has any open channels.
297✔
1440
        sourceNode, err := c.sourceNode(nodes)
297✔
1441
        if err != nil {
297✔
1442
                return err
×
1443
        }
×
1444

1445
        // We'll use this map to keep count the number of references to a node
1446
        // in the graph. A node should only be removed once it has no more
1447
        // references in the graph.
1448
        nodeRefCounts := make(map[[33]byte]int)
297✔
1449
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
1,882✔
1450
                // If this is the source key, then we skip this
1,585✔
1451
                // iteration as the value for this key is a pubKey
1,585✔
1452
                // rather than raw node information.
1,585✔
1453
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
2,468✔
1454
                        return nil
883✔
1455
                }
883✔
1456

1457
                var nodePub [33]byte
706✔
1458
                copy(nodePub[:], pubKey)
706✔
1459
                nodeRefCounts[nodePub] = 0
706✔
1460

706✔
1461
                return nil
706✔
1462
        })
1463
        if err != nil {
297✔
1464
                return err
×
1465
        }
×
1466

1467
        // To ensure we never delete the source node, we'll start off by
1468
        // bumping its ref count to 1.
1469
        nodeRefCounts[sourceNode.PubKeyBytes] = 1
297✔
1470

297✔
1471
        // Next, we'll run through the edgeIndex which maps a channel ID to the
297✔
1472
        // edge info. We'll use this scan to populate our reference count map
297✔
1473
        // above.
297✔
1474
        err = edgeIndex.ForEach(func(chanID, edgeInfoBytes []byte) error {
722✔
1475
                // The first 66 bytes of the edge info contain the pubkeys of
425✔
1476
                // the nodes that this edge attaches. We'll extract them, and
425✔
1477
                // add them to the ref count map.
425✔
1478
                var node1, node2 [33]byte
425✔
1479
                copy(node1[:], edgeInfoBytes[:33])
425✔
1480
                copy(node2[:], edgeInfoBytes[33:])
425✔
1481

425✔
1482
                // With the nodes extracted, we'll increase the ref count of
425✔
1483
                // each of the nodes.
425✔
1484
                nodeRefCounts[node1]++
425✔
1485
                nodeRefCounts[node2]++
425✔
1486

425✔
1487
                return nil
425✔
1488
        })
425✔
1489
        if err != nil {
297✔
1490
                return err
×
1491
        }
×
1492

1493
        // Finally, we'll make a second pass over the set of nodes, and delete
1494
        // any nodes that have a ref count of zero.
1495
        var numNodesPruned int
297✔
1496
        for nodePubKey, refCount := range nodeRefCounts {
1,003✔
1497
                // If the ref count of the node isn't zero, then we can safely
706✔
1498
                // skip it as it still has edges to or from it within the
706✔
1499
                // graph.
706✔
1500
                if refCount != 0 {
1,355✔
1501
                        continue
649✔
1502
                }
1503

1504
                if c.graphCache != nil {
122✔
1505
                        c.graphCache.RemoveNode(nodePubKey)
61✔
1506
                }
61✔
1507

1508
                // If we reach this point, then there are no longer any edges
1509
                // that connect this node, so we can delete it.
1510
                if err := c.deleteLightningNode(nodes, nodePubKey[:]); err != nil {
61✔
1511
                        if errors.Is(err, ErrGraphNodeNotFound) ||
×
1512
                                errors.Is(err, ErrGraphNodesNotFound) {
×
1513

×
1514
                                log.Warnf("Unable to prune node %x from the "+
×
1515
                                        "graph: %v", nodePubKey, err)
×
1516
                                continue
×
1517
                        }
1518

1519
                        return err
×
1520
                }
1521

1522
                log.Infof("Pruned unconnected node %x from channel graph",
61✔
1523
                        nodePubKey[:])
61✔
1524

61✔
1525
                numNodesPruned++
61✔
1526
        }
1527

1528
        if numNodesPruned > 0 {
342✔
1529
                log.Infof("Pruned %v unconnected nodes from the channel graph",
45✔
1530
                        numNodesPruned)
45✔
1531
        }
45✔
1532

1533
        return nil
297✔
1534
}
1535

1536
// DisconnectBlockAtHeight is used to indicate that the block specified
1537
// by the passed height has been disconnected from the main chain. This
1538
// will "rewind" the graph back to the height below, deleting channels
1539
// that are no longer confirmed from the graph. The prune log will be
1540
// set to the last prune height valid for the remaining chain.
1541
// Channels that were removed from the graph resulting from the
1542
// disconnected block are returned.
1543
func (c *ChannelGraph) DisconnectBlockAtHeight(height uint32) (
1544
        []*models.ChannelEdgeInfo, error) {
162✔
1545

162✔
1546
        // Every channel having a ShortChannelID starting at 'height'
162✔
1547
        // will no longer be confirmed.
162✔
1548
        startShortChanID := lnwire.ShortChannelID{
162✔
1549
                BlockHeight: height,
162✔
1550
        }
162✔
1551

162✔
1552
        // Delete everything after this height from the db up until the
162✔
1553
        // SCID alias range.
162✔
1554
        endShortChanID := aliasmgr.StartingAlias
162✔
1555

162✔
1556
        // The block height will be the 3 first bytes of the channel IDs.
162✔
1557
        var chanIDStart [8]byte
162✔
1558
        byteOrder.PutUint64(chanIDStart[:], startShortChanID.ToUint64())
162✔
1559
        var chanIDEnd [8]byte
162✔
1560
        byteOrder.PutUint64(chanIDEnd[:], endShortChanID.ToUint64())
162✔
1561

162✔
1562
        c.cacheMu.Lock()
162✔
1563
        defer c.cacheMu.Unlock()
162✔
1564

162✔
1565
        // Keep track of the channels that are removed from the graph.
162✔
1566
        var removedChans []*models.ChannelEdgeInfo
162✔
1567

162✔
1568
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
324✔
1569
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
162✔
1570
                if err != nil {
162✔
1571
                        return err
×
1572
                }
×
1573
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
162✔
1574
                if err != nil {
162✔
1575
                        return err
×
1576
                }
×
1577
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
162✔
1578
                if err != nil {
162✔
1579
                        return err
×
1580
                }
×
1581
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
162✔
1582
                if err != nil {
162✔
1583
                        return err
×
1584
                }
×
1585

1586
                // Scan from chanIDStart to chanIDEnd, deleting every
1587
                // found edge.
1588
                // NOTE: we must delete the edges after the cursor loop, since
1589
                // modifying the bucket while traversing is not safe.
1590
                // NOTE: We use a < comparison in bytes.Compare instead of <=
1591
                // so that the StartingAlias itself isn't deleted.
1592
                var keys [][]byte
162✔
1593
                cursor := edgeIndex.ReadWriteCursor()
162✔
1594

162✔
1595
                //nolint:lll
162✔
1596
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
162✔
1597
                        bytes.Compare(k, chanIDEnd[:]) < 0; k, v = cursor.Next() {
255✔
1598
                        edgeInfoReader := bytes.NewReader(v)
93✔
1599
                        edgeInfo, err := deserializeChanEdgeInfo(edgeInfoReader)
93✔
1600
                        if err != nil {
93✔
1601
                                return err
×
1602
                        }
×
1603

1604
                        keys = append(keys, k)
93✔
1605
                        removedChans = append(removedChans, &edgeInfo)
93✔
1606
                }
1607

1608
                for _, k := range keys {
255✔
1609
                        err = c.delChannelEdgeUnsafe(
93✔
1610
                                edges, edgeIndex, chanIndex, zombieIndex,
93✔
1611
                                k, false, false,
93✔
1612
                        )
93✔
1613
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
93✔
1614
                                return err
×
1615
                        }
×
1616
                }
1617

1618
                // Delete all the entries in the prune log having a height
1619
                // greater or equal to the block disconnected.
1620
                metaBucket, err := tx.CreateTopLevelBucket(graphMetaBucket)
162✔
1621
                if err != nil {
162✔
1622
                        return err
×
1623
                }
×
1624

1625
                pruneBucket, err := metaBucket.CreateBucketIfNotExists(pruneLogBucket)
162✔
1626
                if err != nil {
162✔
1627
                        return err
×
1628
                }
×
1629

1630
                var pruneKeyStart [4]byte
162✔
1631
                byteOrder.PutUint32(pruneKeyStart[:], height)
162✔
1632

162✔
1633
                var pruneKeyEnd [4]byte
162✔
1634
                byteOrder.PutUint32(pruneKeyEnd[:], math.MaxUint32)
162✔
1635

162✔
1636
                // To avoid modifying the bucket while traversing, we delete
162✔
1637
                // the keys in a second loop.
162✔
1638
                var pruneKeys [][]byte
162✔
1639
                pruneCursor := pruneBucket.ReadWriteCursor()
162✔
1640
                for k, _ := pruneCursor.Seek(pruneKeyStart[:]); k != nil &&
162✔
1641
                        bytes.Compare(k, pruneKeyEnd[:]) <= 0; k, _ = pruneCursor.Next() {
258✔
1642

96✔
1643
                        pruneKeys = append(pruneKeys, k)
96✔
1644
                }
96✔
1645

1646
                for _, k := range pruneKeys {
258✔
1647
                        if err := pruneBucket.Delete(k); err != nil {
96✔
1648
                                return err
×
1649
                        }
×
1650
                }
1651

1652
                return nil
162✔
1653
        }, func() {
162✔
1654
                removedChans = nil
162✔
1655
        }); err != nil {
162✔
1656
                return nil, err
×
1657
        }
×
1658

1659
        for _, channel := range removedChans {
255✔
1660
                c.rejectCache.remove(channel.ChannelID)
93✔
1661
                c.chanCache.remove(channel.ChannelID)
93✔
1662
        }
93✔
1663

1664
        return removedChans, nil
162✔
1665
}
1666

1667
// PruneTip returns the block height and hash of the latest block that has been
1668
// used to prune channels in the graph. Knowing the "prune tip" allows callers
1669
// to tell if the graph is currently in sync with the current best known UTXO
1670
// state.
1671
func (c *ChannelGraph) PruneTip() (*chainhash.Hash, uint32, error) {
93✔
1672
        var (
93✔
1673
                tipHash   chainhash.Hash
93✔
1674
                tipHeight uint32
93✔
1675
        )
93✔
1676

93✔
1677
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
186✔
1678
                graphMeta := tx.ReadBucket(graphMetaBucket)
93✔
1679
                if graphMeta == nil {
93✔
1680
                        return ErrGraphNotFound
×
1681
                }
×
1682
                pruneBucket := graphMeta.NestedReadBucket(pruneLogBucket)
93✔
1683
                if pruneBucket == nil {
93✔
1684
                        return ErrGraphNeverPruned
×
1685
                }
×
1686

1687
                pruneCursor := pruneBucket.ReadCursor()
93✔
1688

93✔
1689
                // The prune key with the largest block height will be our
93✔
1690
                // prune tip.
93✔
1691
                k, v := pruneCursor.Last()
93✔
1692
                if k == nil {
133✔
1693
                        return ErrGraphNeverPruned
40✔
1694
                }
40✔
1695

1696
                // Once we have the prune tip, the value will be the block hash,
1697
                // and the key the block height.
1698
                copy(tipHash[:], v[:])
57✔
1699
                tipHeight = byteOrder.Uint32(k[:])
57✔
1700

57✔
1701
                return nil
57✔
1702
        }, func() {})
93✔
1703
        if err != nil {
133✔
1704
                return nil, 0, err
40✔
1705
        }
40✔
1706

1707
        return &tipHash, tipHeight, nil
57✔
1708
}
1709

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

148✔
1721
        // TODO(roasbeef): possibly delete from node bucket if node has no more
148✔
1722
        // channels
148✔
1723
        // TODO(roasbeef): don't delete both edges?
148✔
1724

148✔
1725
        c.cacheMu.Lock()
148✔
1726
        defer c.cacheMu.Unlock()
148✔
1727

148✔
1728
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
296✔
1729
                edges := tx.ReadWriteBucket(edgeBucket)
148✔
1730
                if edges == nil {
148✔
1731
                        return ErrEdgeNotFound
×
1732
                }
×
1733
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
148✔
1734
                if edgeIndex == nil {
148✔
1735
                        return ErrEdgeNotFound
×
1736
                }
×
1737
                chanIndex := edges.NestedReadWriteBucket(channelPointBucket)
148✔
1738
                if chanIndex == nil {
148✔
1739
                        return ErrEdgeNotFound
×
1740
                }
×
1741
                nodes := tx.ReadWriteBucket(nodeBucket)
148✔
1742
                if nodes == nil {
148✔
1743
                        return ErrGraphNodeNotFound
×
1744
                }
×
1745
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
148✔
1746
                if err != nil {
148✔
1747
                        return err
×
1748
                }
×
1749

1750
                var rawChanID [8]byte
148✔
1751
                for _, chanID := range chanIDs {
242✔
1752
                        byteOrder.PutUint64(rawChanID[:], chanID)
94✔
1753
                        err := c.delChannelEdgeUnsafe(
94✔
1754
                                edges, edgeIndex, chanIndex, zombieIndex,
94✔
1755
                                rawChanID[:], markZombie, strictZombiePruning,
94✔
1756
                        )
94✔
1757
                        if err != nil {
159✔
1758
                                return err
65✔
1759
                        }
65✔
1760
                }
1761

1762
                return nil
83✔
1763
        }, func() {})
148✔
1764
        if err != nil {
213✔
1765
                return err
65✔
1766
        }
65✔
1767

1768
        for _, chanID := range chanIDs {
112✔
1769
                c.rejectCache.remove(chanID)
29✔
1770
                c.chanCache.remove(chanID)
29✔
1771
        }
29✔
1772

1773
        return nil
83✔
1774
}
1775

1776
// ChannelID attempt to lookup the 8-byte compact channel ID which maps to the
1777
// passed channel point (outpoint). If the passed channel doesn't exist within
1778
// the database, then ErrEdgeNotFound is returned.
1779
func (c *ChannelGraph) ChannelID(chanPoint *wire.OutPoint) (uint64, error) {
5✔
1780
        var chanID uint64
5✔
1781
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
1782
                var err error
5✔
1783
                chanID, err = getChanID(tx, chanPoint)
5✔
1784
                return err
5✔
1785
        }, func() {
10✔
1786
                chanID = 0
5✔
1787
        }); err != nil {
9✔
1788
                return 0, err
4✔
1789
        }
4✔
1790

1791
        return chanID, nil
5✔
1792
}
1793

1794
// getChanID returns the assigned channel ID for a given channel point.
1795
func getChanID(tx kvdb.RTx, chanPoint *wire.OutPoint) (uint64, error) {
5✔
1796
        var b bytes.Buffer
5✔
1797
        if err := writeOutpoint(&b, chanPoint); err != nil {
5✔
1798
                return 0, err
×
1799
        }
×
1800

1801
        edges := tx.ReadBucket(edgeBucket)
5✔
1802
        if edges == nil {
5✔
1803
                return 0, ErrGraphNoEdgesFound
×
1804
        }
×
1805
        chanIndex := edges.NestedReadBucket(channelPointBucket)
5✔
1806
        if chanIndex == nil {
5✔
1807
                return 0, ErrGraphNoEdgesFound
×
1808
        }
×
1809

1810
        chanIDBytes := chanIndex.Get(b.Bytes())
5✔
1811
        if chanIDBytes == nil {
9✔
1812
                return 0, ErrEdgeNotFound
4✔
1813
        }
4✔
1814

1815
        chanID := byteOrder.Uint64(chanIDBytes)
5✔
1816

5✔
1817
        return chanID, nil
5✔
1818
}
1819

1820
// TODO(roasbeef): allow updates to use Batch?
1821

1822
// HighestChanID returns the "highest" known channel ID in the channel graph.
1823
// This represents the "newest" channel from the PoV of the chain. This method
1824
// can be used by peers to quickly determine if they're graphs are in sync.
1825
func (c *ChannelGraph) HighestChanID() (uint64, error) {
7✔
1826
        var cid uint64
7✔
1827

7✔
1828
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
14✔
1829
                edges := tx.ReadBucket(edgeBucket)
7✔
1830
                if edges == nil {
7✔
1831
                        return ErrGraphNoEdgesFound
×
1832
                }
×
1833
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
7✔
1834
                if edgeIndex == nil {
7✔
1835
                        return ErrGraphNoEdgesFound
×
1836
                }
×
1837

1838
                // In order to find the highest chan ID, we'll fetch a cursor
1839
                // and use that to seek to the "end" of our known rage.
1840
                cidCursor := edgeIndex.ReadCursor()
7✔
1841

7✔
1842
                lastChanID, _ := cidCursor.Last()
7✔
1843

7✔
1844
                // If there's no key, then this means that we don't actually
7✔
1845
                // know of any channels, so we'll return a predicable error.
7✔
1846
                if lastChanID == nil {
12✔
1847
                        return ErrGraphNoEdgesFound
5✔
1848
                }
5✔
1849

1850
                // Otherwise, we'll de serialize the channel ID and return it
1851
                // to the caller.
1852
                cid = byteOrder.Uint64(lastChanID)
6✔
1853
                return nil
6✔
1854
        }, func() {
7✔
1855
                cid = 0
7✔
1856
        })
7✔
1857
        if err != nil && err != ErrGraphNoEdgesFound {
7✔
1858
                return 0, err
×
1859
        }
×
1860

1861
        return cid, nil
7✔
1862
}
1863

1864
// ChannelEdge represents the complete set of information for a channel edge in
1865
// the known channel graph. This struct couples the core information of the
1866
// edge as well as each of the known advertised edge policies.
1867
type ChannelEdge struct {
1868
        // Info contains all the static information describing the channel.
1869
        Info *models.ChannelEdgeInfo
1870

1871
        // Policy1 points to the "first" edge policy of the channel containing
1872
        // the dynamic information required to properly route through the edge.
1873
        Policy1 *models.ChannelEdgePolicy
1874

1875
        // Policy2 points to the "second" edge policy of the channel containing
1876
        // the dynamic information required to properly route through the edge.
1877
        Policy2 *models.ChannelEdgePolicy
1878

1879
        // Node1 is "node 1" in the channel. This is the node that would have
1880
        // produced Policy1 if it exists.
1881
        Node1 *LightningNode
1882

1883
        // Node2 is "node 2" in the channel. This is the node that would have
1884
        // produced Policy2 if it exists.
1885
        Node2 *LightningNode
1886
}
1887

1888
// ChanUpdatesInHorizon returns all the known channel edges which have at least
1889
// one edge that has an update timestamp within the specified horizon.
1890
func (c *ChannelGraph) ChanUpdatesInHorizon(startTime,
1891
        endTime time.Time) ([]ChannelEdge, error) {
141✔
1892

141✔
1893
        // To ensure we don't return duplicate ChannelEdges, we'll use an
141✔
1894
        // additional map to keep track of the edges already seen to prevent
141✔
1895
        // re-adding it.
141✔
1896
        var edgesSeen map[uint64]struct{}
141✔
1897
        var edgesToCache map[uint64]ChannelEdge
141✔
1898
        var edgesInHorizon []ChannelEdge
141✔
1899

141✔
1900
        c.cacheMu.Lock()
141✔
1901
        defer c.cacheMu.Unlock()
141✔
1902

141✔
1903
        var hits int
141✔
1904
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
282✔
1905
                edges := tx.ReadBucket(edgeBucket)
141✔
1906
                if edges == nil {
141✔
1907
                        return ErrGraphNoEdgesFound
×
1908
                }
×
1909
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
141✔
1910
                if edgeIndex == nil {
141✔
1911
                        return ErrGraphNoEdgesFound
×
1912
                }
×
1913
                edgeUpdateIndex := edges.NestedReadBucket(edgeUpdateIndexBucket)
141✔
1914
                if edgeUpdateIndex == nil {
141✔
1915
                        return ErrGraphNoEdgesFound
×
1916
                }
×
1917

1918
                nodes := tx.ReadBucket(nodeBucket)
141✔
1919
                if nodes == nil {
141✔
1920
                        return ErrGraphNodesNotFound
×
1921
                }
×
1922

1923
                // We'll now obtain a cursor to perform a range query within
1924
                // the index to find all channels within the horizon.
1925
                updateCursor := edgeUpdateIndex.ReadCursor()
141✔
1926

141✔
1927
                var startTimeBytes, endTimeBytes [8 + 8]byte
141✔
1928
                byteOrder.PutUint64(
141✔
1929
                        startTimeBytes[:8], uint64(startTime.Unix()),
141✔
1930
                )
141✔
1931
                byteOrder.PutUint64(
141✔
1932
                        endTimeBytes[:8], uint64(endTime.Unix()),
141✔
1933
                )
141✔
1934

141✔
1935
                // With our start and end times constructed, we'll step through
141✔
1936
                // the index collecting the info and policy of each update of
141✔
1937
                // each channel that has a last update within the time range.
141✔
1938
                for indexKey, _ := updateCursor.Seek(startTimeBytes[:]); indexKey != nil &&
141✔
1939
                        bytes.Compare(indexKey, endTimeBytes[:]) <= 0; indexKey, _ = updateCursor.Next() {
191✔
1940

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

50✔
1945
                        // If we've already retrieved the info and policies for
50✔
1946
                        // this edge, then we can skip it as we don't need to do
50✔
1947
                        // so again.
50✔
1948
                        chanIDInt := byteOrder.Uint64(chanID)
50✔
1949
                        if _, ok := edgesSeen[chanIDInt]; ok {
69✔
1950
                                continue
19✔
1951
                        }
1952

1953
                        if channel, ok := c.chanCache.get(chanIDInt); ok {
44✔
1954
                                hits++
13✔
1955
                                edgesSeen[chanIDInt] = struct{}{}
13✔
1956
                                edgesInHorizon = append(edgesInHorizon, channel)
13✔
1957
                                continue
13✔
1958
                        }
1959

1960
                        // First, we'll fetch the static edge information.
1961
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
22✔
1962
                        if err != nil {
22✔
1963
                                chanID := byteOrder.Uint64(chanID)
×
1964
                                return fmt.Errorf("unable to fetch info for "+
×
1965
                                        "edge with chan_id=%v: %v", chanID, err)
×
1966
                        }
×
1967

1968
                        // With the static information obtained, we'll now
1969
                        // fetch the dynamic policy info.
1970
                        edge1, edge2, err := fetchChanEdgePolicies(
22✔
1971
                                edgeIndex, edges, chanID,
22✔
1972
                        )
22✔
1973
                        if err != nil {
22✔
1974
                                chanID := byteOrder.Uint64(chanID)
×
1975
                                return fmt.Errorf("unable to fetch policies "+
×
1976
                                        "for edge with chan_id=%v: %v", chanID,
×
1977
                                        err)
×
1978
                        }
×
1979

1980
                        node1, err := fetchLightningNode(
22✔
1981
                                nodes, edgeInfo.NodeKey1Bytes[:],
22✔
1982
                        )
22✔
1983
                        if err != nil {
22✔
1984
                                return err
×
1985
                        }
×
1986

1987
                        node2, err := fetchLightningNode(
22✔
1988
                                nodes, edgeInfo.NodeKey2Bytes[:],
22✔
1989
                        )
22✔
1990
                        if err != nil {
22✔
1991
                                return err
×
1992
                        }
×
1993

1994
                        // Finally, we'll collate this edge with the rest of
1995
                        // edges to be returned.
1996
                        edgesSeen[chanIDInt] = struct{}{}
22✔
1997
                        channel := ChannelEdge{
22✔
1998
                                Info:    &edgeInfo,
22✔
1999
                                Policy1: edge1,
22✔
2000
                                Policy2: edge2,
22✔
2001
                                Node1:   &node1,
22✔
2002
                                Node2:   &node2,
22✔
2003
                        }
22✔
2004
                        edgesInHorizon = append(edgesInHorizon, channel)
22✔
2005
                        edgesToCache[chanIDInt] = channel
22✔
2006
                }
2007

2008
                return nil
141✔
2009
        }, func() {
141✔
2010
                edgesSeen = make(map[uint64]struct{})
141✔
2011
                edgesToCache = make(map[uint64]ChannelEdge)
141✔
2012
                edgesInHorizon = nil
141✔
2013
        })
141✔
2014
        switch {
141✔
2015
        case err == ErrGraphNoEdgesFound:
×
2016
                fallthrough
×
2017
        case err == ErrGraphNodesNotFound:
×
2018
                break
×
2019

2020
        case err != nil:
×
2021
                return nil, err
×
2022
        }
2023

2024
        // Insert any edges loaded from disk into the cache.
2025
        for chanid, channel := range edgesToCache {
163✔
2026
                c.chanCache.insert(chanid, channel)
22✔
2027
        }
22✔
2028

2029
        log.Debugf("ChanUpdatesInHorizon hit percentage: %f (%d/%d)",
141✔
2030
                float64(hits)/float64(len(edgesInHorizon)), hits,
141✔
2031
                len(edgesInHorizon))
141✔
2032

141✔
2033
        return edgesInHorizon, nil
141✔
2034
}
2035

2036
// NodeUpdatesInHorizon returns all the known lightning node which have an
2037
// update timestamp within the passed range. This method can be used by two
2038
// nodes to quickly determine if they have the same set of up to date node
2039
// announcements.
2040
func (c *ChannelGraph) NodeUpdatesInHorizon(startTime,
2041
        endTime time.Time) ([]LightningNode, error) {
12✔
2042

12✔
2043
        var nodesInHorizon []LightningNode
12✔
2044

12✔
2045
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
24✔
2046
                nodes := tx.ReadBucket(nodeBucket)
12✔
2047
                if nodes == nil {
12✔
2048
                        return ErrGraphNodesNotFound
×
2049
                }
×
2050

2051
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
12✔
2052
                if nodeUpdateIndex == nil {
12✔
2053
                        return ErrGraphNodesNotFound
×
2054
                }
×
2055

2056
                // We'll now obtain a cursor to perform a range query within
2057
                // the index to find all node announcements within the horizon.
2058
                updateCursor := nodeUpdateIndex.ReadCursor()
12✔
2059

12✔
2060
                var startTimeBytes, endTimeBytes [8 + 33]byte
12✔
2061
                byteOrder.PutUint64(
12✔
2062
                        startTimeBytes[:8], uint64(startTime.Unix()),
12✔
2063
                )
12✔
2064
                byteOrder.PutUint64(
12✔
2065
                        endTimeBytes[:8], uint64(endTime.Unix()),
12✔
2066
                )
12✔
2067

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

33✔
2074
                        nodePub := indexKey[8:]
33✔
2075
                        node, err := fetchLightningNode(nodes, nodePub)
33✔
2076
                        if err != nil {
33✔
2077
                                return err
×
2078
                        }
×
2079

2080
                        nodesInHorizon = append(nodesInHorizon, node)
33✔
2081
                }
2082

2083
                return nil
12✔
2084
        }, func() {
12✔
2085
                nodesInHorizon = nil
12✔
2086
        })
12✔
2087
        switch {
12✔
2088
        case err == ErrGraphNoEdgesFound:
×
2089
                fallthrough
×
2090
        case err == ErrGraphNodesNotFound:
×
2091
                break
×
2092

2093
        case err != nil:
×
2094
                return nil, err
×
2095
        }
2096

2097
        return nodesInHorizon, nil
12✔
2098
}
2099

2100
// FilterKnownChanIDs takes a set of channel IDs and return the subset of chan
2101
// ID's that we don't know and are not known zombies of the passed set. In other
2102
// words, we perform a set difference of our set of chan ID's and the ones
2103
// passed in. This method can be used by callers to determine the set of
2104
// channels another peer knows of that we don't.
2105
func (c *ChannelGraph) FilterKnownChanIDs(chansInfo []ChannelUpdateInfo,
2106
        isZombieChan func(time.Time, time.Time) bool) ([]uint64, error) {
124✔
2107

124✔
2108
        var newChanIDs []uint64
124✔
2109

124✔
2110
        c.cacheMu.Lock()
124✔
2111
        defer c.cacheMu.Unlock()
124✔
2112

124✔
2113
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
248✔
2114
                edges := tx.ReadBucket(edgeBucket)
124✔
2115
                if edges == nil {
124✔
2116
                        return ErrGraphNoEdgesFound
×
2117
                }
×
2118
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
124✔
2119
                if edgeIndex == nil {
124✔
2120
                        return ErrGraphNoEdgesFound
×
2121
                }
×
2122

2123
                // Fetch the zombie index, it may not exist if no edges have
2124
                // ever been marked as zombies. If the index has been
2125
                // initialized, we will use it later to skip known zombie edges.
2126
                zombieIndex := edges.NestedReadBucket(zombieBucket)
124✔
2127

124✔
2128
                // We'll run through the set of chanIDs and collate only the
124✔
2129
                // set of channel that are unable to be found within our db.
124✔
2130
                var cidBytes [8]byte
124✔
2131
                for _, info := range chansInfo {
228✔
2132
                        scid := info.ShortChannelID.ToUint64()
104✔
2133
                        byteOrder.PutUint64(cidBytes[:], scid)
104✔
2134

104✔
2135
                        // If the edge is already known, skip it.
104✔
2136
                        if v := edgeIndex.Get(cidBytes[:]); v != nil {
128✔
2137
                                continue
24✔
2138
                        }
2139

2140
                        // If the edge is a known zombie, skip it.
2141
                        if zombieIndex != nil {
168✔
2142
                                isZombie, _, _ := isZombieEdge(
84✔
2143
                                        zombieIndex, scid,
84✔
2144
                                )
84✔
2145

84✔
2146
                                isStillZombie := isZombieChan(
84✔
2147
                                        info.Node1UpdateTimestamp,
84✔
2148
                                        info.Node2UpdateTimestamp,
84✔
2149
                                )
84✔
2150

84✔
2151
                                switch {
84✔
2152
                                // If the edge is a known zombie and if we
2153
                                // would still consider it a zombie given the
2154
                                // latest update timestamps, then we skip this
2155
                                // channel.
2156
                                case isZombie && isStillZombie:
27✔
2157
                                        continue
27✔
2158

2159
                                // Otherwise, if we have marked it as a zombie
2160
                                // but the latest update timestamps could bring
2161
                                // it back from the dead, then we mark it alive,
2162
                                // and we let it be added to the set of IDs to
2163
                                // query our peer for.
2164
                                case isZombie && !isStillZombie:
20✔
2165
                                        err := c.markEdgeLiveUnsafe(tx, scid)
20✔
2166
                                        if err != nil {
20✔
2167
                                                return err
×
2168
                                        }
×
2169
                                }
2170
                        }
2171

2172
                        newChanIDs = append(newChanIDs, scid)
57✔
2173
                }
2174

2175
                return nil
124✔
2176
        }, func() {
124✔
2177
                newChanIDs = nil
124✔
2178
        })
124✔
2179
        switch {
124✔
2180
        // If we don't know of any edges yet, then we'll return the entire set
2181
        // of chan IDs specified.
2182
        case err == ErrGraphNoEdgesFound:
×
2183
                ogChanIDs := make([]uint64, len(chansInfo))
×
2184
                for i, info := range chansInfo {
×
2185
                        ogChanIDs[i] = info.ShortChannelID.ToUint64()
×
2186
                }
×
2187

2188
                return ogChanIDs, nil
×
2189

2190
        case err != nil:
×
2191
                return nil, err
×
2192
        }
2193

2194
        return newChanIDs, nil
124✔
2195
}
2196

2197
// ChannelUpdateInfo couples the SCID of a channel with the timestamps of the
2198
// latest received channel updates for the channel.
2199
type ChannelUpdateInfo struct {
2200
        // ShortChannelID is the SCID identifier of the channel.
2201
        ShortChannelID lnwire.ShortChannelID
2202

2203
        // Node1UpdateTimestamp is the timestamp of the latest received update
2204
        // from the node 1 channel peer. This will be set to zero time if no
2205
        // update has yet been received from this node.
2206
        Node1UpdateTimestamp time.Time
2207

2208
        // Node2UpdateTimestamp is the timestamp of the latest received update
2209
        // from the node 2 channel peer. This will be set to zero time if no
2210
        // update has yet been received from this node.
2211
        Node2UpdateTimestamp time.Time
2212
}
2213

2214
// BlockChannelRange represents a range of channels for a given block height.
2215
type BlockChannelRange struct {
2216
        // Height is the height of the block all of the channels below were
2217
        // included in.
2218
        Height uint32
2219

2220
        // Channels is the list of channels identified by their short ID
2221
        // representation known to us that were included in the block height
2222
        // above. The list may include channel update timestamp information if
2223
        // requested.
2224
        Channels []ChannelUpdateInfo
2225
}
2226

2227
// FilterChannelRange returns the channel ID's of all known channels which were
2228
// mined in a block height within the passed range. The channel IDs are grouped
2229
// by their common block height. This method can be used to quickly share with a
2230
// peer the set of channels we know of within a particular range to catch them
2231
// up after a period of time offline. If withTimestamps is true then the
2232
// timestamp info of the latest received channel update messages of the channel
2233
// will be included in the response.
2234
func (c *ChannelGraph) FilterChannelRange(startHeight,
2235
        endHeight uint32, withTimestamps bool) ([]BlockChannelRange, error) {
15✔
2236

15✔
2237
        startChanID := &lnwire.ShortChannelID{
15✔
2238
                BlockHeight: startHeight,
15✔
2239
        }
15✔
2240

15✔
2241
        endChanID := lnwire.ShortChannelID{
15✔
2242
                BlockHeight: endHeight,
15✔
2243
                TxIndex:     math.MaxUint32 & 0x00ffffff,
15✔
2244
                TxPosition:  math.MaxUint16,
15✔
2245
        }
15✔
2246

15✔
2247
        // As we need to perform a range scan, we'll convert the starting and
15✔
2248
        // ending height to their corresponding values when encoded using short
15✔
2249
        // channel ID's.
15✔
2250
        var chanIDStart, chanIDEnd [8]byte
15✔
2251
        byteOrder.PutUint64(chanIDStart[:], startChanID.ToUint64())
15✔
2252
        byteOrder.PutUint64(chanIDEnd[:], endChanID.ToUint64())
15✔
2253

15✔
2254
        var channelsPerBlock map[uint32][]ChannelUpdateInfo
15✔
2255
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
30✔
2256
                edges := tx.ReadBucket(edgeBucket)
15✔
2257
                if edges == nil {
15✔
2258
                        return ErrGraphNoEdgesFound
×
2259
                }
×
2260
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
15✔
2261
                if edgeIndex == nil {
15✔
2262
                        return ErrGraphNoEdgesFound
×
2263
                }
×
2264

2265
                cursor := edgeIndex.ReadCursor()
15✔
2266

15✔
2267
                // We'll now iterate through the database, and find each
15✔
2268
                // channel ID that resides within the specified range.
15✔
2269
                for k, v := cursor.Seek(chanIDStart[:]); k != nil &&
15✔
2270
                        bytes.Compare(k, chanIDEnd[:]) <= 0; k, v = cursor.Next() {
63✔
2271
                        // Don't send alias SCIDs during gossip sync.
48✔
2272
                        edgeReader := bytes.NewReader(v)
48✔
2273
                        edgeInfo, err := deserializeChanEdgeInfo(edgeReader)
48✔
2274
                        if err != nil {
48✔
2275
                                return err
×
2276
                        }
×
2277

2278
                        if edgeInfo.AuthProof == nil {
52✔
2279
                                continue
4✔
2280
                        }
2281

2282
                        // This channel ID rests within the target range, so
2283
                        // we'll add it to our returned set.
2284
                        rawCid := byteOrder.Uint64(k)
48✔
2285
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
48✔
2286

48✔
2287
                        chanInfo := ChannelUpdateInfo{
48✔
2288
                                ShortChannelID: cid,
48✔
2289
                        }
48✔
2290

48✔
2291
                        if !withTimestamps {
70✔
2292
                                channelsPerBlock[cid.BlockHeight] = append(
22✔
2293
                                        channelsPerBlock[cid.BlockHeight],
22✔
2294
                                        chanInfo,
22✔
2295
                                )
22✔
2296

22✔
2297
                                continue
22✔
2298
                        }
2299

2300
                        node1Key, node2Key := computeEdgePolicyKeys(&edgeInfo)
26✔
2301

26✔
2302
                        rawPolicy := edges.Get(node1Key)
26✔
2303
                        if len(rawPolicy) != 0 {
36✔
2304
                                r := bytes.NewReader(rawPolicy)
10✔
2305

10✔
2306
                                edge, err := deserializeChanEdgePolicyRaw(r)
10✔
2307
                                if err != nil && !errors.Is(
10✔
2308
                                        err, ErrEdgePolicyOptionalFieldNotFound,
10✔
2309
                                ) {
10✔
2310

×
2311
                                        return err
×
2312
                                }
×
2313

2314
                                chanInfo.Node1UpdateTimestamp = edge.LastUpdate
10✔
2315
                        }
2316

2317
                        rawPolicy = edges.Get(node2Key)
26✔
2318
                        if len(rawPolicy) != 0 {
41✔
2319
                                r := bytes.NewReader(rawPolicy)
15✔
2320

15✔
2321
                                edge, err := deserializeChanEdgePolicyRaw(r)
15✔
2322
                                if err != nil && !errors.Is(
15✔
2323
                                        err, ErrEdgePolicyOptionalFieldNotFound,
15✔
2324
                                ) {
15✔
2325

×
2326
                                        return err
×
2327
                                }
×
2328

2329
                                chanInfo.Node2UpdateTimestamp = edge.LastUpdate
15✔
2330
                        }
2331

2332
                        channelsPerBlock[cid.BlockHeight] = append(
26✔
2333
                                channelsPerBlock[cid.BlockHeight], chanInfo,
26✔
2334
                        )
26✔
2335
                }
2336

2337
                return nil
15✔
2338
        }, func() {
15✔
2339
                channelsPerBlock = make(map[uint32][]ChannelUpdateInfo)
15✔
2340
        })
15✔
2341

2342
        switch {
15✔
2343
        // If we don't know of any channels yet, then there's nothing to
2344
        // filter, so we'll return an empty slice.
2345
        case err == ErrGraphNoEdgesFound || len(channelsPerBlock) == 0:
7✔
2346
                return nil, nil
7✔
2347

2348
        case err != nil:
×
2349
                return nil, err
×
2350
        }
2351

2352
        // Return the channel ranges in ascending block height order.
2353
        blocks := make([]uint32, 0, len(channelsPerBlock))
12✔
2354
        for block := range channelsPerBlock {
38✔
2355
                blocks = append(blocks, block)
26✔
2356
        }
26✔
2357
        sort.Slice(blocks, func(i, j int) bool {
35✔
2358
                return blocks[i] < blocks[j]
23✔
2359
        })
23✔
2360

2361
        channelRanges := make([]BlockChannelRange, 0, len(channelsPerBlock))
12✔
2362
        for _, block := range blocks {
38✔
2363
                channelRanges = append(channelRanges, BlockChannelRange{
26✔
2364
                        Height:   block,
26✔
2365
                        Channels: channelsPerBlock[block],
26✔
2366
                })
26✔
2367
        }
26✔
2368

2369
        return channelRanges, nil
12✔
2370
}
2371

2372
// FetchChanInfos returns the set of channel edges that correspond to the passed
2373
// channel ID's. If an edge is the query is unknown to the database, it will
2374
// skipped and the result will contain only those edges that exist at the time
2375
// of the query. This can be used to respond to peer queries that are seeking to
2376
// fill in gaps in their view of the channel graph.
2377
//
2378
// NOTE: An optional transaction may be provided. If none is provided, then a
2379
// new one will be created.
2380
func (c *ChannelGraph) FetchChanInfos(tx kvdb.RTx, chanIDs []uint64) (
2381
        []ChannelEdge, error) {
28✔
2382
        // TODO(roasbeef): sort cids?
28✔
2383

28✔
2384
        var (
28✔
2385
                chanEdges []ChannelEdge
28✔
2386
                cidBytes  [8]byte
28✔
2387
        )
28✔
2388

28✔
2389
        fetchChanInfos := func(tx kvdb.RTx) error {
56✔
2390
                edges := tx.ReadBucket(edgeBucket)
28✔
2391
                if edges == nil {
28✔
2392
                        return ErrGraphNoEdgesFound
×
2393
                }
×
2394
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
28✔
2395
                if edgeIndex == nil {
28✔
2396
                        return ErrGraphNoEdgesFound
×
2397
                }
×
2398
                nodes := tx.ReadBucket(nodeBucket)
28✔
2399
                if nodes == nil {
28✔
2400
                        return ErrGraphNotFound
×
2401
                }
×
2402

2403
                for _, cid := range chanIDs {
63✔
2404
                        byteOrder.PutUint64(cidBytes[:], cid)
35✔
2405

35✔
2406
                        // First, we'll fetch the static edge information. If
35✔
2407
                        // the edge is unknown, we will skip the edge and
35✔
2408
                        // continue gathering all known edges.
35✔
2409
                        edgeInfo, err := fetchChanEdgeInfo(
35✔
2410
                                edgeIndex, cidBytes[:],
35✔
2411
                        )
35✔
2412
                        switch {
35✔
2413
                        case errors.Is(err, ErrEdgeNotFound):
27✔
2414
                                continue
27✔
2415
                        case err != nil:
×
2416
                                return err
×
2417
                        }
2418

2419
                        // With the static information obtained, we'll now
2420
                        // fetch the dynamic policy info.
2421
                        edge1, edge2, err := fetchChanEdgePolicies(
12✔
2422
                                edgeIndex, edges, cidBytes[:],
12✔
2423
                        )
12✔
2424
                        if err != nil {
12✔
2425
                                return err
×
2426
                        }
×
2427

2428
                        node1, err := fetchLightningNode(
12✔
2429
                                nodes, edgeInfo.NodeKey1Bytes[:],
12✔
2430
                        )
12✔
2431
                        if err != nil {
12✔
2432
                                return err
×
2433
                        }
×
2434

2435
                        node2, err := fetchLightningNode(
12✔
2436
                                nodes, edgeInfo.NodeKey2Bytes[:],
12✔
2437
                        )
12✔
2438
                        if err != nil {
12✔
2439
                                return err
×
2440
                        }
×
2441

2442
                        chanEdges = append(chanEdges, ChannelEdge{
12✔
2443
                                Info:    &edgeInfo,
12✔
2444
                                Policy1: edge1,
12✔
2445
                                Policy2: edge2,
12✔
2446
                                Node1:   &node1,
12✔
2447
                                Node2:   &node2,
12✔
2448
                        })
12✔
2449
                }
2450
                return nil
28✔
2451
        }
2452

2453
        if tx == nil {
36✔
2454
                err := kvdb.View(c.db, fetchChanInfos, func() {
16✔
2455
                        chanEdges = nil
8✔
2456
                })
8✔
2457
                if err != nil {
8✔
2458
                        return nil, err
×
2459
                }
×
2460

2461
                return chanEdges, nil
8✔
2462
        }
2463

2464
        err := fetchChanInfos(tx)
20✔
2465
        if err != nil {
20✔
2466
                return nil, err
×
2467
        }
×
2468

2469
        return chanEdges, nil
20✔
2470
}
2471

2472
func delEdgeUpdateIndexEntry(edgesBucket kvdb.RwBucket, chanID uint64,
2473
        edge1, edge2 *models.ChannelEdgePolicy) error {
141✔
2474

141✔
2475
        // First, we'll fetch the edge update index bucket which currently
141✔
2476
        // stores an entry for the channel we're about to delete.
141✔
2477
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
141✔
2478
        if updateIndex == nil {
141✔
2479
                // No edges in bucket, return early.
×
2480
                return nil
×
2481
        }
×
2482

2483
        // Now that we have the bucket, we'll attempt to construct a template
2484
        // for the index key: updateTime || chanid.
2485
        var indexKey [8 + 8]byte
141✔
2486
        byteOrder.PutUint64(indexKey[8:], chanID)
141✔
2487

141✔
2488
        // With the template constructed, we'll attempt to delete an entry that
141✔
2489
        // would have been created by both edges: we'll alternate the update
141✔
2490
        // times, as one may had overridden the other.
141✔
2491
        if edge1 != nil {
155✔
2492
                byteOrder.PutUint64(indexKey[:8], uint64(edge1.LastUpdate.Unix()))
14✔
2493
                if err := updateIndex.Delete(indexKey[:]); err != nil {
14✔
2494
                        return err
×
2495
                }
×
2496
        }
2497

2498
        // We'll also attempt to delete the entry that may have been created by
2499
        // the second edge.
2500
        if edge2 != nil {
157✔
2501
                byteOrder.PutUint64(indexKey[:8], uint64(edge2.LastUpdate.Unix()))
16✔
2502
                if err := updateIndex.Delete(indexKey[:]); err != nil {
16✔
2503
                        return err
×
2504
                }
×
2505
        }
2506

2507
        return nil
141✔
2508
}
2509

2510
// delChannelEdgeUnsafe deletes the edge with the given chanID from the graph
2511
// cache. It then goes on to delete any policy info and edge info for this
2512
// channel from the DB and finally, if isZombie is true, it will add an entry
2513
// for this channel in the zombie index.
2514
//
2515
// NOTE: this method MUST only be called if the cacheMu has already been
2516
// acquired.
2517
func (c *ChannelGraph) delChannelEdgeUnsafe(edges, edgeIndex, chanIndex,
2518
        zombieIndex kvdb.RwBucket, chanID []byte, isZombie,
2519
        strictZombie bool) error {
206✔
2520

206✔
2521
        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
206✔
2522
        if err != nil {
271✔
2523
                return err
65✔
2524
        }
65✔
2525

2526
        if c.graphCache != nil {
282✔
2527
                c.graphCache.RemoveChannel(
141✔
2528
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
141✔
2529
                        edgeInfo.ChannelID,
141✔
2530
                )
141✔
2531
        }
141✔
2532

2533
        // We'll also remove the entry in the edge update index bucket before
2534
        // we delete the edges themselves so we can access their last update
2535
        // times.
2536
        cid := byteOrder.Uint64(chanID)
141✔
2537
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
141✔
2538
        if err != nil {
141✔
2539
                return err
×
2540
        }
×
2541
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
141✔
2542
        if err != nil {
141✔
2543
                return err
×
2544
        }
×
2545

2546
        // The edge key is of the format pubKey || chanID. First we construct
2547
        // the latter half, populating the channel ID.
2548
        var edgeKey [33 + 8]byte
141✔
2549
        copy(edgeKey[33:], chanID)
141✔
2550

141✔
2551
        // With the latter half constructed, copy over the first public key to
141✔
2552
        // delete the edge in this direction, then the second to delete the
141✔
2553
        // edge in the opposite direction.
141✔
2554
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
141✔
2555
        if edges.Get(edgeKey[:]) != nil {
282✔
2556
                if err := edges.Delete(edgeKey[:]); err != nil {
141✔
2557
                        return err
×
2558
                }
×
2559
        }
2560
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
141✔
2561
        if edges.Get(edgeKey[:]) != nil {
282✔
2562
                if err := edges.Delete(edgeKey[:]); err != nil {
141✔
2563
                        return err
×
2564
                }
×
2565
        }
2566

2567
        // As part of deleting the edge we also remove all disabled entries
2568
        // from the edgePolicyDisabledIndex bucket. We do that for both directions.
2569
        updateEdgePolicyDisabledIndex(edges, cid, false, false)
141✔
2570
        updateEdgePolicyDisabledIndex(edges, cid, true, false)
141✔
2571

141✔
2572
        // With the edge data deleted, we can purge the information from the two
141✔
2573
        // edge indexes.
141✔
2574
        if err := edgeIndex.Delete(chanID); err != nil {
141✔
2575
                return err
×
2576
        }
×
2577
        var b bytes.Buffer
141✔
2578
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
141✔
2579
                return err
×
2580
        }
×
2581
        if err := chanIndex.Delete(b.Bytes()); err != nil {
141✔
2582
                return err
×
2583
        }
×
2584

2585
        // Finally, we'll mark the edge as a zombie within our index if it's
2586
        // being removed due to the channel becoming a zombie. We do this to
2587
        // ensure we don't store unnecessary data for spent channels.
2588
        if !isZombie {
259✔
2589
                return nil
118✔
2590
        }
118✔
2591

2592
        nodeKey1, nodeKey2 := edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes
27✔
2593
        if strictZombie {
30✔
2594
                nodeKey1, nodeKey2 = makeZombiePubkeys(&edgeInfo, edge1, edge2)
3✔
2595
        }
3✔
2596

2597
        return markEdgeZombie(
27✔
2598
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
27✔
2599
        )
27✔
2600
}
2601

2602
// makeZombiePubkeys derives the node pubkeys to store in the zombie index for a
2603
// particular pair of channel policies. The return values are one of:
2604
//  1. (pubkey1, pubkey2)
2605
//  2. (pubkey1, blank)
2606
//  3. (blank, pubkey2)
2607
//
2608
// A blank pubkey means that corresponding node will be unable to resurrect a
2609
// channel on its own. For example, node1 may continue to publish recent
2610
// updates, but node2 has fallen way behind. After marking an edge as a zombie,
2611
// we don't want another fresh update from node1 to resurrect, as the edge can
2612
// only become live once node2 finally sends something recent.
2613
//
2614
// In the case where we have neither update, we allow either party to resurrect
2615
// the channel. If the channel were to be marked zombie again, it would be
2616
// marked with the correct lagging channel since we received an update from only
2617
// one side.
2618
func makeZombiePubkeys(info *models.ChannelEdgeInfo,
2619
        e1, e2 *models.ChannelEdgePolicy) ([33]byte, [33]byte) {
3✔
2620

3✔
2621
        switch {
3✔
2622
        // If we don't have either edge policy, we'll return both pubkeys so
2623
        // that the channel can be resurrected by either party.
2624
        case e1 == nil && e2 == nil:
×
2625
                return info.NodeKey1Bytes, info.NodeKey2Bytes
×
2626

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

2634
        // Otherwise, we're missing edge2 or edge2 is the older side, so we
2635
        // return a blank pubkey for edge1. In this case, only an update from
2636
        // edge2 can resurect the channel.
2637
        default:
2✔
2638
                return [33]byte{}, info.NodeKey2Bytes
2✔
2639
        }
2640
}
2641

2642
// UpdateEdgePolicy updates the edge routing policy for a single directed edge
2643
// within the database for the referenced channel. The `flags` attribute within
2644
// the ChannelEdgePolicy determines which of the directed edges are being
2645
// updated. If the flag is 1, then the first node's information is being
2646
// updated, otherwise it's the second node's information. The node ordering is
2647
// determined by the lexicographical ordering of the identity public keys of the
2648
// nodes on either side of the channel.
2649
func (c *ChannelGraph) UpdateEdgePolicy(edge *models.ChannelEdgePolicy,
2650
        op ...batch.SchedulerOption) error {
2,621✔
2651

2,621✔
2652
        var (
2,621✔
2653
                isUpdate1    bool
2,621✔
2654
                edgeNotFound bool
2,621✔
2655
        )
2,621✔
2656

2,621✔
2657
        r := &batch.Request{
2,621✔
2658
                Reset: func() {
5,242✔
2659
                        isUpdate1 = false
2,621✔
2660
                        edgeNotFound = false
2,621✔
2661
                },
2,621✔
2662
                Update: func(tx kvdb.RwTx) error {
2,621✔
2663
                        var err error
2,621✔
2664
                        isUpdate1, err = updateEdgePolicy(
2,621✔
2665
                                tx, edge, c.graphCache,
2,621✔
2666
                        )
2,621✔
2667

2,621✔
2668
                        // Silence ErrEdgeNotFound so that the batch can
2,621✔
2669
                        // succeed, but propagate the error via local state.
2,621✔
2670
                        if errors.Is(err, ErrEdgeNotFound) {
2,623✔
2671
                                edgeNotFound = true
2✔
2672
                                return nil
2✔
2673
                        }
2✔
2674

2675
                        return err
2,619✔
2676
                },
2677
                OnCommit: func(err error) error {
2,621✔
2678
                        switch {
2,621✔
2679
                        case err != nil:
×
2680
                                return err
×
2681
                        case edgeNotFound:
2✔
2682
                                return ErrEdgeNotFound
2✔
2683
                        default:
2,619✔
2684
                                c.updateEdgeCache(edge, isUpdate1)
2,619✔
2685
                                return nil
2,619✔
2686
                        }
2687
                },
2688
        }
2689

2690
        for _, f := range op {
2,625✔
2691
                f(r)
4✔
2692
        }
4✔
2693

2694
        return c.chanScheduler.Execute(r)
2,621✔
2695
}
2696

2697
func (c *ChannelGraph) updateEdgeCache(e *models.ChannelEdgePolicy,
2698
        isUpdate1 bool) {
2,619✔
2699

2,619✔
2700
        // If an entry for this channel is found in reject cache, we'll modify
2,619✔
2701
        // the entry with the updated timestamp for the direction that was just
2,619✔
2702
        // written. If the edge doesn't exist, we'll load the cache entry lazily
2,619✔
2703
        // during the next query for this edge.
2,619✔
2704
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
2,633✔
2705
                if isUpdate1 {
23✔
2706
                        entry.upd1Time = e.LastUpdate.Unix()
9✔
2707
                } else {
18✔
2708
                        entry.upd2Time = e.LastUpdate.Unix()
9✔
2709
                }
9✔
2710
                c.rejectCache.insert(e.ChannelID, entry)
14✔
2711
        }
2712

2713
        // If an entry for this channel is found in channel cache, we'll modify
2714
        // the entry with the updated policy for the direction that was just
2715
        // written. If the edge doesn't exist, we'll defer loading the info and
2716
        // policies and lazily read from disk during the next query.
2717
        if channel, ok := c.chanCache.get(e.ChannelID); ok {
2,623✔
2718
                if isUpdate1 {
8✔
2719
                        channel.Policy1 = e
4✔
2720
                } else {
8✔
2721
                        channel.Policy2 = e
4✔
2722
                }
4✔
2723
                c.chanCache.insert(e.ChannelID, channel)
4✔
2724
        }
2725
}
2726

2727
// updateEdgePolicy attempts to update an edge's policy within the relevant
2728
// buckets using an existing database transaction. The returned boolean will be
2729
// true if the updated policy belongs to node1, and false if the policy belonged
2730
// to node2.
2731
func updateEdgePolicy(tx kvdb.RwTx, edge *models.ChannelEdgePolicy,
2732
        graphCache *GraphCache) (bool, error) {
2,621✔
2733

2,621✔
2734
        edges := tx.ReadWriteBucket(edgeBucket)
2,621✔
2735
        if edges == nil {
2,621✔
2736
                return false, ErrEdgeNotFound
×
2737
        }
×
2738
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
2,621✔
2739
        if edgeIndex == nil {
2,621✔
2740
                return false, ErrEdgeNotFound
×
2741
        }
×
2742

2743
        // Create the channelID key be converting the channel ID
2744
        // integer into a byte slice.
2745
        var chanID [8]byte
2,621✔
2746
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
2,621✔
2747

2,621✔
2748
        // With the channel ID, we then fetch the value storing the two
2,621✔
2749
        // nodes which connect this channel edge.
2,621✔
2750
        nodeInfo := edgeIndex.Get(chanID[:])
2,621✔
2751
        if nodeInfo == nil {
2,623✔
2752
                return false, ErrEdgeNotFound
2✔
2753
        }
2✔
2754

2755
        // Depending on the flags value passed above, either the first
2756
        // or second edge policy is being updated.
2757
        var fromNode, toNode []byte
2,619✔
2758
        var isUpdate1 bool
2,619✔
2759
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
3,934✔
2760
                fromNode = nodeInfo[:33]
1,315✔
2761
                toNode = nodeInfo[33:66]
1,315✔
2762
                isUpdate1 = true
1,315✔
2763
        } else {
2,623✔
2764
                fromNode = nodeInfo[33:66]
1,308✔
2765
                toNode = nodeInfo[:33]
1,308✔
2766
                isUpdate1 = false
1,308✔
2767
        }
1,308✔
2768

2769
        // Finally, with the direction of the edge being updated
2770
        // identified, we update the on-disk edge representation.
2771
        err := putChanEdgePolicy(edges, edge, fromNode, toNode)
2,619✔
2772
        if err != nil {
2,619✔
2773
                return false, err
×
2774
        }
×
2775

2776
        var (
2,619✔
2777
                fromNodePubKey route.Vertex
2,619✔
2778
                toNodePubKey   route.Vertex
2,619✔
2779
        )
2,619✔
2780
        copy(fromNodePubKey[:], fromNode)
2,619✔
2781
        copy(toNodePubKey[:], toNode)
2,619✔
2782

2,619✔
2783
        if graphCache != nil {
4,862✔
2784
                graphCache.UpdatePolicy(
2,243✔
2785
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
2,243✔
2786
                )
2,243✔
2787
        }
2,243✔
2788

2789
        return isUpdate1, nil
2,619✔
2790
}
2791

2792
// LightningNode represents an individual vertex/node within the channel graph.
2793
// A node is connected to other nodes by one or more channel edges emanating
2794
// from it. As the graph is directed, a node will also have an incoming edge
2795
// attached to it for each outgoing edge.
2796
type LightningNode struct {
2797
        // PubKeyBytes is the raw bytes of the public key of the target node.
2798
        PubKeyBytes [33]byte
2799
        pubKey      *btcec.PublicKey
2800

2801
        // HaveNodeAnnouncement indicates whether we received a node
2802
        // announcement for this particular node. If true, the remaining fields
2803
        // will be set, if false only the PubKey is known for this node.
2804
        HaveNodeAnnouncement bool
2805

2806
        // LastUpdate is the last time the vertex information for this node has
2807
        // been updated.
2808
        LastUpdate time.Time
2809

2810
        // Address is the TCP address this node is reachable over.
2811
        Addresses []net.Addr
2812

2813
        // Color is the selected color for the node.
2814
        Color color.RGBA
2815

2816
        // Alias is a nick-name for the node. The alias can be used to confirm
2817
        // a node's identity or to serve as a short ID for an address book.
2818
        Alias string
2819

2820
        // AuthSigBytes is the raw signature under the advertised public key
2821
        // which serves to authenticate the attributes announced by this node.
2822
        AuthSigBytes []byte
2823

2824
        // Features is the list of protocol features supported by this node.
2825
        Features *lnwire.FeatureVector
2826

2827
        // ExtraOpaqueData is the set of data that was appended to this
2828
        // message, some of which we may not actually know how to iterate or
2829
        // parse. By holding onto this data, we ensure that we're able to
2830
        // properly validate the set of signatures that cover these new fields,
2831
        // and ensure we're able to make upgrades to the network in a forwards
2832
        // compatible manner.
2833
        ExtraOpaqueData []byte
2834

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

2838
        // TODO(roasbeef): add update method and fetch?
2839
}
2840

2841
// PubKey is the node's long-term identity public key. This key will be used to
2842
// authenticated any advertisements/updates sent by the node.
2843
//
2844
// NOTE: By having this method to access an attribute, we ensure we only need
2845
// to fully deserialize the pubkey if absolutely necessary.
2846
func (l *LightningNode) PubKey() (*btcec.PublicKey, error) {
1,455✔
2847
        if l.pubKey != nil {
1,943✔
2848
                return l.pubKey, nil
488✔
2849
        }
488✔
2850

2851
        key, err := btcec.ParsePubKey(l.PubKeyBytes[:])
971✔
2852
        if err != nil {
971✔
2853
                return nil, err
×
2854
        }
×
2855
        l.pubKey = key
971✔
2856

971✔
2857
        return key, nil
971✔
2858
}
2859

2860
// AuthSig is a signature under the advertised public key which serves to
2861
// authenticate the attributes announced by this node.
2862
//
2863
// NOTE: By having this method to access an attribute, we ensure we only need
2864
// to fully deserialize the signature if absolutely necessary.
2865
func (l *LightningNode) AuthSig() (*ecdsa.Signature, error) {
×
2866
        return ecdsa.ParseSignature(l.AuthSigBytes)
×
2867
}
×
2868

2869
// AddPubKey is a setter-link method that can be used to swap out the public
2870
// key for a node.
2871
func (l *LightningNode) AddPubKey(key *btcec.PublicKey) {
66✔
2872
        l.pubKey = key
66✔
2873
        copy(l.PubKeyBytes[:], key.SerializeCompressed())
66✔
2874
}
66✔
2875

2876
// NodeAnnouncement retrieves the latest node announcement of the node.
2877
func (l *LightningNode) NodeAnnouncement(signed bool) (*lnwire.NodeAnnouncement,
2878
        error) {
18✔
2879

18✔
2880
        if !l.HaveNodeAnnouncement {
22✔
2881
                return nil, fmt.Errorf("node does not have node announcement")
4✔
2882
        }
4✔
2883

2884
        alias, err := lnwire.NewNodeAlias(l.Alias)
18✔
2885
        if err != nil {
18✔
2886
                return nil, err
×
2887
        }
×
2888

2889
        nodeAnn := &lnwire.NodeAnnouncement{
18✔
2890
                Features:        l.Features.RawFeatureVector,
18✔
2891
                NodeID:          l.PubKeyBytes,
18✔
2892
                RGBColor:        l.Color,
18✔
2893
                Alias:           alias,
18✔
2894
                Addresses:       l.Addresses,
18✔
2895
                Timestamp:       uint32(l.LastUpdate.Unix()),
18✔
2896
                ExtraOpaqueData: l.ExtraOpaqueData,
18✔
2897
        }
18✔
2898

18✔
2899
        if !signed {
22✔
2900
                return nodeAnn, nil
4✔
2901
        }
4✔
2902

2903
        sig, err := lnwire.NewSigFromECDSARawSignature(l.AuthSigBytes)
18✔
2904
        if err != nil {
18✔
2905
                return nil, err
×
2906
        }
×
2907

2908
        nodeAnn.Signature = sig
18✔
2909

18✔
2910
        return nodeAnn, nil
18✔
2911
}
2912

2913
// isPublic determines whether the node is seen as public within the graph from
2914
// the source node's point of view. An existing database transaction can also be
2915
// specified.
2916
func (c *ChannelGraph) isPublic(tx kvdb.RTx, nodePub route.Vertex,
2917
        sourcePubKey []byte) (bool, error) {
17✔
2918

17✔
2919
        // In order to determine whether this node is publicly advertised within
17✔
2920
        // the graph, we'll need to look at all of its edges and check whether
17✔
2921
        // they extend to any other node than the source node. errDone will be
17✔
2922
        // used to terminate the check early.
17✔
2923
        nodeIsPublic := false
17✔
2924
        errDone := errors.New("done")
17✔
2925
        err := c.ForEachNodeChannel(tx, nodePub, func(tx kvdb.RTx,
17✔
2926
                info *models.ChannelEdgeInfo, _ *models.ChannelEdgePolicy,
17✔
2927
                _ *models.ChannelEdgePolicy) error {
31✔
2928

14✔
2929
                // If this edge doesn't extend to the source node, we'll
14✔
2930
                // terminate our search as we can now conclude that the node is
14✔
2931
                // publicly advertised within the graph due to the local node
14✔
2932
                // knowing of the current edge.
14✔
2933
                if !bytes.Equal(info.NodeKey1Bytes[:], sourcePubKey) &&
14✔
2934
                        !bytes.Equal(info.NodeKey2Bytes[:], sourcePubKey) {
21✔
2935

7✔
2936
                        nodeIsPublic = true
7✔
2937
                        return errDone
7✔
2938
                }
7✔
2939

2940
                // Since the edge _does_ extend to the source node, we'll also
2941
                // need to ensure that this is a public edge.
2942
                if info.AuthProof != nil {
21✔
2943
                        nodeIsPublic = true
10✔
2944
                        return errDone
10✔
2945
                }
10✔
2946

2947
                // Otherwise, we'll continue our search.
2948
                return nil
5✔
2949
        })
2950
        if err != nil && err != errDone {
17✔
2951
                return false, err
×
2952
        }
×
2953

2954
        return nodeIsPublic, nil
17✔
2955
}
2956

2957
// FetchLightningNode attempts to look up a target node by its identity public
2958
// key. If the node isn't found in the database, then ErrGraphNodeNotFound is
2959
// returned. An optional transaction may be provided. If none is provided, then
2960
// a new one will be created.
2961
func (c *ChannelGraph) FetchLightningNode(tx kvdb.RTx, nodePub route.Vertex) (
2962
        *LightningNode, error) {
3,753✔
2963

3,753✔
2964
        var node *LightningNode
3,753✔
2965
        fetch := func(tx kvdb.RTx) error {
7,506✔
2966
                // First grab the nodes bucket which stores the mapping from
3,753✔
2967
                // pubKey to node information.
3,753✔
2968
                nodes := tx.ReadBucket(nodeBucket)
3,753✔
2969
                if nodes == nil {
3,753✔
2970
                        return ErrGraphNotFound
×
2971
                }
×
2972

2973
                // If a key for this serialized public key isn't found, then
2974
                // the target node doesn't exist within the database.
2975
                nodeBytes := nodes.Get(nodePub[:])
3,753✔
2976
                if nodeBytes == nil {
3,768✔
2977
                        return ErrGraphNodeNotFound
15✔
2978
                }
15✔
2979

2980
                // If the node is found, then we can de deserialize the node
2981
                // information to return to the user.
2982
                nodeReader := bytes.NewReader(nodeBytes)
3,742✔
2983
                n, err := deserializeLightningNode(nodeReader)
3,742✔
2984
                if err != nil {
3,742✔
2985
                        return err
×
2986
                }
×
2987

2988
                node = &n
3,742✔
2989

3,742✔
2990
                return nil
3,742✔
2991
        }
2992

2993
        if tx == nil {
4,562✔
2994
                err := kvdb.View(
809✔
2995
                        c.db, fetch, func() {
1,618✔
2996
                                node = nil
809✔
2997
                        },
809✔
2998
                )
2999
                if err != nil {
824✔
3000
                        return nil, err
15✔
3001
                }
15✔
3002

3003
                return node, nil
798✔
3004
        }
3005

3006
        err := fetch(tx)
2,944✔
3007
        if err != nil {
2,944✔
3008
                return nil, err
×
3009
        }
×
3010

3011
        return node, nil
2,944✔
3012
}
3013

3014
// graphCacheNode is a struct that wraps a LightningNode in a way that it can be
3015
// cached in the graph cache.
3016
type graphCacheNode struct {
3017
        pubKeyBytes route.Vertex
3018
        features    *lnwire.FeatureVector
3019
}
3020

3021
// newGraphCacheNode returns a new cache optimized node.
3022
func newGraphCacheNode(pubKey route.Vertex,
3023
        features *lnwire.FeatureVector) *graphCacheNode {
722✔
3024

722✔
3025
        return &graphCacheNode{
722✔
3026
                pubKeyBytes: pubKey,
722✔
3027
                features:    features,
722✔
3028
        }
722✔
3029
}
722✔
3030

3031
// PubKey returns the node's public identity key.
3032
func (n *graphCacheNode) PubKey() route.Vertex {
722✔
3033
        return n.pubKeyBytes
722✔
3034
}
722✔
3035

3036
// Features returns the node's features.
3037
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
702✔
3038
        return n.features
702✔
3039
}
702✔
3040

3041
// ForEachChannel iterates through all channels of this node, executing the
3042
// passed callback with an edge info structure and the policies of each end
3043
// of the channel. The first edge policy is the outgoing edge *to* the
3044
// connecting node, while the second is the incoming edge *from* the
3045
// connecting node. If the callback returns an error, then the iteration is
3046
// halted with the error propagated back up to the caller.
3047
//
3048
// Unknown policies are passed into the callback as nil values.
3049
func (n *graphCacheNode) ForEachChannel(tx kvdb.RTx,
3050
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3051
                *models.ChannelEdgePolicy) error) error {
622✔
3052

622✔
3053
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
622✔
3054
}
622✔
3055

3056
var _ GraphCacheNode = (*graphCacheNode)(nil)
3057

3058
// HasLightningNode determines if the graph has a vertex identified by the
3059
// target node identity public key. If the node exists in the database, a
3060
// timestamp of when the data for the node was lasted updated is returned along
3061
// with a true boolean. Otherwise, an empty time.Time is returned with a false
3062
// boolean.
3063
func (c *ChannelGraph) HasLightningNode(nodePub [33]byte) (time.Time, bool, error) {
22✔
3064
        var (
22✔
3065
                updateTime time.Time
22✔
3066
                exists     bool
22✔
3067
        )
22✔
3068

22✔
3069
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
44✔
3070
                // First grab the nodes bucket which stores the mapping from
22✔
3071
                // pubKey to node information.
22✔
3072
                nodes := tx.ReadBucket(nodeBucket)
22✔
3073
                if nodes == nil {
22✔
3074
                        return ErrGraphNotFound
×
3075
                }
×
3076

3077
                // If a key for this serialized public key isn't found, we can
3078
                // exit early.
3079
                nodeBytes := nodes.Get(nodePub[:])
22✔
3080
                if nodeBytes == nil {
29✔
3081
                        exists = false
7✔
3082
                        return nil
7✔
3083
                }
7✔
3084

3085
                // Otherwise we continue on to obtain the time stamp
3086
                // representing the last time the data for this node was
3087
                // updated.
3088
                nodeReader := bytes.NewReader(nodeBytes)
19✔
3089
                node, err := deserializeLightningNode(nodeReader)
19✔
3090
                if err != nil {
19✔
3091
                        return err
×
3092
                }
×
3093

3094
                exists = true
19✔
3095
                updateTime = node.LastUpdate
19✔
3096
                return nil
19✔
3097
        }, func() {
22✔
3098
                updateTime = time.Time{}
22✔
3099
                exists = false
22✔
3100
        })
22✔
3101
        if err != nil {
22✔
3102
                return time.Time{}, exists, err
×
3103
        }
×
3104

3105
        return updateTime, exists, nil
22✔
3106
}
3107

3108
// nodeTraversal is used to traverse all channels of a node given by its
3109
// public key and passes channel information into the specified callback.
3110
func nodeTraversal(tx kvdb.RTx, nodePub []byte, db kvdb.Backend,
3111
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3112
                *models.ChannelEdgePolicy) error) error {
1,850✔
3113

1,850✔
3114
        traversal := func(tx kvdb.RTx) error {
3,700✔
3115
                edges := tx.ReadBucket(edgeBucket)
1,850✔
3116
                if edges == nil {
1,850✔
3117
                        return ErrGraphNotFound
×
3118
                }
×
3119
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
1,850✔
3120
                if edgeIndex == nil {
1,850✔
3121
                        return ErrGraphNoEdgesFound
×
3122
                }
×
3123

3124
                // In order to reach all the edges for this node, we take
3125
                // advantage of the construction of the key-space within the
3126
                // edge bucket. The keys are stored in the form: pubKey ||
3127
                // chanID. Therefore, starting from a chanID of zero, we can
3128
                // scan forward in the bucket, grabbing all the edges for the
3129
                // node. Once the prefix no longer matches, then we know we're
3130
                // done.
3131
                var nodeStart [33 + 8]byte
1,850✔
3132
                copy(nodeStart[:], nodePub)
1,850✔
3133
                copy(nodeStart[33:], chanStart[:])
1,850✔
3134

1,850✔
3135
                // Starting from the key pubKey || 0, we seek forward in the
1,850✔
3136
                // bucket until the retrieved key no longer has the public key
1,850✔
3137
                // as its prefix. This indicates that we've stepped over into
1,850✔
3138
                // another node's edges, so we can terminate our scan.
1,850✔
3139
                edgeCursor := edges.ReadCursor()
1,850✔
3140
                for nodeEdge, _ := edgeCursor.Seek(nodeStart[:]); bytes.HasPrefix(nodeEdge, nodePub); nodeEdge, _ = edgeCursor.Next() {
5,672✔
3141
                        // If the prefix still matches, the channel id is
3,822✔
3142
                        // returned in nodeEdge. Channel id is used to lookup
3,822✔
3143
                        // the node at the other end of the channel and both
3,822✔
3144
                        // edge policies.
3,822✔
3145
                        chanID := nodeEdge[33:]
3,822✔
3146
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3,822✔
3147
                        if err != nil {
3,822✔
3148
                                return err
×
3149
                        }
×
3150

3151
                        outgoingPolicy, err := fetchChanEdgePolicy(
3,822✔
3152
                                edges, chanID, nodePub,
3,822✔
3153
                        )
3,822✔
3154
                        if err != nil {
3,822✔
3155
                                return err
×
3156
                        }
×
3157

3158
                        otherNode, err := edgeInfo.OtherNodeKeyBytes(nodePub)
3,822✔
3159
                        if err != nil {
3,822✔
3160
                                return err
×
3161
                        }
×
3162

3163
                        incomingPolicy, err := fetchChanEdgePolicy(
3,822✔
3164
                                edges, chanID, otherNode[:],
3,822✔
3165
                        )
3,822✔
3166
                        if err != nil {
3,822✔
3167
                                return err
×
3168
                        }
×
3169

3170
                        // Finally, we execute the callback.
3171
                        err = cb(tx, &edgeInfo, outgoingPolicy, incomingPolicy)
3,822✔
3172
                        if err != nil {
3,835✔
3173
                                return err
13✔
3174
                        }
13✔
3175
                }
3176

3177
                return nil
1,841✔
3178
        }
3179

3180
        // If no transaction was provided, then we'll create a new transaction
3181
        // to execute the transaction within.
3182
        if tx == nil {
1,863✔
3183
                return kvdb.View(db, traversal, func() {})
26✔
3184
        }
3185

3186
        // Otherwise, we re-use the existing transaction to execute the graph
3187
        // traversal.
3188
        return traversal(tx)
1,841✔
3189
}
3190

3191
// ForEachNodeChannel iterates through all channels of the given node,
3192
// executing the passed callback with an edge info structure and the policies
3193
// of each end of the channel. The first edge policy is the outgoing edge *to*
3194
// the connecting node, while the second is the incoming edge *from* the
3195
// connecting node. If the callback returns an error, then the iteration is
3196
// halted with the error propagated back up to the caller.
3197
//
3198
// Unknown policies are passed into the callback as nil values.
3199
//
3200
// If the caller wishes to re-use an existing boltdb transaction, then it
3201
// should be passed as the first argument.  Otherwise the first argument should
3202
// be nil and a fresh transaction will be created to execute the graph
3203
// traversal.
3204
func (c *ChannelGraph) ForEachNodeChannel(tx kvdb.RTx, nodePub route.Vertex,
3205
        cb func(kvdb.RTx, *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3206
                *models.ChannelEdgePolicy) error) error {
1,008✔
3207

1,008✔
3208
        return nodeTraversal(tx, nodePub[:], c.db, cb)
1,008✔
3209
}
1,008✔
3210

3211
// FetchOtherNode attempts to fetch the full LightningNode that's opposite of
3212
// the target node in the channel. This is useful when one knows the pubkey of
3213
// one of the nodes, and wishes to obtain the full LightningNode for the other
3214
// end of the channel.
3215
func (c *ChannelGraph) FetchOtherNode(tx kvdb.RTx,
3216
        channel *models.ChannelEdgeInfo, thisNodeKey []byte) (*LightningNode,
3217
        error) {
4✔
3218

4✔
3219
        // Ensure that the node passed in is actually a member of the channel.
4✔
3220
        var targetNodeBytes [33]byte
4✔
3221
        switch {
4✔
3222
        case bytes.Equal(channel.NodeKey1Bytes[:], thisNodeKey):
4✔
3223
                targetNodeBytes = channel.NodeKey2Bytes
4✔
3224
        case bytes.Equal(channel.NodeKey2Bytes[:], thisNodeKey):
4✔
3225
                targetNodeBytes = channel.NodeKey1Bytes
4✔
3226
        default:
×
3227
                return nil, fmt.Errorf("node not participating in this channel")
×
3228
        }
3229

3230
        var targetNode *LightningNode
4✔
3231
        fetchNodeFunc := func(tx kvdb.RTx) error {
8✔
3232
                // First grab the nodes bucket which stores the mapping from
4✔
3233
                // pubKey to node information.
4✔
3234
                nodes := tx.ReadBucket(nodeBucket)
4✔
3235
                if nodes == nil {
4✔
3236
                        return ErrGraphNotFound
×
3237
                }
×
3238

3239
                node, err := fetchLightningNode(nodes, targetNodeBytes[:])
4✔
3240
                if err != nil {
4✔
3241
                        return err
×
3242
                }
×
3243

3244
                targetNode = &node
4✔
3245

4✔
3246
                return nil
4✔
3247
        }
3248

3249
        // If the transaction is nil, then we'll need to create a new one,
3250
        // otherwise we can use the existing db transaction.
3251
        var err error
4✔
3252
        if tx == nil {
4✔
3253
                err = kvdb.View(c.db, fetchNodeFunc, func() { targetNode = nil })
×
3254
        } else {
4✔
3255
                err = fetchNodeFunc(tx)
4✔
3256
        }
4✔
3257

3258
        return targetNode, err
4✔
3259
}
3260

3261
// computeEdgePolicyKeys is a helper function that can be used to compute the
3262
// keys used to index the channel edge policy info for the two nodes of the
3263
// edge. The keys for node 1 and node 2 are returned respectively.
3264
func computeEdgePolicyKeys(info *models.ChannelEdgeInfo) ([]byte, []byte) {
26✔
3265
        var (
26✔
3266
                node1Key [33 + 8]byte
26✔
3267
                node2Key [33 + 8]byte
26✔
3268
        )
26✔
3269

26✔
3270
        copy(node1Key[:], info.NodeKey1Bytes[:])
26✔
3271
        copy(node2Key[:], info.NodeKey2Bytes[:])
26✔
3272

26✔
3273
        byteOrder.PutUint64(node1Key[33:], info.ChannelID)
26✔
3274
        byteOrder.PutUint64(node2Key[33:], info.ChannelID)
26✔
3275

26✔
3276
        return node1Key[:], node2Key[:]
26✔
3277
}
26✔
3278

3279
// FetchChannelEdgesByOutpoint attempts to lookup the two directed edges for
3280
// the channel identified by the funding outpoint. If the channel can't be
3281
// found, then ErrEdgeNotFound is returned. A struct which houses the general
3282
// information for the channel itself is returned as well as two structs that
3283
// contain the routing policies for the channel in either direction.
3284
func (c *ChannelGraph) FetchChannelEdgesByOutpoint(op *wire.OutPoint) (
3285
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3286
        *models.ChannelEdgePolicy, error) {
15✔
3287

15✔
3288
        var (
15✔
3289
                edgeInfo *models.ChannelEdgeInfo
15✔
3290
                policy1  *models.ChannelEdgePolicy
15✔
3291
                policy2  *models.ChannelEdgePolicy
15✔
3292
        )
15✔
3293

15✔
3294
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
30✔
3295
                // First, grab the node bucket. This will be used to populate
15✔
3296
                // the Node pointers in each edge read from disk.
15✔
3297
                nodes := tx.ReadBucket(nodeBucket)
15✔
3298
                if nodes == nil {
15✔
3299
                        return ErrGraphNotFound
×
3300
                }
×
3301

3302
                // Next, grab the edge bucket which stores the edges, and also
3303
                // the index itself so we can group the directed edges together
3304
                // logically.
3305
                edges := tx.ReadBucket(edgeBucket)
15✔
3306
                if edges == nil {
15✔
3307
                        return ErrGraphNoEdgesFound
×
3308
                }
×
3309
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
15✔
3310
                if edgeIndex == nil {
15✔
3311
                        return ErrGraphNoEdgesFound
×
3312
                }
×
3313

3314
                // If the channel's outpoint doesn't exist within the outpoint
3315
                // index, then the edge does not exist.
3316
                chanIndex := edges.NestedReadBucket(channelPointBucket)
15✔
3317
                if chanIndex == nil {
15✔
3318
                        return ErrGraphNoEdgesFound
×
3319
                }
×
3320
                var b bytes.Buffer
15✔
3321
                if err := writeOutpoint(&b, op); err != nil {
15✔
3322
                        return err
×
3323
                }
×
3324
                chanID := chanIndex.Get(b.Bytes())
15✔
3325
                if chanID == nil {
29✔
3326
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
14✔
3327
                }
14✔
3328

3329
                // If the channel is found to exists, then we'll first retrieve
3330
                // the general information for the channel.
3331
                edge, err := fetchChanEdgeInfo(edgeIndex, chanID)
5✔
3332
                if err != nil {
5✔
3333
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3334
                }
×
3335
                edgeInfo = &edge
5✔
3336

5✔
3337
                // Once we have the information about the channels' parameters,
5✔
3338
                // we'll fetch the routing policies for each for the directed
5✔
3339
                // edges.
5✔
3340
                e1, e2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
5✔
3341
                if err != nil {
5✔
3342
                        return fmt.Errorf("failed to find policy: %w", err)
×
3343
                }
×
3344

3345
                policy1 = e1
5✔
3346
                policy2 = e2
5✔
3347
                return nil
5✔
3348
        }, func() {
15✔
3349
                edgeInfo = nil
15✔
3350
                policy1 = nil
15✔
3351
                policy2 = nil
15✔
3352
        })
15✔
3353
        if err != nil {
29✔
3354
                return nil, nil, nil, err
14✔
3355
        }
14✔
3356

3357
        return edgeInfo, policy1, policy2, nil
5✔
3358
}
3359

3360
// FetchChannelEdgesByID attempts to lookup the two directed edges for the
3361
// channel identified by the channel ID. If the channel can't be found, then
3362
// ErrEdgeNotFound is returned. A struct which houses the general information
3363
// for the channel itself is returned as well as two structs that contain the
3364
// routing policies for the channel in either direction.
3365
//
3366
// ErrZombieEdge an be returned if the edge is currently marked as a zombie
3367
// within the database. In this case, the ChannelEdgePolicy's will be nil, and
3368
// the ChannelEdgeInfo will only include the public keys of each node.
3369
func (c *ChannelGraph) FetchChannelEdgesByID(chanID uint64) (
3370
        *models.ChannelEdgeInfo, *models.ChannelEdgePolicy,
3371
        *models.ChannelEdgePolicy, error) {
40✔
3372

40✔
3373
        var (
40✔
3374
                edgeInfo  *models.ChannelEdgeInfo
40✔
3375
                policy1   *models.ChannelEdgePolicy
40✔
3376
                policy2   *models.ChannelEdgePolicy
40✔
3377
                channelID [8]byte
40✔
3378
        )
40✔
3379

40✔
3380
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
80✔
3381
                // First, grab the node bucket. This will be used to populate
40✔
3382
                // the Node pointers in each edge read from disk.
40✔
3383
                nodes := tx.ReadBucket(nodeBucket)
40✔
3384
                if nodes == nil {
40✔
3385
                        return ErrGraphNotFound
×
3386
                }
×
3387

3388
                // Next, grab the edge bucket which stores the edges, and also
3389
                // the index itself so we can group the directed edges together
3390
                // logically.
3391
                edges := tx.ReadBucket(edgeBucket)
40✔
3392
                if edges == nil {
40✔
3393
                        return ErrGraphNoEdgesFound
×
3394
                }
×
3395
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
40✔
3396
                if edgeIndex == nil {
40✔
3397
                        return ErrGraphNoEdgesFound
×
3398
                }
×
3399

3400
                byteOrder.PutUint64(channelID[:], chanID)
40✔
3401

40✔
3402
                // Now, attempt to fetch edge.
40✔
3403
                edge, err := fetchChanEdgeInfo(edgeIndex, channelID[:])
40✔
3404

40✔
3405
                // If it doesn't exist, we'll quickly check our zombie index to
40✔
3406
                // see if we've previously marked it as so.
40✔
3407
                if errors.Is(err, ErrEdgeNotFound) {
46✔
3408
                        // If the zombie index doesn't exist, or the edge is not
6✔
3409
                        // marked as a zombie within it, then we'll return the
6✔
3410
                        // original ErrEdgeNotFound error.
6✔
3411
                        zombieIndex := edges.NestedReadBucket(zombieBucket)
6✔
3412
                        if zombieIndex == nil {
6✔
3413
                                return ErrEdgeNotFound
×
3414
                        }
×
3415

3416
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
6✔
3417
                                zombieIndex, chanID,
6✔
3418
                        )
6✔
3419
                        if !isZombie {
11✔
3420
                                return ErrEdgeNotFound
5✔
3421
                        }
5✔
3422

3423
                        // Otherwise, the edge is marked as a zombie, so we'll
3424
                        // populate the edge info with the public keys of each
3425
                        // party as this is the only information we have about
3426
                        // it and return an error signaling so.
3427
                        edgeInfo = &models.ChannelEdgeInfo{
5✔
3428
                                NodeKey1Bytes: pubKey1,
5✔
3429
                                NodeKey2Bytes: pubKey2,
5✔
3430
                        }
5✔
3431
                        return ErrZombieEdge
5✔
3432
                }
3433

3434
                // Otherwise, we'll just return the error if any.
3435
                if err != nil {
38✔
3436
                        return err
×
3437
                }
×
3438

3439
                edgeInfo = &edge
38✔
3440

38✔
3441
                // Then we'll attempt to fetch the accompanying policies of this
38✔
3442
                // edge.
38✔
3443
                e1, e2, err := fetchChanEdgePolicies(
38✔
3444
                        edgeIndex, edges, channelID[:],
38✔
3445
                )
38✔
3446
                if err != nil {
38✔
3447
                        return err
×
3448
                }
×
3449

3450
                policy1 = e1
38✔
3451
                policy2 = e2
38✔
3452
                return nil
38✔
3453
        }, func() {
40✔
3454
                edgeInfo = nil
40✔
3455
                policy1 = nil
40✔
3456
                policy2 = nil
40✔
3457
        })
40✔
3458
        if err == ErrZombieEdge {
45✔
3459
                return edgeInfo, nil, nil, err
5✔
3460
        }
5✔
3461
        if err != nil {
44✔
3462
                return nil, nil, nil, err
5✔
3463
        }
5✔
3464

3465
        return edgeInfo, policy1, policy2, nil
38✔
3466
}
3467

3468
// IsPublicNode is a helper method that determines whether the node with the
3469
// given public key is seen as a public node in the graph from the graph's
3470
// source node's point of view.
3471
func (c *ChannelGraph) IsPublicNode(pubKey [33]byte) (bool, error) {
17✔
3472
        var nodeIsPublic bool
17✔
3473
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
34✔
3474
                nodes := tx.ReadBucket(nodeBucket)
17✔
3475
                if nodes == nil {
17✔
3476
                        return ErrGraphNodesNotFound
×
3477
                }
×
3478
                ourPubKey := nodes.Get(sourceKey)
17✔
3479
                if ourPubKey == nil {
17✔
3480
                        return ErrSourceNodeNotSet
×
3481
                }
×
3482
                node, err := fetchLightningNode(nodes, pubKey[:])
17✔
3483
                if err != nil {
17✔
3484
                        return err
×
3485
                }
×
3486

3487
                nodeIsPublic, err = c.isPublic(tx, node.PubKeyBytes, ourPubKey)
17✔
3488
                return err
17✔
3489
        }, func() {
17✔
3490
                nodeIsPublic = false
17✔
3491
        })
17✔
3492
        if err != nil {
17✔
3493
                return false, err
×
3494
        }
×
3495

3496
        return nodeIsPublic, nil
17✔
3497
}
3498

3499
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3500
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
154✔
3501
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
154✔
3502
        if err != nil {
154✔
3503
                return nil, err
×
3504
        }
×
3505

3506
        // With the witness script generated, we'll now turn it into a p2wsh
3507
        // script:
3508
        //  * OP_0 <sha256(script)>
3509
        bldr := txscript.NewScriptBuilder(
154✔
3510
                txscript.WithScriptAllocSize(input.P2WSHSize),
154✔
3511
        )
154✔
3512
        bldr.AddOp(txscript.OP_0)
154✔
3513
        scriptHash := sha256.Sum256(witnessScript)
154✔
3514
        bldr.AddData(scriptHash[:])
154✔
3515

154✔
3516
        return bldr.Script()
154✔
3517
}
3518

3519
// EdgePoint couples the outpoint of a channel with the funding script that it
3520
// creates. The FilteredChainView will use this to watch for spends of this
3521
// edge point on chain. We require both of these values as depending on the
3522
// concrete implementation, either the pkScript, or the out point will be used.
3523
type EdgePoint struct {
3524
        // FundingPkScript is the p2wsh multi-sig script of the target channel.
3525
        FundingPkScript []byte
3526

3527
        // OutPoint is the outpoint of the target channel.
3528
        OutPoint wire.OutPoint
3529
}
3530

3531
// String returns a human readable version of the target EdgePoint. We return
3532
// the outpoint directly as it is enough to uniquely identify the edge point.
3533
func (e *EdgePoint) String() string {
×
3534
        return e.OutPoint.String()
×
3535
}
×
3536

3537
// ChannelView returns the verifiable edge information for each active channel
3538
// within the known channel graph. The set of UTXO's (along with their scripts)
3539
// returned are the ones that need to be watched on chain to detect channel
3540
// closes on the resident blockchain.
3541
func (c *ChannelGraph) ChannelView() ([]EdgePoint, error) {
44✔
3542
        var edgePoints []EdgePoint
44✔
3543
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
88✔
3544
                // We're going to iterate over the entire channel index, so
44✔
3545
                // we'll need to fetch the edgeBucket to get to the index as
44✔
3546
                // it's a sub-bucket.
44✔
3547
                edges := tx.ReadBucket(edgeBucket)
44✔
3548
                if edges == nil {
44✔
3549
                        return ErrGraphNoEdgesFound
×
3550
                }
×
3551
                chanIndex := edges.NestedReadBucket(channelPointBucket)
44✔
3552
                if chanIndex == nil {
44✔
3553
                        return ErrGraphNoEdgesFound
×
3554
                }
×
3555
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
44✔
3556
                if edgeIndex == nil {
44✔
3557
                        return ErrGraphNoEdgesFound
×
3558
                }
×
3559

3560
                // Once we have the proper bucket, we'll range over each key
3561
                // (which is the channel point for the channel) and decode it,
3562
                // accumulating each entry.
3563
                return chanIndex.ForEach(func(chanPointBytes, chanID []byte) error {
194✔
3564
                        chanPointReader := bytes.NewReader(chanPointBytes)
150✔
3565

150✔
3566
                        var chanPoint wire.OutPoint
150✔
3567
                        err := readOutpoint(chanPointReader, &chanPoint)
150✔
3568
                        if err != nil {
150✔
3569
                                return err
×
3570
                        }
×
3571

3572
                        edgeInfo, err := fetchChanEdgeInfo(
150✔
3573
                                edgeIndex, chanID,
150✔
3574
                        )
150✔
3575
                        if err != nil {
150✔
3576
                                return err
×
3577
                        }
×
3578

3579
                        pkScript, err := genMultiSigP2WSH(
150✔
3580
                                edgeInfo.BitcoinKey1Bytes[:],
150✔
3581
                                edgeInfo.BitcoinKey2Bytes[:],
150✔
3582
                        )
150✔
3583
                        if err != nil {
150✔
3584
                                return err
×
3585
                        }
×
3586

3587
                        edgePoints = append(edgePoints, EdgePoint{
150✔
3588
                                FundingPkScript: pkScript,
150✔
3589
                                OutPoint:        chanPoint,
150✔
3590
                        })
150✔
3591

150✔
3592
                        return nil
150✔
3593
                })
3594
        }, func() {
44✔
3595
                edgePoints = nil
44✔
3596
        }); err != nil {
44✔
3597
                return nil, err
×
3598
        }
×
3599

3600
        return edgePoints, nil
44✔
3601
}
3602

3603
// MarkEdgeZombie attempts to mark a channel identified by its channel ID as a
3604
// zombie. This method is used on an ad-hoc basis, when channels need to be
3605
// marked as zombies outside the normal pruning cycle.
3606
func (c *ChannelGraph) MarkEdgeZombie(chanID uint64,
3607
        pubKey1, pubKey2 [33]byte) error {
136✔
3608

136✔
3609
        c.cacheMu.Lock()
136✔
3610
        defer c.cacheMu.Unlock()
136✔
3611

136✔
3612
        err := kvdb.Batch(c.db, func(tx kvdb.RwTx) error {
272✔
3613
                edges := tx.ReadWriteBucket(edgeBucket)
136✔
3614
                if edges == nil {
136✔
3615
                        return ErrGraphNoEdgesFound
×
3616
                }
×
3617
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
136✔
3618
                if err != nil {
136✔
3619
                        return fmt.Errorf("unable to create zombie "+
×
3620
                                "bucket: %w", err)
×
3621
                }
×
3622

3623
                if c.graphCache != nil {
272✔
3624
                        c.graphCache.RemoveChannel(pubKey1, pubKey2, chanID)
136✔
3625
                }
136✔
3626

3627
                return markEdgeZombie(zombieIndex, chanID, pubKey1, pubKey2)
136✔
3628
        })
3629
        if err != nil {
136✔
3630
                return err
×
3631
        }
×
3632

3633
        c.rejectCache.remove(chanID)
136✔
3634
        c.chanCache.remove(chanID)
136✔
3635

136✔
3636
        return nil
136✔
3637
}
3638

3639
// markEdgeZombie marks an edge as a zombie within our zombie index. The public
3640
// keys should represent the node public keys of the two parties involved in the
3641
// edge.
3642
func markEdgeZombie(zombieIndex kvdb.RwBucket, chanID uint64, pubKey1,
3643
        pubKey2 [33]byte) error {
163✔
3644

163✔
3645
        var k [8]byte
163✔
3646
        byteOrder.PutUint64(k[:], chanID)
163✔
3647

163✔
3648
        var v [66]byte
163✔
3649
        copy(v[:33], pubKey1[:])
163✔
3650
        copy(v[33:], pubKey2[:])
163✔
3651

163✔
3652
        return zombieIndex.Put(k[:], v[:])
163✔
3653
}
163✔
3654

3655
// MarkEdgeLive clears an edge from our zombie index, deeming it as live.
3656
func (c *ChannelGraph) MarkEdgeLive(chanID uint64) error {
6✔
3657
        c.cacheMu.Lock()
6✔
3658
        defer c.cacheMu.Unlock()
6✔
3659

6✔
3660
        return c.markEdgeLiveUnsafe(nil, chanID)
6✔
3661
}
6✔
3662

3663
// markEdgeLiveUnsafe clears an edge from the zombie index. This method can be
3664
// called with an existing kvdb.RwTx or the argument can be set to nil in which
3665
// case a new transaction will be created.
3666
//
3667
// NOTE: this method MUST only be called if the cacheMu has already been
3668
// acquired.
3669
func (c *ChannelGraph) markEdgeLiveUnsafe(tx kvdb.RwTx, chanID uint64) error {
26✔
3670
        dbFn := func(tx kvdb.RwTx) error {
52✔
3671
                edges := tx.ReadWriteBucket(edgeBucket)
26✔
3672
                if edges == nil {
26✔
3673
                        return ErrGraphNoEdgesFound
×
3674
                }
×
3675
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
26✔
3676
                if zombieIndex == nil {
26✔
3677
                        return nil
×
3678
                }
×
3679

3680
                var k [8]byte
26✔
3681
                byteOrder.PutUint64(k[:], chanID)
26✔
3682

26✔
3683
                if len(zombieIndex.Get(k[:])) == 0 {
27✔
3684
                        return ErrZombieEdgeNotFound
1✔
3685
                }
1✔
3686

3687
                return zombieIndex.Delete(k[:])
25✔
3688
        }
3689

3690
        // If the transaction is nil, we'll create a new one. Otherwise, we use
3691
        // the existing transaction
3692
        var err error
26✔
3693
        if tx == nil {
32✔
3694
                err = kvdb.Update(c.db, dbFn, func() {})
12✔
3695
        } else {
20✔
3696
                err = dbFn(tx)
20✔
3697
        }
20✔
3698
        if err != nil {
27✔
3699
                return err
1✔
3700
        }
1✔
3701

3702
        c.rejectCache.remove(chanID)
25✔
3703
        c.chanCache.remove(chanID)
25✔
3704

25✔
3705
        // We need to add the channel back into our graph cache, otherwise we
25✔
3706
        // won't use it for path finding.
25✔
3707
        if c.graphCache != nil {
50✔
3708
                edgeInfos, err := c.FetchChanInfos(tx, []uint64{chanID})
25✔
3709
                if err != nil {
25✔
3710
                        return err
×
3711
                }
×
3712

3713
                for _, edgeInfo := range edgeInfos {
25✔
3714
                        c.graphCache.AddChannel(
×
3715
                                edgeInfo.Info, edgeInfo.Policy1,
×
3716
                                edgeInfo.Policy2,
×
3717
                        )
×
3718
                }
×
3719
        }
3720

3721
        return nil
25✔
3722
}
3723

3724
// IsZombieEdge returns whether the edge is considered zombie. If it is a
3725
// zombie, then the two node public keys corresponding to this edge are also
3726
// returned.
3727
func (c *ChannelGraph) IsZombieEdge(chanID uint64) (bool, [33]byte, [33]byte) {
5✔
3728
        var (
5✔
3729
                isZombie         bool
5✔
3730
                pubKey1, pubKey2 [33]byte
5✔
3731
        )
5✔
3732

5✔
3733
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
10✔
3734
                edges := tx.ReadBucket(edgeBucket)
5✔
3735
                if edges == nil {
5✔
3736
                        return ErrGraphNoEdgesFound
×
3737
                }
×
3738
                zombieIndex := edges.NestedReadBucket(zombieBucket)
5✔
3739
                if zombieIndex == nil {
5✔
3740
                        return nil
×
3741
                }
×
3742

3743
                isZombie, pubKey1, pubKey2 = isZombieEdge(zombieIndex, chanID)
5✔
3744
                return nil
5✔
3745
        }, func() {
5✔
3746
                isZombie = false
5✔
3747
                pubKey1 = [33]byte{}
5✔
3748
                pubKey2 = [33]byte{}
5✔
3749
        })
5✔
3750
        if err != nil {
5✔
3751
                return false, [33]byte{}, [33]byte{}
×
3752
        }
×
3753

3754
        return isZombie, pubKey1, pubKey2
5✔
3755
}
3756

3757
// isZombieEdge returns whether an entry exists for the given channel in the
3758
// zombie index. If an entry exists, then the two node public keys corresponding
3759
// to this edge are also returned.
3760
func isZombieEdge(zombieIndex kvdb.RBucket,
3761
        chanID uint64) (bool, [33]byte, [33]byte) {
191✔
3762

191✔
3763
        var k [8]byte
191✔
3764
        byteOrder.PutUint64(k[:], chanID)
191✔
3765

191✔
3766
        v := zombieIndex.Get(k[:])
191✔
3767
        if v == nil {
292✔
3768
                return false, [33]byte{}, [33]byte{}
101✔
3769
        }
101✔
3770

3771
        var pubKey1, pubKey2 [33]byte
94✔
3772
        copy(pubKey1[:], v[:33])
94✔
3773
        copy(pubKey2[:], v[33:])
94✔
3774

94✔
3775
        return true, pubKey1, pubKey2
94✔
3776
}
3777

3778
// NumZombies returns the current number of zombie channels in the graph.
3779
func (c *ChannelGraph) NumZombies() (uint64, error) {
4✔
3780
        var numZombies uint64
4✔
3781
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
8✔
3782
                edges := tx.ReadBucket(edgeBucket)
4✔
3783
                if edges == nil {
4✔
3784
                        return nil
×
3785
                }
×
3786
                zombieIndex := edges.NestedReadBucket(zombieBucket)
4✔
3787
                if zombieIndex == nil {
4✔
3788
                        return nil
×
3789
                }
×
3790

3791
                return zombieIndex.ForEach(func(_, _ []byte) error {
6✔
3792
                        numZombies++
2✔
3793
                        return nil
2✔
3794
                })
2✔
3795
        }, func() {
4✔
3796
                numZombies = 0
4✔
3797
        })
4✔
3798
        if err != nil {
4✔
3799
                return 0, err
×
3800
        }
×
3801

3802
        return numZombies, nil
4✔
3803
}
3804

3805
func putLightningNode(nodeBucket kvdb.RwBucket, aliasBucket kvdb.RwBucket, // nolint:dupl
3806
        updateIndex kvdb.RwBucket, node *LightningNode) error {
971✔
3807

971✔
3808
        var (
971✔
3809
                scratch [16]byte
971✔
3810
                b       bytes.Buffer
971✔
3811
        )
971✔
3812

971✔
3813
        pub, err := node.PubKey()
971✔
3814
        if err != nil {
971✔
3815
                return err
×
3816
        }
×
3817
        nodePub := pub.SerializeCompressed()
971✔
3818

971✔
3819
        // If the node has the update time set, write it, else write 0.
971✔
3820
        updateUnix := uint64(0)
971✔
3821
        if node.LastUpdate.Unix() > 0 {
1,820✔
3822
                updateUnix = uint64(node.LastUpdate.Unix())
849✔
3823
        }
849✔
3824

3825
        byteOrder.PutUint64(scratch[:8], updateUnix)
971✔
3826
        if _, err := b.Write(scratch[:8]); err != nil {
971✔
3827
                return err
×
3828
        }
×
3829

3830
        if _, err := b.Write(nodePub); err != nil {
971✔
3831
                return err
×
3832
        }
×
3833

3834
        // If we got a node announcement for this node, we will have the rest
3835
        // of the data available. If not we don't have more data to write.
3836
        if !node.HaveNodeAnnouncement {
1,044✔
3837
                // Write HaveNodeAnnouncement=0.
73✔
3838
                byteOrder.PutUint16(scratch[:2], 0)
73✔
3839
                if _, err := b.Write(scratch[:2]); err != nil {
73✔
3840
                        return err
×
3841
                }
×
3842

3843
                return nodeBucket.Put(nodePub, b.Bytes())
73✔
3844
        }
3845

3846
        // Write HaveNodeAnnouncement=1.
3847
        byteOrder.PutUint16(scratch[:2], 1)
902✔
3848
        if _, err := b.Write(scratch[:2]); err != nil {
902✔
3849
                return err
×
3850
        }
×
3851

3852
        if err := binary.Write(&b, byteOrder, node.Color.R); err != nil {
902✔
3853
                return err
×
3854
        }
×
3855
        if err := binary.Write(&b, byteOrder, node.Color.G); err != nil {
902✔
3856
                return err
×
3857
        }
×
3858
        if err := binary.Write(&b, byteOrder, node.Color.B); err != nil {
902✔
3859
                return err
×
3860
        }
×
3861

3862
        if err := wire.WriteVarString(&b, 0, node.Alias); err != nil {
902✔
3863
                return err
×
3864
        }
×
3865

3866
        if err := node.Features.Encode(&b); err != nil {
902✔
3867
                return err
×
3868
        }
×
3869

3870
        numAddresses := uint16(len(node.Addresses))
902✔
3871
        byteOrder.PutUint16(scratch[:2], numAddresses)
902✔
3872
        if _, err := b.Write(scratch[:2]); err != nil {
902✔
3873
                return err
×
3874
        }
×
3875

3876
        for _, address := range node.Addresses {
2,034✔
3877
                if err := serializeAddr(&b, address); err != nil {
1,132✔
3878
                        return err
×
3879
                }
×
3880
        }
3881

3882
        sigLen := len(node.AuthSigBytes)
902✔
3883
        if sigLen > 80 {
902✔
3884
                return fmt.Errorf("max sig len allowed is 80, had %v",
×
3885
                        sigLen)
×
3886
        }
×
3887

3888
        err = wire.WriteVarBytes(&b, 0, node.AuthSigBytes)
902✔
3889
        if err != nil {
902✔
3890
                return err
×
3891
        }
×
3892

3893
        if len(node.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
902✔
3894
                return ErrTooManyExtraOpaqueBytes(len(node.ExtraOpaqueData))
×
3895
        }
×
3896
        err = wire.WriteVarBytes(&b, 0, node.ExtraOpaqueData)
902✔
3897
        if err != nil {
902✔
3898
                return err
×
3899
        }
×
3900

3901
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
902✔
3902
                return err
×
3903
        }
×
3904

3905
        // With the alias bucket updated, we'll now update the index that
3906
        // tracks the time series of node updates.
3907
        var indexKey [8 + 33]byte
902✔
3908
        byteOrder.PutUint64(indexKey[:8], updateUnix)
902✔
3909
        copy(indexKey[8:], nodePub)
902✔
3910

902✔
3911
        // If there was already an old index entry for this node, then we'll
902✔
3912
        // delete the old one before we write the new entry.
902✔
3913
        if nodeBytes := nodeBucket.Get(nodePub); nodeBytes != nil {
1,011✔
3914
                // Extract out the old update time to we can reconstruct the
109✔
3915
                // prior index key to delete it from the index.
109✔
3916
                oldUpdateTime := nodeBytes[:8]
109✔
3917

109✔
3918
                var oldIndexKey [8 + 33]byte
109✔
3919
                copy(oldIndexKey[:8], oldUpdateTime)
109✔
3920
                copy(oldIndexKey[8:], nodePub)
109✔
3921

109✔
3922
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
109✔
3923
                        return err
×
3924
                }
×
3925
        }
3926

3927
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
902✔
3928
                return err
×
3929
        }
×
3930

3931
        return nodeBucket.Put(nodePub, b.Bytes())
902✔
3932
}
3933

3934
func fetchLightningNode(nodeBucket kvdb.RBucket,
3935
        nodePub []byte) (LightningNode, error) {
3,645✔
3936

3,645✔
3937
        nodeBytes := nodeBucket.Get(nodePub)
3,645✔
3938
        if nodeBytes == nil {
3,717✔
3939
                return LightningNode{}, ErrGraphNodeNotFound
72✔
3940
        }
72✔
3941

3942
        nodeReader := bytes.NewReader(nodeBytes)
3,577✔
3943
        return deserializeLightningNode(nodeReader)
3,577✔
3944
}
3945

3946
func deserializeLightningNodeCacheable(r io.Reader) (*graphCacheNode, error) {
124✔
3947
        // Always populate a feature vector, even if we don't have a node
124✔
3948
        // announcement and short circuit below.
124✔
3949
        node := newGraphCacheNode(
124✔
3950
                route.Vertex{},
124✔
3951
                lnwire.EmptyFeatureVector(),
124✔
3952
        )
124✔
3953

124✔
3954
        var nodeScratch [8]byte
124✔
3955

124✔
3956
        // Skip ahead:
124✔
3957
        // - LastUpdate (8 bytes)
124✔
3958
        if _, err := r.Read(nodeScratch[:]); err != nil {
124✔
3959
                return nil, err
×
3960
        }
×
3961

3962
        if _, err := io.ReadFull(r, node.pubKeyBytes[:]); err != nil {
124✔
3963
                return nil, err
×
3964
        }
×
3965

3966
        // Read the node announcement flag.
3967
        if _, err := r.Read(nodeScratch[:2]); err != nil {
124✔
3968
                return nil, err
×
3969
        }
×
3970
        hasNodeAnn := byteOrder.Uint16(nodeScratch[:2])
124✔
3971

124✔
3972
        // The rest of the data is optional, and will only be there if we got a
124✔
3973
        // node announcement for this node.
124✔
3974
        if hasNodeAnn == 0 {
128✔
3975
                return node, nil
4✔
3976
        }
4✔
3977

3978
        // We did get a node announcement for this node, so we'll have the rest
3979
        // of the data available.
3980
        var rgb uint8
124✔
3981
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
124✔
3982
                return nil, err
×
3983
        }
×
3984
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
124✔
3985
                return nil, err
×
3986
        }
×
3987
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
124✔
3988
                return nil, err
×
3989
        }
×
3990

3991
        if _, err := wire.ReadVarString(r, 0); err != nil {
124✔
3992
                return nil, err
×
3993
        }
×
3994

3995
        if err := node.features.Decode(r); err != nil {
124✔
3996
                return nil, err
×
3997
        }
×
3998

3999
        return node, nil
124✔
4000
}
4001

4002
func deserializeLightningNode(r io.Reader) (LightningNode, error) {
8,508✔
4003
        var (
8,508✔
4004
                node    LightningNode
8,508✔
4005
                scratch [8]byte
8,508✔
4006
                err     error
8,508✔
4007
        )
8,508✔
4008

8,508✔
4009
        // Always populate a feature vector, even if we don't have a node
8,508✔
4010
        // announcement and short circuit below.
8,508✔
4011
        node.Features = lnwire.EmptyFeatureVector()
8,508✔
4012

8,508✔
4013
        if _, err := r.Read(scratch[:]); err != nil {
8,508✔
4014
                return LightningNode{}, err
×
4015
        }
×
4016

4017
        unix := int64(byteOrder.Uint64(scratch[:]))
8,508✔
4018
        node.LastUpdate = time.Unix(unix, 0)
8,508✔
4019

8,508✔
4020
        if _, err := io.ReadFull(r, node.PubKeyBytes[:]); err != nil {
8,508✔
4021
                return LightningNode{}, err
×
4022
        }
×
4023

4024
        if _, err := r.Read(scratch[:2]); err != nil {
8,508✔
4025
                return LightningNode{}, err
×
4026
        }
×
4027

4028
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
8,508✔
4029
        if hasNodeAnn == 1 {
16,875✔
4030
                node.HaveNodeAnnouncement = true
8,367✔
4031
        } else {
8,512✔
4032
                node.HaveNodeAnnouncement = false
145✔
4033
        }
145✔
4034

4035
        // The rest of the data is optional, and will only be there if we got a node
4036
        // announcement for this node.
4037
        if !node.HaveNodeAnnouncement {
8,653✔
4038
                return node, nil
145✔
4039
        }
145✔
4040

4041
        // We did get a node announcement for this node, so we'll have the rest
4042
        // of the data available.
4043
        if err := binary.Read(r, byteOrder, &node.Color.R); err != nil {
8,367✔
4044
                return LightningNode{}, err
×
4045
        }
×
4046
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
8,367✔
4047
                return LightningNode{}, err
×
4048
        }
×
4049
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
8,367✔
4050
                return LightningNode{}, err
×
4051
        }
×
4052

4053
        node.Alias, err = wire.ReadVarString(r, 0)
8,367✔
4054
        if err != nil {
8,367✔
4055
                return LightningNode{}, err
×
4056
        }
×
4057

4058
        err = node.Features.Decode(r)
8,367✔
4059
        if err != nil {
8,367✔
4060
                return LightningNode{}, err
×
4061
        }
×
4062

4063
        if _, err := r.Read(scratch[:2]); err != nil {
8,367✔
4064
                return LightningNode{}, err
×
4065
        }
×
4066
        numAddresses := int(byteOrder.Uint16(scratch[:2]))
8,367✔
4067

8,367✔
4068
        var addresses []net.Addr
8,367✔
4069
        for i := 0; i < numAddresses; i++ {
18,953✔
4070
                address, err := deserializeAddr(r)
10,586✔
4071
                if err != nil {
10,586✔
4072
                        return LightningNode{}, err
×
4073
                }
×
4074
                addresses = append(addresses, address)
10,586✔
4075
        }
4076
        node.Addresses = addresses
8,367✔
4077

8,367✔
4078
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,367✔
4079
        if err != nil {
8,367✔
4080
                return LightningNode{}, err
×
4081
        }
×
4082

4083
        // We'll try and see if there are any opaque bytes left, if not, then
4084
        // we'll ignore the EOF error and return the node as is.
4085
        node.ExtraOpaqueData, err = wire.ReadVarBytes(
8,367✔
4086
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,367✔
4087
        )
8,367✔
4088
        switch {
8,367✔
4089
        case err == io.ErrUnexpectedEOF:
×
4090
        case err == io.EOF:
×
4091
        case err != nil:
×
4092
                return LightningNode{}, err
×
4093
        }
4094

4095
        return node, nil
8,367✔
4096
}
4097

4098
func putChanEdgeInfo(edgeIndex kvdb.RwBucket,
4099
        edgeInfo *models.ChannelEdgeInfo, chanID [8]byte) error {
1,464✔
4100

1,464✔
4101
        var b bytes.Buffer
1,464✔
4102

1,464✔
4103
        if _, err := b.Write(edgeInfo.NodeKey1Bytes[:]); err != nil {
1,464✔
4104
                return err
×
4105
        }
×
4106
        if _, err := b.Write(edgeInfo.NodeKey2Bytes[:]); err != nil {
1,464✔
4107
                return err
×
4108
        }
×
4109
        if _, err := b.Write(edgeInfo.BitcoinKey1Bytes[:]); err != nil {
1,464✔
4110
                return err
×
4111
        }
×
4112
        if _, err := b.Write(edgeInfo.BitcoinKey2Bytes[:]); err != nil {
1,464✔
4113
                return err
×
4114
        }
×
4115

4116
        if err := wire.WriteVarBytes(&b, 0, edgeInfo.Features); err != nil {
1,464✔
4117
                return err
×
4118
        }
×
4119

4120
        authProof := edgeInfo.AuthProof
1,464✔
4121
        var nodeSig1, nodeSig2, bitcoinSig1, bitcoinSig2 []byte
1,464✔
4122
        if authProof != nil {
2,845✔
4123
                nodeSig1 = authProof.NodeSig1Bytes
1,381✔
4124
                nodeSig2 = authProof.NodeSig2Bytes
1,381✔
4125
                bitcoinSig1 = authProof.BitcoinSig1Bytes
1,381✔
4126
                bitcoinSig2 = authProof.BitcoinSig2Bytes
1,381✔
4127
        }
1,381✔
4128

4129
        if err := wire.WriteVarBytes(&b, 0, nodeSig1); err != nil {
1,464✔
4130
                return err
×
4131
        }
×
4132
        if err := wire.WriteVarBytes(&b, 0, nodeSig2); err != nil {
1,464✔
4133
                return err
×
4134
        }
×
4135
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig1); err != nil {
1,464✔
4136
                return err
×
4137
        }
×
4138
        if err := wire.WriteVarBytes(&b, 0, bitcoinSig2); err != nil {
1,464✔
4139
                return err
×
4140
        }
×
4141

4142
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
1,464✔
4143
                return err
×
4144
        }
×
4145
        if err := binary.Write(&b, byteOrder, uint64(edgeInfo.Capacity)); err != nil {
1,464✔
4146
                return err
×
4147
        }
×
4148
        if _, err := b.Write(chanID[:]); err != nil {
1,464✔
4149
                return err
×
4150
        }
×
4151
        if _, err := b.Write(edgeInfo.ChainHash[:]); err != nil {
1,464✔
4152
                return err
×
4153
        }
×
4154

4155
        if len(edgeInfo.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
1,464✔
4156
                return ErrTooManyExtraOpaqueBytes(len(edgeInfo.ExtraOpaqueData))
×
4157
        }
×
4158
        err := wire.WriteVarBytes(&b, 0, edgeInfo.ExtraOpaqueData)
1,464✔
4159
        if err != nil {
1,464✔
4160
                return err
×
4161
        }
×
4162

4163
        return edgeIndex.Put(chanID[:], b.Bytes())
1,464✔
4164
}
4165

4166
func fetchChanEdgeInfo(edgeIndex kvdb.RBucket,
4167
        chanID []byte) (models.ChannelEdgeInfo, error) {
4,278✔
4168

4,278✔
4169
        edgeInfoBytes := edgeIndex.Get(chanID)
4,278✔
4170
        if edgeInfoBytes == nil {
4,372✔
4171
                return models.ChannelEdgeInfo{}, ErrEdgeNotFound
94✔
4172
        }
94✔
4173

4174
        edgeInfoReader := bytes.NewReader(edgeInfoBytes)
4,188✔
4175
        return deserializeChanEdgeInfo(edgeInfoReader)
4,188✔
4176
}
4177

4178
func deserializeChanEdgeInfo(r io.Reader) (models.ChannelEdgeInfo, error) {
4,817✔
4179
        var (
4,817✔
4180
                err      error
4,817✔
4181
                edgeInfo models.ChannelEdgeInfo
4,817✔
4182
        )
4,817✔
4183

4,817✔
4184
        if _, err := io.ReadFull(r, edgeInfo.NodeKey1Bytes[:]); err != nil {
4,817✔
4185
                return models.ChannelEdgeInfo{}, err
×
4186
        }
×
4187
        if _, err := io.ReadFull(r, edgeInfo.NodeKey2Bytes[:]); err != nil {
4,817✔
4188
                return models.ChannelEdgeInfo{}, err
×
4189
        }
×
4190
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey1Bytes[:]); err != nil {
4,817✔
4191
                return models.ChannelEdgeInfo{}, err
×
4192
        }
×
4193
        if _, err := io.ReadFull(r, edgeInfo.BitcoinKey2Bytes[:]); err != nil {
4,817✔
4194
                return models.ChannelEdgeInfo{}, err
×
4195
        }
×
4196

4197
        edgeInfo.Features, err = wire.ReadVarBytes(r, 0, 900, "features")
4,817✔
4198
        if err != nil {
4,817✔
4199
                return models.ChannelEdgeInfo{}, err
×
4200
        }
×
4201

4202
        proof := &models.ChannelAuthProof{}
4,817✔
4203

4,817✔
4204
        proof.NodeSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,817✔
4205
        if err != nil {
4,817✔
4206
                return models.ChannelEdgeInfo{}, err
×
4207
        }
×
4208
        proof.NodeSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,817✔
4209
        if err != nil {
4,817✔
4210
                return models.ChannelEdgeInfo{}, err
×
4211
        }
×
4212
        proof.BitcoinSig1Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,817✔
4213
        if err != nil {
4,817✔
4214
                return models.ChannelEdgeInfo{}, err
×
4215
        }
×
4216
        proof.BitcoinSig2Bytes, err = wire.ReadVarBytes(r, 0, 80, "sigs")
4,817✔
4217
        if err != nil {
4,817✔
4218
                return models.ChannelEdgeInfo{}, err
×
4219
        }
×
4220

4221
        if !proof.IsEmpty() {
6,677✔
4222
                edgeInfo.AuthProof = proof
1,860✔
4223
        }
1,860✔
4224

4225
        edgeInfo.ChannelPoint = wire.OutPoint{}
4,817✔
4226
        if err := readOutpoint(r, &edgeInfo.ChannelPoint); err != nil {
4,817✔
4227
                return models.ChannelEdgeInfo{}, err
×
4228
        }
×
4229
        if err := binary.Read(r, byteOrder, &edgeInfo.Capacity); err != nil {
4,817✔
4230
                return models.ChannelEdgeInfo{}, err
×
4231
        }
×
4232
        if err := binary.Read(r, byteOrder, &edgeInfo.ChannelID); err != nil {
4,817✔
4233
                return models.ChannelEdgeInfo{}, err
×
4234
        }
×
4235

4236
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
4,817✔
4237
                return models.ChannelEdgeInfo{}, err
×
4238
        }
×
4239

4240
        // We'll try and see if there are any opaque bytes left, if not, then
4241
        // we'll ignore the EOF error and return the edge as is.
4242
        edgeInfo.ExtraOpaqueData, err = wire.ReadVarBytes(
4,817✔
4243
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
4,817✔
4244
        )
4,817✔
4245
        switch {
4,817✔
4246
        case err == io.ErrUnexpectedEOF:
×
4247
        case err == io.EOF:
×
4248
        case err != nil:
×
4249
                return models.ChannelEdgeInfo{}, err
×
4250
        }
4251

4252
        return edgeInfo, nil
4,817✔
4253
}
4254

4255
func putChanEdgePolicy(edges kvdb.RwBucket, edge *models.ChannelEdgePolicy,
4256
        from, to []byte) error {
2,619✔
4257

2,619✔
4258
        var edgeKey [33 + 8]byte
2,619✔
4259
        copy(edgeKey[:], from)
2,619✔
4260
        byteOrder.PutUint64(edgeKey[33:], edge.ChannelID)
2,619✔
4261

2,619✔
4262
        var b bytes.Buffer
2,619✔
4263
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
2,619✔
4264
                return err
×
4265
        }
×
4266

4267
        // Before we write out the new edge, we'll create a new entry in the
4268
        // update index in order to keep it fresh.
4269
        updateUnix := uint64(edge.LastUpdate.Unix())
2,619✔
4270
        var indexKey [8 + 8]byte
2,619✔
4271
        byteOrder.PutUint64(indexKey[:8], updateUnix)
2,619✔
4272
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
2,619✔
4273

2,619✔
4274
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
2,619✔
4275
        if err != nil {
2,619✔
4276
                return err
×
4277
        }
×
4278

4279
        // If there was already an entry for this edge, then we'll need to
4280
        // delete the old one to ensure we don't leave around any after-images.
4281
        // An unknown policy value does not have a update time recorded, so
4282
        // it also does not need to be removed.
4283
        if edgeBytes := edges.Get(edgeKey[:]); edgeBytes != nil &&
2,619✔
4284
                !bytes.Equal(edgeBytes[:], unknownPolicy) {
2,644✔
4285

25✔
4286
                // In order to delete the old entry, we'll need to obtain the
25✔
4287
                // *prior* update time in order to delete it. To do this, we'll
25✔
4288
                // need to deserialize the existing policy within the database
25✔
4289
                // (now outdated by the new one), and delete its corresponding
25✔
4290
                // entry within the update index. We'll ignore any
25✔
4291
                // ErrEdgePolicyOptionalFieldNotFound error, as we only need
25✔
4292
                // the channel ID and update time to delete the entry.
25✔
4293
                // TODO(halseth): get rid of these invalid policies in a
25✔
4294
                // migration.
25✔
4295
                oldEdgePolicy, err := deserializeChanEdgePolicy(
25✔
4296
                        bytes.NewReader(edgeBytes),
25✔
4297
                )
25✔
4298
                if err != nil && err != ErrEdgePolicyOptionalFieldNotFound {
25✔
4299
                        return err
×
4300
                }
×
4301

4302
                oldUpdateTime := uint64(oldEdgePolicy.LastUpdate.Unix())
25✔
4303

25✔
4304
                var oldIndexKey [8 + 8]byte
25✔
4305
                byteOrder.PutUint64(oldIndexKey[:8], oldUpdateTime)
25✔
4306
                byteOrder.PutUint64(oldIndexKey[8:], edge.ChannelID)
25✔
4307

25✔
4308
                if err := updateIndex.Delete(oldIndexKey[:]); err != nil {
25✔
4309
                        return err
×
4310
                }
×
4311
        }
4312

4313
        if err := updateIndex.Put(indexKey[:], nil); err != nil {
2,619✔
4314
                return err
×
4315
        }
×
4316

4317
        updateEdgePolicyDisabledIndex(
2,619✔
4318
                edges, edge.ChannelID,
2,619✔
4319
                edge.ChannelFlags&lnwire.ChanUpdateDirection > 0,
2,619✔
4320
                edge.IsDisabled(),
2,619✔
4321
        )
2,619✔
4322

2,619✔
4323
        return edges.Put(edgeKey[:], b.Bytes()[:])
2,619✔
4324
}
4325

4326
// updateEdgePolicyDisabledIndex is used to update the disabledEdgePolicyIndex
4327
// bucket by either add a new disabled ChannelEdgePolicy or remove an existing
4328
// one.
4329
// The direction represents the direction of the edge and disabled is used for
4330
// deciding whether to remove or add an entry to the bucket.
4331
// In general a channel is disabled if two entries for the same chanID exist
4332
// in this bucket.
4333
// Maintaining the bucket this way allows a fast retrieval of disabled
4334
// channels, for example when prune is needed.
4335
func updateEdgePolicyDisabledIndex(edges kvdb.RwBucket, chanID uint64,
4336
        direction bool, disabled bool) error {
2,893✔
4337

2,893✔
4338
        var disabledEdgeKey [8 + 1]byte
2,893✔
4339
        byteOrder.PutUint64(disabledEdgeKey[0:], chanID)
2,893✔
4340
        if direction {
4,338✔
4341
                disabledEdgeKey[8] = 1
1,445✔
4342
        }
1,445✔
4343

4344
        disabledEdgePolicyIndex, err := edges.CreateBucketIfNotExists(
2,893✔
4345
                disabledEdgePolicyBucket,
2,893✔
4346
        )
2,893✔
4347
        if err != nil {
2,893✔
4348
                return err
×
4349
        }
×
4350

4351
        if disabled {
2,923✔
4352
                return disabledEdgePolicyIndex.Put(disabledEdgeKey[:], []byte{})
30✔
4353
        }
30✔
4354

4355
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
2,867✔
4356
}
4357

4358
// putChanEdgePolicyUnknown marks the edge policy as unknown
4359
// in the edges bucket.
4360
func putChanEdgePolicyUnknown(edges kvdb.RwBucket, channelID uint64,
4361
        from []byte) error {
2,922✔
4362

2,922✔
4363
        var edgeKey [33 + 8]byte
2,922✔
4364
        copy(edgeKey[:], from)
2,922✔
4365
        byteOrder.PutUint64(edgeKey[33:], channelID)
2,922✔
4366

2,922✔
4367
        if edges.Get(edgeKey[:]) != nil {
2,922✔
4368
                return fmt.Errorf("cannot write unknown policy for channel %v "+
×
4369
                        " when there is already a policy present", channelID)
×
4370
        }
×
4371

4372
        return edges.Put(edgeKey[:], unknownPolicy)
2,922✔
4373
}
4374

4375
func fetchChanEdgePolicy(edges kvdb.RBucket, chanID []byte,
4376
        nodePub []byte) (*models.ChannelEdgePolicy, error) {
8,134✔
4377

8,134✔
4378
        var edgeKey [33 + 8]byte
8,134✔
4379
        copy(edgeKey[:], nodePub)
8,134✔
4380
        copy(edgeKey[33:], chanID[:])
8,134✔
4381

8,134✔
4382
        edgeBytes := edges.Get(edgeKey[:])
8,134✔
4383
        if edgeBytes == nil {
8,134✔
4384
                return nil, ErrEdgeNotFound
×
4385
        }
×
4386

4387
        // No need to deserialize unknown policy.
4388
        if bytes.Equal(edgeBytes[:], unknownPolicy) {
8,507✔
4389
                return nil, nil
373✔
4390
        }
373✔
4391

4392
        edgeReader := bytes.NewReader(edgeBytes)
7,765✔
4393

7,765✔
4394
        ep, err := deserializeChanEdgePolicy(edgeReader)
7,765✔
4395
        switch {
7,765✔
4396
        // If the db policy was missing an expected optional field, we return
4397
        // nil as if the policy was unknown.
4398
        case err == ErrEdgePolicyOptionalFieldNotFound:
1✔
4399
                return nil, nil
1✔
4400

4401
        case err != nil:
×
4402
                return nil, err
×
4403
        }
4404

4405
        return ep, nil
7,764✔
4406
}
4407

4408
func fetchChanEdgePolicies(edgeIndex kvdb.RBucket, edges kvdb.RBucket,
4409
        chanID []byte) (*models.ChannelEdgePolicy, *models.ChannelEdgePolicy,
4410
        error) {
251✔
4411

251✔
4412
        edgeInfo := edgeIndex.Get(chanID)
251✔
4413
        if edgeInfo == nil {
251✔
4414
                return nil, nil, fmt.Errorf("%w: chanID=%x", ErrEdgeNotFound,
×
4415
                        chanID)
×
4416
        }
×
4417

4418
        // The first node is contained within the first half of the edge
4419
        // information. We only propagate the error here and below if it's
4420
        // something other than edge non-existence.
4421
        node1Pub := edgeInfo[:33]
251✔
4422
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
251✔
4423
        if err != nil {
251✔
4424
                return nil, nil, fmt.Errorf("%w: node1Pub=%x", ErrEdgeNotFound,
×
4425
                        node1Pub)
×
4426
        }
×
4427

4428
        // Similarly, the second node is contained within the latter
4429
        // half of the edge information.
4430
        node2Pub := edgeInfo[33:66]
251✔
4431
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
251✔
4432
        if err != nil {
251✔
4433
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4434
                        node2Pub)
×
4435
        }
×
4436

4437
        return edge1, edge2, nil
251✔
4438
}
4439

4440
func serializeChanEdgePolicy(w io.Writer, edge *models.ChannelEdgePolicy,
4441
        to []byte) error {
2,621✔
4442

2,621✔
4443
        err := wire.WriteVarBytes(w, 0, edge.SigBytes)
2,621✔
4444
        if err != nil {
2,621✔
4445
                return err
×
4446
        }
×
4447

4448
        if err := binary.Write(w, byteOrder, edge.ChannelID); err != nil {
2,621✔
4449
                return err
×
4450
        }
×
4451

4452
        var scratch [8]byte
2,621✔
4453
        updateUnix := uint64(edge.LastUpdate.Unix())
2,621✔
4454
        byteOrder.PutUint64(scratch[:], updateUnix)
2,621✔
4455
        if _, err := w.Write(scratch[:]); err != nil {
2,621✔
4456
                return err
×
4457
        }
×
4458

4459
        if err := binary.Write(w, byteOrder, edge.MessageFlags); err != nil {
2,621✔
4460
                return err
×
4461
        }
×
4462
        if err := binary.Write(w, byteOrder, edge.ChannelFlags); err != nil {
2,621✔
4463
                return err
×
4464
        }
×
4465
        if err := binary.Write(w, byteOrder, edge.TimeLockDelta); err != nil {
2,621✔
4466
                return err
×
4467
        }
×
4468
        if err := binary.Write(w, byteOrder, uint64(edge.MinHTLC)); err != nil {
2,621✔
4469
                return err
×
4470
        }
×
4471
        if err := binary.Write(w, byteOrder, uint64(edge.FeeBaseMSat)); err != nil {
2,621✔
4472
                return err
×
4473
        }
×
4474
        if err := binary.Write(w, byteOrder, uint64(edge.FeeProportionalMillionths)); err != nil {
2,621✔
4475
                return err
×
4476
        }
×
4477

4478
        if _, err := w.Write(to); err != nil {
2,621✔
4479
                return err
×
4480
        }
×
4481

4482
        // If the max_htlc field is present, we write it. To be compatible with
4483
        // older versions that wasn't aware of this field, we write it as part
4484
        // of the opaque data.
4485
        // TODO(halseth): clean up when moving to TLV.
4486
        var opaqueBuf bytes.Buffer
2,621✔
4487
        if edge.MessageFlags.HasMaxHtlc() {
4,858✔
4488
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
2,237✔
4489
                if err != nil {
2,237✔
4490
                        return err
×
4491
                }
×
4492
        }
4493

4494
        if len(edge.ExtraOpaqueData) > MaxAllowedExtraOpaqueBytes {
2,621✔
4495
                return ErrTooManyExtraOpaqueBytes(len(edge.ExtraOpaqueData))
×
4496
        }
×
4497
        if _, err := opaqueBuf.Write(edge.ExtraOpaqueData); err != nil {
2,621✔
4498
                return err
×
4499
        }
×
4500

4501
        if err := wire.WriteVarBytes(w, 0, opaqueBuf.Bytes()); err != nil {
2,621✔
4502
                return err
×
4503
        }
×
4504
        return nil
2,621✔
4505
}
4506

4507
func deserializeChanEdgePolicy(r io.Reader) (*models.ChannelEdgePolicy, error) {
7,787✔
4508
        // Deserialize the policy. Note that in case an optional field is not
7,787✔
4509
        // found, both an error and a populated policy object are returned.
7,787✔
4510
        edge, deserializeErr := deserializeChanEdgePolicyRaw(r)
7,787✔
4511
        if deserializeErr != nil &&
7,787✔
4512
                deserializeErr != ErrEdgePolicyOptionalFieldNotFound {
7,787✔
4513

×
4514
                return nil, deserializeErr
×
4515
        }
×
4516

4517
        return edge, deserializeErr
7,787✔
4518
}
4519

4520
func deserializeChanEdgePolicyRaw(r io.Reader) (*models.ChannelEdgePolicy,
4521
        error) {
8,794✔
4522

8,794✔
4523
        edge := &models.ChannelEdgePolicy{}
8,794✔
4524

8,794✔
4525
        var err error
8,794✔
4526
        edge.SigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
8,794✔
4527
        if err != nil {
8,794✔
4528
                return nil, err
×
4529
        }
×
4530

4531
        if err := binary.Read(r, byteOrder, &edge.ChannelID); err != nil {
8,794✔
4532
                return nil, err
×
4533
        }
×
4534

4535
        var scratch [8]byte
8,794✔
4536
        if _, err := r.Read(scratch[:]); err != nil {
8,794✔
4537
                return nil, err
×
4538
        }
×
4539
        unix := int64(byteOrder.Uint64(scratch[:]))
8,794✔
4540
        edge.LastUpdate = time.Unix(unix, 0)
8,794✔
4541

8,794✔
4542
        if err := binary.Read(r, byteOrder, &edge.MessageFlags); err != nil {
8,794✔
4543
                return nil, err
×
4544
        }
×
4545
        if err := binary.Read(r, byteOrder, &edge.ChannelFlags); err != nil {
8,794✔
4546
                return nil, err
×
4547
        }
×
4548
        if err := binary.Read(r, byteOrder, &edge.TimeLockDelta); err != nil {
8,794✔
4549
                return nil, err
×
4550
        }
×
4551

4552
        var n uint64
8,794✔
4553
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,794✔
4554
                return nil, err
×
4555
        }
×
4556
        edge.MinHTLC = lnwire.MilliSatoshi(n)
8,794✔
4557

8,794✔
4558
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,794✔
4559
                return nil, err
×
4560
        }
×
4561
        edge.FeeBaseMSat = lnwire.MilliSatoshi(n)
8,794✔
4562

8,794✔
4563
        if err := binary.Read(r, byteOrder, &n); err != nil {
8,794✔
4564
                return nil, err
×
4565
        }
×
4566
        edge.FeeProportionalMillionths = lnwire.MilliSatoshi(n)
8,794✔
4567

8,794✔
4568
        if _, err := r.Read(edge.ToNode[:]); err != nil {
8,794✔
4569
                return nil, err
×
4570
        }
×
4571

4572
        // We'll try and see if there are any opaque bytes left, if not, then
4573
        // we'll ignore the EOF error and return the edge as is.
4574
        edge.ExtraOpaqueData, err = wire.ReadVarBytes(
8,794✔
4575
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
8,794✔
4576
        )
8,794✔
4577
        switch {
8,794✔
4578
        case err == io.ErrUnexpectedEOF:
×
4579
        case err == io.EOF:
3✔
4580
        case err != nil:
×
4581
                return nil, err
×
4582
        }
4583

4584
        // See if optional fields are present.
4585
        if edge.MessageFlags.HasMaxHtlc() {
17,202✔
4586
                // The max_htlc field should be at the beginning of the opaque
8,408✔
4587
                // bytes.
8,408✔
4588
                opq := edge.ExtraOpaqueData
8,408✔
4589

8,408✔
4590
                // If the max_htlc field is not present, it might be old data
8,408✔
4591
                // stored before this field was validated. We'll return the
8,408✔
4592
                // edge along with an error.
8,408✔
4593
                if len(opq) < 8 {
8,411✔
4594
                        return edge, ErrEdgePolicyOptionalFieldNotFound
3✔
4595
                }
3✔
4596

4597
                maxHtlc := byteOrder.Uint64(opq[:8])
8,405✔
4598
                edge.MaxHTLC = lnwire.MilliSatoshi(maxHtlc)
8,405✔
4599

8,405✔
4600
                // Exclude the parsed field from the rest of the opaque data.
8,405✔
4601
                edge.ExtraOpaqueData = opq[8:]
8,405✔
4602
        }
4603

4604
        return edge, nil
8,791✔
4605
}
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