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

lightningnetwork / lnd / 9915780197

13 Jul 2024 12:30AM UTC coverage: 49.268% (-9.1%) from 58.413%
9915780197

push

github

web-flow
Merge pull request #8653 from ProofOfKeags/fn-prim

DynComms [0/n]: `fn` package additions

92837 of 188433 relevant lines covered (49.27%)

1.55 hits per line

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

69.87
/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) {
3✔
196

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

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

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

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

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

234
                err = g.ForEachChannel(func(info *models.ChannelEdgeInfo,
3✔
235
                        policy1, policy2 *models.ChannelEdgePolicy) error {
6✔
236

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

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

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

249
        return g, nil
3✔
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) {
3✔
262

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

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

3✔
274
                        return nil
3✔
275
                }
3✔
276

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

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

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

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

3✔
296
                switch {
3✔
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
3✔
307

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

314
        return channelMap, nil
3✔
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 {
3✔
348
        err := kvdb.Update(db, func(tx kvdb.RwTx) error {
6✔
349
                for _, tlb := range graphTopLevelBuckets {
6✔
350
                        if _, err := tx.CreateTopLevelBucket(tlb); err != nil {
3✔
351
                                return err
×
352
                        }
×
353
                }
354

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

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

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

391
        return nil
3✔
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) {
3✔
397
        if c.graphCache != nil {
6✔
398
                return nil, nil
3✔
399
        }
3✔
400

401
        return c.db.BeginReadTx()
×
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 {
3✔
415

3✔
416
        return c.db.View(func(tx kvdb.RTx) error {
6✔
417
                edges := tx.ReadBucket(edgeBucket)
3✔
418
                if edges == nil {
3✔
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)
3✔
425
                if err != nil {
3✔
426
                        return err
×
427
                }
×
428

429
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
430
                if edgeIndex == nil {
3✔
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 {
6✔
437
                        var chanID [8]byte
3✔
438
                        copy(chanID[:], k)
3✔
439

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

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

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

3✔
456
                        return cb(&info, policy1, policy2)
3✔
457
                })
458
        }, func() {})
3✔
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 {
3✔
469

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

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

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

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

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

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

3✔
513
                if node == e.NodeKey2Bytes {
6✔
514
                        directedChannel.OtherNode = e.NodeKey1Bytes
3✔
515
                }
3✔
516

517
                return cb(directedChannel)
3✔
518
        }
519
        return nodeTraversal(tx, node[:], c.db, dbCallback)
3✔
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) {
3✔
526

3✔
527
        if c.graphCache != nil {
6✔
528
                return c.graphCache.GetFeatures(node), nil
3✔
529
        }
3✔
530

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

538
        // If we couldn't find a node announcement, populate a blank feature
539
        // vector.
540
        case ErrGraphNodeNotFound:
×
541
                return lnwire.EmptyFeatureVector(), nil
×
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 {
×
556

×
557
        if c.graphCache != nil {
×
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 {
×
566
                channels := make(map[uint64]*DirectedChannel)
×
567

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

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

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

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

×
603
                                if node.PubKeyBytes == e.NodeKey2Bytes {
×
604
                                        directedChannel.OtherNode =
×
605
                                                e.NodeKey1Bytes
×
606
                                }
×
607

608
                                channels[e.ChannelID] = directedChannel
×
609

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

616
                return cb(node.PubKeyBytes, channels)
×
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) {
×
624
        var disabledChanIDs []uint64
×
625
        var chanEdgeFound map[uint64]struct{}
×
626

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

633
                disabledEdgePolicyIndex := edges.NestedReadBucket(
×
634
                        disabledEdgePolicyBucket,
×
635
                )
×
636
                if disabledEdgePolicyIndex == nil {
×
637
                        return nil
×
638
                }
×
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 {
×
643
                        chanID := byteOrder.Uint64(k[:8])
×
644
                        _, edgeFound := chanEdgeFound[chanID]
×
645
                        if edgeFound {
×
646
                                delete(chanEdgeFound, chanID)
×
647
                                disabledChanIDs = append(disabledChanIDs, chanID)
×
648
                                return nil
×
649
                        }
×
650

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

662
        return disabledChanIDs, nil
×
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 {
3✔
674

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

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

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

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

703
        return kvdb.View(c.db, traversal, func() {})
6✔
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 {
3✔
712

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

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

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

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

743
        return kvdb.View(c.db, traversal, func() {})
6✔
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) {
3✔
751
        var source *LightningNode
3✔
752
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
753
                // First grab the nodes bucket which stores the mapping from
3✔
754
                // pubKey to node information.
3✔
755
                nodes := tx.ReadBucket(nodeBucket)
3✔
756
                if nodes == nil {
3✔
757
                        return ErrGraphNotFound
×
758
                }
×
759

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

3✔
766
                return nil
3✔
767
        }, func() {
3✔
768
                source = nil
3✔
769
        })
3✔
770
        if err != nil {
3✔
771
                return nil, err
×
772
        }
×
773

774
        return source, nil
3✔
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) {
3✔
782
        selfPub := nodes.Get(sourceKey)
3✔
783
        if selfPub == nil {
3✔
784
                return nil, ErrSourceNodeNotSet
×
785
        }
×
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)
3✔
790
        if err != nil {
3✔
791
                return nil, err
×
792
        }
×
793

794
        return &node, nil
3✔
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 {
3✔
801
        nodePubBytes := node.PubKeyBytes[:]
3✔
802

3✔
803
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
804
                // First grab the nodes bucket which stores the mapping from
3✔
805
                // pubKey to node information.
3✔
806
                nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
807
                if err != nil {
3✔
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 {
3✔
814
                        return err
×
815
                }
×
816

817
                // Finally, we commit the information of the lightning node
818
                // itself.
819
                return addLightningNode(tx, node)
3✔
820
        }, func() {})
3✔
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 {
3✔
833

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

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

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

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

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

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

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

875
        return putLightningNode(nodes, aliases, updateIndex, node)
3✔
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) {
3✔
881
        var alias string
3✔
882

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

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

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

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

911
        return alias, nil
3✔
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 {
×
917
        // TODO(roasbeef): ensure dangling edges are removed...
×
918
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
×
919
                nodes := tx.ReadWriteBucket(nodeBucket)
×
920
                if nodes == nil {
×
921
                        return ErrGraphNodeNotFound
×
922
                }
×
923

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

928
                return c.deleteLightningNode(nodes, nodePub[:])
×
929
        }, func() {})
×
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 {
3✔
936

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

942
        if err := aliases.Delete(compressedPubKey); err != nil {
3✔
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)
3✔
950
        if err != nil {
3✔
951
                return err
×
952
        }
×
953

954
        if err := nodes.Delete(compressedPubKey); err != nil {
3✔
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)
3✔
962
        if nodeUpdateIndex == nil {
3✔
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())
3✔
969
        var indexKey [8 + 33]byte
3✔
970
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
971
        copy(indexKey[8:], compressedPubKey)
3✔
972

3✔
973
        return nodeUpdateIndex.Delete(indexKey[:])
3✔
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 {
3✔
984

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

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

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

1016
        for _, f := range op {
6✔
1017
                f(r)
3✔
1018
        }
3✔
1019

1020
        return c.chanScheduler.Execute(r)
3✔
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 {
3✔
1027

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

3✔
1032
        nodes, err := tx.CreateTopLevelBucket(nodeBucket)
3✔
1033
        if err != nil {
3✔
1034
                return err
×
1035
        }
×
1036
        edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1037
        if err != nil {
3✔
1038
                return err
×
1039
        }
×
1040
        edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1041
        if err != nil {
3✔
1042
                return err
×
1043
        }
×
1044
        chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
3✔
1045
        if err != nil {
3✔
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 {
3✔
1052
                return ErrEdgeAlreadyExist
×
1053
        }
×
1054

1055
        if c.graphCache != nil {
6✔
1056
                c.graphCache.AddChannel(edge, nil, nil)
3✔
1057
        }
3✔
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[:])
3✔
1064
        switch {
3✔
1065
        case node1Err == ErrGraphNodeNotFound:
3✔
1066
                node1Shell := LightningNode{
3✔
1067
                        PubKeyBytes:          edge.NodeKey1Bytes,
3✔
1068
                        HaveNodeAnnouncement: false,
3✔
1069
                }
3✔
1070
                err := addLightningNode(tx, &node1Shell)
3✔
1071
                if err != nil {
3✔
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[:])
3✔
1080
        switch {
3✔
1081
        case node2Err == ErrGraphNodeNotFound:
3✔
1082
                node2Shell := LightningNode{
3✔
1083
                        PubKeyBytes:          edge.NodeKey2Bytes,
3✔
1084
                        HaveNodeAnnouncement: false,
3✔
1085
                }
3✔
1086
                err := addLightningNode(tx, &node2Shell)
3✔
1087
                if err != nil {
3✔
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 {
3✔
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{
3✔
1105
                &edge.NodeKey1Bytes,
3✔
1106
                &edge.NodeKey2Bytes,
3✔
1107
        }
3✔
1108
        for _, key := range keys {
6✔
1109
                err := putChanEdgePolicyUnknown(edges, edge.ChannelID, key[:])
3✔
1110
                if err != nil {
3✔
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
3✔
1118
        if err := writeOutpoint(&b, &edge.ChannelPoint); err != nil {
3✔
1119
                return err
×
1120
        }
×
1121
        return chanIndex.Put(b.Bytes(), chanKey[:])
3✔
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) {
3✔
1132

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

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

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

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

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

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

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

1189
                        return nil
3✔
1190
                }
1191

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

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

1203
                e1, e2, err := fetchChanEdgePolicies(
3✔
1204
                        edgeIndex, edges, channelID[:],
3✔
1205
                )
3✔
1206
                if err != nil {
3✔
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 {
6✔
1213
                        upd1Time = e1.LastUpdate
3✔
1214
                }
3✔
1215
                if e2 != nil {
6✔
1216
                        upd2Time = e2.LastUpdate
3✔
1217
                }
3✔
1218

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

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

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

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

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

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

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

1262
                return putChanEdgeInfo(edgeIndex, edge, chanKey)
3✔
1263
        }, func() {})
3✔
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) {
3✔
1285

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

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

3✔
1291
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1292
                // First grab the edges bucket which houses the information
3✔
1293
                // we'd like to delete
3✔
1294
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1295
                if err != nil {
3✔
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)
3✔
1301
                if err != nil {
3✔
1302
                        return err
×
1303
                }
×
1304
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
3✔
1305
                if err != nil {
3✔
1306
                        return err
×
1307
                }
×
1308
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1309
                if nodes == nil {
3✔
1310
                        return ErrSourceNodeNotSet
×
1311
                }
×
1312
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1313
                if err != nil {
3✔
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 {
6✔
1321
                        // TODO(roasbeef): load channel bloom filter, continue
3✔
1322
                        // if NOT if filter
3✔
1323

3✔
1324
                        var opBytes bytes.Buffer
3✔
1325
                        if err := writeOutpoint(&opBytes, chanPoint); err != nil {
3✔
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())
3✔
1332
                        if chanID == nil {
6✔
1333
                                continue
3✔
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)
3✔
1340
                        if err != nil {
3✔
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(
3✔
1349
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1350
                                chanID, false, false,
3✔
1351
                        )
3✔
1352
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
3✔
1353
                                return err
×
1354
                        }
×
1355

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

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

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

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

3✔
1378
                err = pruneBucket.Put(blockHeightBytes[:], newTip[:])
3✔
1379
                if err != nil {
3✔
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)
3✔
1387
        }, func() {
3✔
1388
                chansClosed = nil
3✔
1389
        })
3✔
1390
        if err != nil {
3✔
1391
                return nil, err
×
1392
        }
×
1393

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

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

1404
        return chansClosed, nil
3✔
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 {
3✔
1412
        return kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1413
                nodes := tx.ReadWriteBucket(nodeBucket)
3✔
1414
                if nodes == nil {
3✔
1415
                        return ErrGraphNodesNotFound
×
1416
                }
×
1417
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
1418
                if edges == nil {
3✔
1419
                        return ErrGraphNotFound
×
1420
                }
×
1421
                edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
1422
                if edgeIndex == nil {
3✔
1423
                        return ErrGraphNoEdgesFound
×
1424
                }
×
1425

1426
                return c.pruneGraphNodes(nodes, edgeIndex)
3✔
1427
        }, func() {})
3✔
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 {
3✔
1435

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

3✔
1438
        // We'll retrieve the graph's source node to ensure we don't remove it
3✔
1439
        // even if it no longer has any open channels.
3✔
1440
        sourceNode, err := c.sourceNode(nodes)
3✔
1441
        if err != nil {
3✔
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)
3✔
1449
        err = nodes.ForEach(func(pubKey, nodeBytes []byte) error {
6✔
1450
                // If this is the source key, then we skip this
3✔
1451
                // iteration as the value for this key is a pubKey
3✔
1452
                // rather than raw node information.
3✔
1453
                if bytes.Equal(pubKey, sourceKey) || len(pubKey) != 33 {
6✔
1454
                        return nil
3✔
1455
                }
3✔
1456

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

3✔
1461
                return nil
3✔
1462
        })
1463
        if err != nil {
3✔
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
3✔
1470

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

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

3✔
1487
                return nil
3✔
1488
        })
3✔
1489
        if err != nil {
3✔
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
3✔
1496
        for nodePubKey, refCount := range nodeRefCounts {
6✔
1497
                // If the ref count of the node isn't zero, then we can safely
3✔
1498
                // skip it as it still has edges to or from it within the
3✔
1499
                // graph.
3✔
1500
                if refCount != 0 {
6✔
1501
                        continue
3✔
1502
                }
1503

1504
                if c.graphCache != nil {
6✔
1505
                        c.graphCache.RemoveNode(nodePubKey)
3✔
1506
                }
3✔
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 {
3✔
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",
3✔
1523
                        nodePubKey[:])
3✔
1524

3✔
1525
                numNodesPruned++
3✔
1526
        }
1527

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

1533
        return nil
3✔
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) {
3✔
1545

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

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

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

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

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

3✔
1568
        if err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
1569
                edges, err := tx.CreateTopLevelBucket(edgeBucket)
3✔
1570
                if err != nil {
3✔
1571
                        return err
×
1572
                }
×
1573
                edgeIndex, err := edges.CreateBucketIfNotExists(edgeIndexBucket)
3✔
1574
                if err != nil {
3✔
1575
                        return err
×
1576
                }
×
1577
                chanIndex, err := edges.CreateBucketIfNotExists(channelPointBucket)
3✔
1578
                if err != nil {
3✔
1579
                        return err
×
1580
                }
×
1581
                zombieIndex, err := edges.CreateBucketIfNotExists(zombieBucket)
3✔
1582
                if err != nil {
3✔
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
3✔
1593
                cursor := edgeIndex.ReadWriteCursor()
3✔
1594

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

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

1608
                for _, k := range keys {
6✔
1609
                        err = c.delChannelEdgeUnsafe(
3✔
1610
                                edges, edgeIndex, chanIndex, zombieIndex,
3✔
1611
                                k, false, false,
3✔
1612
                        )
3✔
1613
                        if err != nil && !errors.Is(err, ErrEdgeNotFound) {
3✔
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)
3✔
1621
                if err != nil {
3✔
1622
                        return err
×
1623
                }
×
1624

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

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

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

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

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

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

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

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

1664
        return removedChans, nil
3✔
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) {
3✔
1672
        var (
3✔
1673
                tipHash   chainhash.Hash
3✔
1674
                tipHeight uint32
3✔
1675
        )
3✔
1676

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

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

3✔
1689
                // The prune key with the largest block height will be our
3✔
1690
                // prune tip.
3✔
1691
                k, v := pruneCursor.Last()
3✔
1692
                if k == nil {
6✔
1693
                        return ErrGraphNeverPruned
3✔
1694
                }
3✔
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[:])
3✔
1699
                tipHeight = byteOrder.Uint32(k[:])
3✔
1700

3✔
1701
                return nil
3✔
1702
        }, func() {})
3✔
1703
        if err != nil {
6✔
1704
                return nil, 0, err
3✔
1705
        }
3✔
1706

1707
        return &tipHash, tipHeight, nil
3✔
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 {
3✔
1720

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

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

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

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

1762
                return nil
3✔
1763
        }, func() {})
3✔
1764
        if err != nil {
3✔
1765
                return err
×
1766
        }
×
1767

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

1773
        return nil
3✔
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) {
3✔
1780
        var chanID uint64
3✔
1781
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1782
                var err error
3✔
1783
                chanID, err = getChanID(tx, chanPoint)
3✔
1784
                return err
3✔
1785
        }, func() {
6✔
1786
                chanID = 0
3✔
1787
        }); err != nil {
6✔
1788
                return 0, err
3✔
1789
        }
3✔
1790

1791
        return chanID, nil
3✔
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) {
3✔
1796
        var b bytes.Buffer
3✔
1797
        if err := writeOutpoint(&b, chanPoint); err != nil {
3✔
1798
                return 0, err
×
1799
        }
×
1800

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

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

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

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

3✔
1828
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
1829
                edges := tx.ReadBucket(edgeBucket)
3✔
1830
                if edges == nil {
3✔
1831
                        return ErrGraphNoEdgesFound
×
1832
                }
×
1833
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
1834
                if edgeIndex == nil {
3✔
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()
3✔
1841

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

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

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

1861
        return cid, nil
3✔
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) {
3✔
1892

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

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

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

1918
                nodes := tx.ReadBucket(nodeBucket)
3✔
1919
                if nodes == nil {
3✔
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()
3✔
1926

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

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

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

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

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

1960
                        // First, we'll fetch the static edge information.
1961
                        edgeInfo, err := fetchChanEdgeInfo(edgeIndex, chanID)
3✔
1962
                        if err != nil {
3✔
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(
3✔
1971
                                edgeIndex, edges, chanID,
3✔
1972
                        )
3✔
1973
                        if err != nil {
3✔
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(
3✔
1981
                                nodes, edgeInfo.NodeKey1Bytes[:],
3✔
1982
                        )
3✔
1983
                        if err != nil {
3✔
1984
                                return err
×
1985
                        }
×
1986

1987
                        node2, err := fetchLightningNode(
3✔
1988
                                nodes, edgeInfo.NodeKey2Bytes[:],
3✔
1989
                        )
3✔
1990
                        if err != nil {
3✔
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{}{}
3✔
1997
                        channel := ChannelEdge{
3✔
1998
                                Info:    &edgeInfo,
3✔
1999
                                Policy1: edge1,
3✔
2000
                                Policy2: edge2,
3✔
2001
                                Node1:   &node1,
3✔
2002
                                Node2:   &node2,
3✔
2003
                        }
3✔
2004
                        edgesInHorizon = append(edgesInHorizon, channel)
3✔
2005
                        edgesToCache[chanIDInt] = channel
3✔
2006
                }
2007

2008
                return nil
3✔
2009
        }, func() {
3✔
2010
                edgesSeen = make(map[uint64]struct{})
3✔
2011
                edgesToCache = make(map[uint64]ChannelEdge)
3✔
2012
                edgesInHorizon = nil
3✔
2013
        })
3✔
2014
        switch {
3✔
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 {
6✔
2026
                c.chanCache.insert(chanid, channel)
3✔
2027
        }
3✔
2028

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

3✔
2033
        return edgesInHorizon, nil
3✔
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) {
3✔
2042

3✔
2043
        var nodesInHorizon []LightningNode
3✔
2044

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

2051
                nodeUpdateIndex := nodes.NestedReadBucket(nodeUpdateIndexBucket)
3✔
2052
                if nodeUpdateIndex == nil {
3✔
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()
3✔
2059

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

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

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

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

2083
                return nil
3✔
2084
        }, func() {
3✔
2085
                nodesInHorizon = nil
3✔
2086
        })
3✔
2087
        switch {
3✔
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
3✔
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) {
3✔
2107

3✔
2108
        var newChanIDs []uint64
3✔
2109

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

3✔
2113
        err := kvdb.Update(c.db, func(tx kvdb.RwTx) error {
6✔
2114
                edges := tx.ReadBucket(edgeBucket)
3✔
2115
                if edges == nil {
3✔
2116
                        return ErrGraphNoEdgesFound
×
2117
                }
×
2118
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
2119
                if edgeIndex == nil {
3✔
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)
3✔
2127

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

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

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

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

3✔
2151
                                switch {
3✔
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:
×
2157
                                        continue
×
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:
×
2165
                                        err := c.markEdgeLiveUnsafe(tx, scid)
×
2166
                                        if err != nil {
×
2167
                                                return err
×
2168
                                        }
×
2169
                                }
2170
                        }
2171

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

2175
                return nil
3✔
2176
        }, func() {
3✔
2177
                newChanIDs = nil
3✔
2178
        })
3✔
2179
        switch {
3✔
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
3✔
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) {
3✔
2236

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

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

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

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

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

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

2278
                        if edgeInfo.AuthProof == nil {
6✔
2279
                                continue
3✔
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)
3✔
2285
                        cid := lnwire.NewShortChanIDFromInt(rawCid)
3✔
2286

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

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

×
2297
                                continue
×
2298
                        }
2299

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

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

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

×
2311
                                        return err
×
2312
                                }
×
2313

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

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

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

×
2326
                                        return err
×
2327
                                }
×
2328

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

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

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

2342
        switch {
3✔
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:
3✔
2346
                return nil, nil
3✔
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))
3✔
2354
        for block := range channelsPerBlock {
6✔
2355
                blocks = append(blocks, block)
3✔
2356
        }
3✔
2357
        sort.Slice(blocks, func(i, j int) bool {
6✔
2358
                return blocks[i] < blocks[j]
3✔
2359
        })
3✔
2360

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

2369
        return channelRanges, nil
3✔
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) {
3✔
2382
        // TODO(roasbeef): sort cids?
3✔
2383

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

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

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

3✔
2406
                        // First, we'll fetch the static edge information. If
3✔
2407
                        // the edge is unknown, we will skip the edge and
3✔
2408
                        // continue gathering all known edges.
3✔
2409
                        edgeInfo, err := fetchChanEdgeInfo(
3✔
2410
                                edgeIndex, cidBytes[:],
3✔
2411
                        )
3✔
2412
                        switch {
3✔
2413
                        case errors.Is(err, ErrEdgeNotFound):
3✔
2414
                                continue
3✔
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(
3✔
2422
                                edgeIndex, edges, cidBytes[:],
3✔
2423
                        )
3✔
2424
                        if err != nil {
3✔
2425
                                return err
×
2426
                        }
×
2427

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

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

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

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

2461
                return chanEdges, nil
3✔
2462
        }
2463

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

2469
        return chanEdges, nil
×
2470
}
2471

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

3✔
2475
        // First, we'll fetch the edge update index bucket which currently
3✔
2476
        // stores an entry for the channel we're about to delete.
3✔
2477
        updateIndex := edgesBucket.NestedReadWriteBucket(edgeUpdateIndexBucket)
3✔
2478
        if updateIndex == nil {
3✔
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
3✔
2486
        byteOrder.PutUint64(indexKey[8:], chanID)
3✔
2487

3✔
2488
        // With the template constructed, we'll attempt to delete an entry that
3✔
2489
        // would have been created by both edges: we'll alternate the update
3✔
2490
        // times, as one may had overridden the other.
3✔
2491
        if edge1 != nil {
6✔
2492
                byteOrder.PutUint64(indexKey[:8], uint64(edge1.LastUpdate.Unix()))
3✔
2493
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
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 {
6✔
2501
                byteOrder.PutUint64(indexKey[:8], uint64(edge2.LastUpdate.Unix()))
3✔
2502
                if err := updateIndex.Delete(indexKey[:]); err != nil {
3✔
2503
                        return err
×
2504
                }
×
2505
        }
2506

2507
        return nil
3✔
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 {
3✔
2520

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

2526
        if c.graphCache != nil {
6✔
2527
                c.graphCache.RemoveChannel(
3✔
2528
                        edgeInfo.NodeKey1Bytes, edgeInfo.NodeKey2Bytes,
3✔
2529
                        edgeInfo.ChannelID,
3✔
2530
                )
3✔
2531
        }
3✔
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)
3✔
2537
        edge1, edge2, err := fetchChanEdgePolicies(edgeIndex, edges, chanID)
3✔
2538
        if err != nil {
3✔
2539
                return err
×
2540
        }
×
2541
        err = delEdgeUpdateIndexEntry(edges, cid, edge1, edge2)
3✔
2542
        if err != nil {
3✔
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
3✔
2549
        copy(edgeKey[33:], chanID)
3✔
2550

3✔
2551
        // With the latter half constructed, copy over the first public key to
3✔
2552
        // delete the edge in this direction, then the second to delete the
3✔
2553
        // edge in the opposite direction.
3✔
2554
        copy(edgeKey[:33], edgeInfo.NodeKey1Bytes[:])
3✔
2555
        if edges.Get(edgeKey[:]) != nil {
6✔
2556
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
2557
                        return err
×
2558
                }
×
2559
        }
2560
        copy(edgeKey[:33], edgeInfo.NodeKey2Bytes[:])
3✔
2561
        if edges.Get(edgeKey[:]) != nil {
6✔
2562
                if err := edges.Delete(edgeKey[:]); err != nil {
3✔
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)
3✔
2570
        updateEdgePolicyDisabledIndex(edges, cid, true, false)
3✔
2571

3✔
2572
        // With the edge data deleted, we can purge the information from the two
3✔
2573
        // edge indexes.
3✔
2574
        if err := edgeIndex.Delete(chanID); err != nil {
3✔
2575
                return err
×
2576
        }
×
2577
        var b bytes.Buffer
3✔
2578
        if err := writeOutpoint(&b, &edgeInfo.ChannelPoint); err != nil {
3✔
2579
                return err
×
2580
        }
×
2581
        if err := chanIndex.Delete(b.Bytes()); err != nil {
3✔
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 {
6✔
2589
                return nil
3✔
2590
        }
3✔
2591

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

2597
        return markEdgeZombie(
3✔
2598
                zombieIndex, byteOrder.Uint64(chanID), nodeKey1, nodeKey2,
3✔
2599
        )
3✔
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) {
×
2620

×
2621
        switch {
×
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)):
×
2632
                return info.NodeKey1Bytes, [33]byte{}
×
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:
×
2638
                return [33]byte{}, info.NodeKey2Bytes
×
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 {
3✔
2651

3✔
2652
        var (
3✔
2653
                isUpdate1    bool
3✔
2654
                edgeNotFound bool
3✔
2655
        )
3✔
2656

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

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

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

2690
        for _, f := range op {
6✔
2691
                f(r)
3✔
2692
        }
3✔
2693

2694
        return c.chanScheduler.Execute(r)
3✔
2695
}
2696

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

3✔
2700
        // If an entry for this channel is found in reject cache, we'll modify
3✔
2701
        // the entry with the updated timestamp for the direction that was just
3✔
2702
        // written. If the edge doesn't exist, we'll load the cache entry lazily
3✔
2703
        // during the next query for this edge.
3✔
2704
        if entry, ok := c.rejectCache.get(e.ChannelID); ok {
6✔
2705
                if isUpdate1 {
6✔
2706
                        entry.upd1Time = e.LastUpdate.Unix()
3✔
2707
                } else {
6✔
2708
                        entry.upd2Time = e.LastUpdate.Unix()
3✔
2709
                }
3✔
2710
                c.rejectCache.insert(e.ChannelID, entry)
3✔
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 {
6✔
2718
                if isUpdate1 {
6✔
2719
                        channel.Policy1 = e
3✔
2720
                } else {
6✔
2721
                        channel.Policy2 = e
3✔
2722
                }
3✔
2723
                c.chanCache.insert(e.ChannelID, channel)
3✔
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) {
3✔
2733

3✔
2734
        edges := tx.ReadWriteBucket(edgeBucket)
3✔
2735
        if edges == nil {
3✔
2736
                return false, ErrEdgeNotFound
×
2737
        }
×
2738
        edgeIndex := edges.NestedReadWriteBucket(edgeIndexBucket)
3✔
2739
        if edgeIndex == nil {
3✔
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
3✔
2746
        byteOrder.PutUint64(chanID[:], edge.ChannelID)
3✔
2747

3✔
2748
        // With the channel ID, we then fetch the value storing the two
3✔
2749
        // nodes which connect this channel edge.
3✔
2750
        nodeInfo := edgeIndex.Get(chanID[:])
3✔
2751
        if nodeInfo == nil {
3✔
2752
                return false, ErrEdgeNotFound
×
2753
        }
×
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
3✔
2758
        var isUpdate1 bool
3✔
2759
        if edge.ChannelFlags&lnwire.ChanUpdateDirection == 0 {
6✔
2760
                fromNode = nodeInfo[:33]
3✔
2761
                toNode = nodeInfo[33:66]
3✔
2762
                isUpdate1 = true
3✔
2763
        } else {
6✔
2764
                fromNode = nodeInfo[33:66]
3✔
2765
                toNode = nodeInfo[:33]
3✔
2766
                isUpdate1 = false
3✔
2767
        }
3✔
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)
3✔
2772
        if err != nil {
3✔
2773
                return false, err
×
2774
        }
×
2775

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

3✔
2783
        if graphCache != nil {
6✔
2784
                graphCache.UpdatePolicy(
3✔
2785
                        edge, fromNodePubKey, toNodePubKey, isUpdate1,
3✔
2786
                )
3✔
2787
        }
3✔
2788

2789
        return isUpdate1, nil
3✔
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) {
3✔
2847
        if l.pubKey != nil {
6✔
2848
                return l.pubKey, nil
3✔
2849
        }
3✔
2850

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

3✔
2857
        return key, nil
3✔
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) {
3✔
2872
        l.pubKey = key
3✔
2873
        copy(l.PubKeyBytes[:], key.SerializeCompressed())
3✔
2874
}
3✔
2875

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

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

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

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

3✔
2899
        if !signed {
6✔
2900
                return nodeAnn, nil
3✔
2901
        }
3✔
2902

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

2908
        nodeAnn.Signature = sig
3✔
2909

3✔
2910
        return nodeAnn, nil
3✔
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) {
3✔
2918

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

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

3✔
2936
                        nodeIsPublic = true
3✔
2937
                        return errDone
3✔
2938
                }
3✔
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 {
6✔
2943
                        nodeIsPublic = true
3✔
2944
                        return errDone
3✔
2945
                }
3✔
2946

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

2954
        return nodeIsPublic, nil
3✔
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✔
2963

3✔
2964
        var node *LightningNode
3✔
2965
        fetch := func(tx kvdb.RTx) error {
6✔
2966
                // First grab the nodes bucket which stores the mapping from
3✔
2967
                // pubKey to node information.
3✔
2968
                nodes := tx.ReadBucket(nodeBucket)
3✔
2969
                if nodes == nil {
3✔
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✔
2976
                if nodeBytes == nil {
6✔
2977
                        return ErrGraphNodeNotFound
3✔
2978
                }
3✔
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✔
2983
                n, err := deserializeLightningNode(nodeReader)
3✔
2984
                if err != nil {
3✔
2985
                        return err
×
2986
                }
×
2987

2988
                node = &n
3✔
2989

3✔
2990
                return nil
3✔
2991
        }
2992

2993
        if tx == nil {
6✔
2994
                err := kvdb.View(
3✔
2995
                        c.db, fetch, func() {
6✔
2996
                                node = nil
3✔
2997
                        },
3✔
2998
                )
2999
                if err != nil {
6✔
3000
                        return nil, err
3✔
3001
                }
3✔
3002

3003
                return node, nil
3✔
3004
        }
3005

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

3011
        return node, nil
×
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 {
3✔
3024

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

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

3036
// Features returns the node's features.
3037
func (n *graphCacheNode) Features() *lnwire.FeatureVector {
3✔
3038
        return n.features
3✔
3039
}
3✔
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 {
3✔
3052

3✔
3053
        return nodeTraversal(tx, n.pubKeyBytes[:], nil, cb)
3✔
3054
}
3✔
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) {
3✔
3064
        var (
3✔
3065
                updateTime time.Time
3✔
3066
                exists     bool
3✔
3067
        )
3✔
3068

3✔
3069
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3070
                // First grab the nodes bucket which stores the mapping from
3✔
3071
                // pubKey to node information.
3✔
3072
                nodes := tx.ReadBucket(nodeBucket)
3✔
3073
                if nodes == nil {
3✔
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[:])
3✔
3080
                if nodeBytes == nil {
6✔
3081
                        exists = false
3✔
3082
                        return nil
3✔
3083
                }
3✔
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)
3✔
3089
                node, err := deserializeLightningNode(nodeReader)
3✔
3090
                if err != nil {
3✔
3091
                        return err
×
3092
                }
×
3093

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

3105
        return updateTime, exists, nil
3✔
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 {
3✔
3113

3✔
3114
        traversal := func(tx kvdb.RTx) error {
6✔
3115
                edges := tx.ReadBucket(edgeBucket)
3✔
3116
                if edges == nil {
3✔
3117
                        return ErrGraphNotFound
×
3118
                }
×
3119
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3120
                if edgeIndex == nil {
3✔
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
3✔
3132
                copy(nodeStart[:], nodePub)
3✔
3133
                copy(nodeStart[33:], chanStart[:])
3✔
3134

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

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

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

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

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

3177
                return nil
3✔
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 {
6✔
3183
                return kvdb.View(db, traversal, func() {})
6✔
3184
        }
3185

3186
        // Otherwise, we re-use the existing transaction to execute the graph
3187
        // traversal.
3188
        return traversal(tx)
3✔
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 {
3✔
3207

3✔
3208
        return nodeTraversal(tx, nodePub[:], c.db, cb)
3✔
3209
}
3✔
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) {
3✔
3218

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

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

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

3244
                targetNode = &node
3✔
3245

3✔
3246
                return nil
3✔
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
3✔
3252
        if tx == nil {
3✔
3253
                err = kvdb.View(c.db, fetchNodeFunc, func() { targetNode = nil })
×
3254
        } else {
3✔
3255
                err = fetchNodeFunc(tx)
3✔
3256
        }
3✔
3257

3258
        return targetNode, err
3✔
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) {
3✔
3265
        var (
3✔
3266
                node1Key [33 + 8]byte
3✔
3267
                node2Key [33 + 8]byte
3✔
3268
        )
3✔
3269

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

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

3✔
3276
        return node1Key[:], node2Key[:]
3✔
3277
}
3✔
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) {
3✔
3287

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

3✔
3294
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3295
                // First, grab the node bucket. This will be used to populate
3✔
3296
                // the Node pointers in each edge read from disk.
3✔
3297
                nodes := tx.ReadBucket(nodeBucket)
3✔
3298
                if nodes == nil {
3✔
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)
3✔
3306
                if edges == nil {
3✔
3307
                        return ErrGraphNoEdgesFound
×
3308
                }
×
3309
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3310
                if edgeIndex == nil {
3✔
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)
3✔
3317
                if chanIndex == nil {
3✔
3318
                        return ErrGraphNoEdgesFound
×
3319
                }
×
3320
                var b bytes.Buffer
3✔
3321
                if err := writeOutpoint(&b, op); err != nil {
3✔
3322
                        return err
×
3323
                }
×
3324
                chanID := chanIndex.Get(b.Bytes())
3✔
3325
                if chanID == nil {
6✔
3326
                        return fmt.Errorf("%w: op=%v", ErrEdgeNotFound, op)
3✔
3327
                }
3✔
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)
3✔
3332
                if err != nil {
3✔
3333
                        return fmt.Errorf("%w: chanID=%x", err, chanID)
×
3334
                }
×
3335
                edgeInfo = &edge
3✔
3336

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

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

3357
        return edgeInfo, policy1, policy2, nil
3✔
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) {
3✔
3372

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

3✔
3380
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3381
                // First, grab the node bucket. This will be used to populate
3✔
3382
                // the Node pointers in each edge read from disk.
3✔
3383
                nodes := tx.ReadBucket(nodeBucket)
3✔
3384
                if nodes == nil {
3✔
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)
3✔
3392
                if edges == nil {
3✔
3393
                        return ErrGraphNoEdgesFound
×
3394
                }
×
3395
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3396
                if edgeIndex == nil {
3✔
3397
                        return ErrGraphNoEdgesFound
×
3398
                }
×
3399

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

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

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

3416
                        isZombie, pubKey1, pubKey2 := isZombieEdge(
3✔
3417
                                zombieIndex, chanID,
3✔
3418
                        )
3✔
3419
                        if !isZombie {
6✔
3420
                                return ErrEdgeNotFound
3✔
3421
                        }
3✔
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{
3✔
3428
                                NodeKey1Bytes: pubKey1,
3✔
3429
                                NodeKey2Bytes: pubKey2,
3✔
3430
                        }
3✔
3431
                        return ErrZombieEdge
3✔
3432
                }
3433

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

3439
                edgeInfo = &edge
3✔
3440

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

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

3465
        return edgeInfo, policy1, policy2, nil
3✔
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) {
3✔
3472
        var nodeIsPublic bool
3✔
3473
        err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3474
                nodes := tx.ReadBucket(nodeBucket)
3✔
3475
                if nodes == nil {
3✔
3476
                        return ErrGraphNodesNotFound
×
3477
                }
×
3478
                ourPubKey := nodes.Get(sourceKey)
3✔
3479
                if ourPubKey == nil {
3✔
3480
                        return ErrSourceNodeNotSet
×
3481
                }
×
3482
                node, err := fetchLightningNode(nodes, pubKey[:])
3✔
3483
                if err != nil {
3✔
3484
                        return err
×
3485
                }
×
3486

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

3496
        return nodeIsPublic, nil
3✔
3497
}
3498

3499
// genMultiSigP2WSH generates the p2wsh'd multisig script for 2 of 2 pubkeys.
3500
func genMultiSigP2WSH(aPub, bPub []byte) ([]byte, error) {
3✔
3501
        witnessScript, err := input.GenMultiSigScript(aPub, bPub)
3✔
3502
        if err != nil {
3✔
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(
3✔
3510
                txscript.WithScriptAllocSize(input.P2WSHSize),
3✔
3511
        )
3✔
3512
        bldr.AddOp(txscript.OP_0)
3✔
3513
        scriptHash := sha256.Sum256(witnessScript)
3✔
3514
        bldr.AddData(scriptHash[:])
3✔
3515

3✔
3516
        return bldr.Script()
3✔
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) {
3✔
3542
        var edgePoints []EdgePoint
3✔
3543
        if err := kvdb.View(c.db, func(tx kvdb.RTx) error {
6✔
3544
                // We're going to iterate over the entire channel index, so
3✔
3545
                // we'll need to fetch the edgeBucket to get to the index as
3✔
3546
                // it's a sub-bucket.
3✔
3547
                edges := tx.ReadBucket(edgeBucket)
3✔
3548
                if edges == nil {
3✔
3549
                        return ErrGraphNoEdgesFound
×
3550
                }
×
3551
                chanIndex := edges.NestedReadBucket(channelPointBucket)
3✔
3552
                if chanIndex == nil {
3✔
3553
                        return ErrGraphNoEdgesFound
×
3554
                }
×
3555
                edgeIndex := edges.NestedReadBucket(edgeIndexBucket)
3✔
3556
                if edgeIndex == nil {
3✔
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 {
6✔
3564
                        chanPointReader := bytes.NewReader(chanPointBytes)
3✔
3565

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

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

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

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

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

3600
        return edgePoints, nil
3✔
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 {
×
3608

×
3609
        c.cacheMu.Lock()
×
3610
        defer c.cacheMu.Unlock()
×
3611

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

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

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

3633
        c.rejectCache.remove(chanID)
×
3634
        c.chanCache.remove(chanID)
×
3635

×
3636
        return nil
×
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 {
3✔
3644

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

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

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

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

3✔
3660
        return c.markEdgeLiveUnsafe(nil, chanID)
3✔
3661
}
3✔
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 {
3✔
3670
        dbFn := func(tx kvdb.RwTx) error {
6✔
3671
                edges := tx.ReadWriteBucket(edgeBucket)
3✔
3672
                if edges == nil {
3✔
3673
                        return ErrGraphNoEdgesFound
×
3674
                }
×
3675
                zombieIndex := edges.NestedReadWriteBucket(zombieBucket)
3✔
3676
                if zombieIndex == nil {
3✔
3677
                        return nil
×
3678
                }
×
3679

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

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

3687
                return zombieIndex.Delete(k[:])
3✔
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
3✔
3693
        if tx == nil {
6✔
3694
                err = kvdb.Update(c.db, dbFn, func() {})
6✔
3695
        } else {
×
3696
                err = dbFn(tx)
×
3697
        }
×
3698
        if err != nil {
3✔
3699
                return err
×
3700
        }
×
3701

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

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

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

3721
        return nil
3✔
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) {
×
3728
        var (
×
3729
                isZombie         bool
×
3730
                pubKey1, pubKey2 [33]byte
×
3731
        )
×
3732

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

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

3754
        return isZombie, pubKey1, pubKey2
×
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) {
3✔
3762

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

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

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

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

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

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

3802
        return numZombies, nil
×
3803
}
3804

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

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

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

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

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

3830
        if _, err := b.Write(nodePub); err != nil {
3✔
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 {
6✔
3837
                // Write HaveNodeAnnouncement=0.
3✔
3838
                byteOrder.PutUint16(scratch[:2], 0)
3✔
3839
                if _, err := b.Write(scratch[:2]); err != nil {
3✔
3840
                        return err
×
3841
                }
×
3842

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

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

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

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

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

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

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

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

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

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

3901
        if err := aliasBucket.Put(nodePub, []byte(node.Alias)); err != nil {
3✔
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
3✔
3908
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
3909
        copy(indexKey[8:], nodePub)
3✔
3910

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

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

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

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

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

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

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

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

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

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

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

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

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

3✔
3972
        // The rest of the data is optional, and will only be there if we got a
3✔
3973
        // node announcement for this node.
3✔
3974
        if hasNodeAnn == 0 {
6✔
3975
                return node, nil
3✔
3976
        }
3✔
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
3✔
3981
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
3982
                return nil, err
×
3983
        }
×
3984
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
3985
                return nil, err
×
3986
        }
×
3987
        if err := binary.Read(r, byteOrder, &rgb); err != nil {
3✔
3988
                return nil, err
×
3989
        }
×
3990

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

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

3999
        return node, nil
3✔
4000
}
4001

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

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

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

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

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

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

4028
        hasNodeAnn := byteOrder.Uint16(scratch[:2])
3✔
4029
        if hasNodeAnn == 1 {
6✔
4030
                node.HaveNodeAnnouncement = true
3✔
4031
        } else {
6✔
4032
                node.HaveNodeAnnouncement = false
3✔
4033
        }
3✔
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 {
6✔
4038
                return node, nil
3✔
4039
        }
3✔
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 {
3✔
4044
                return LightningNode{}, err
×
4045
        }
×
4046
        if err := binary.Read(r, byteOrder, &node.Color.G); err != nil {
3✔
4047
                return LightningNode{}, err
×
4048
        }
×
4049
        if err := binary.Read(r, byteOrder, &node.Color.B); err != nil {
3✔
4050
                return LightningNode{}, err
×
4051
        }
×
4052

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

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

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

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

3✔
4078
        node.AuthSigBytes, err = wire.ReadVarBytes(r, 0, 80, "sig")
3✔
4079
        if err != nil {
3✔
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(
3✔
4086
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4087
        )
3✔
4088
        switch {
3✔
4089
        case err == io.ErrUnexpectedEOF:
×
4090
        case err == io.EOF:
×
4091
        case err != nil:
×
4092
                return LightningNode{}, err
×
4093
        }
4094

4095
        return node, nil
3✔
4096
}
4097

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

3✔
4101
        var b bytes.Buffer
3✔
4102

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

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

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

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

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

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

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

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

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

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

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

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

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

4202
        proof := &models.ChannelAuthProof{}
3✔
4203

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

4221
        if !proof.IsEmpty() {
6✔
4222
                edgeInfo.AuthProof = proof
3✔
4223
        }
3✔
4224

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

4236
        if _, err := io.ReadFull(r, edgeInfo.ChainHash[:]); err != nil {
3✔
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(
3✔
4243
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4244
        )
3✔
4245
        switch {
3✔
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
3✔
4253
}
4254

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

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

3✔
4262
        var b bytes.Buffer
3✔
4263
        if err := serializeChanEdgePolicy(&b, edge, to); err != nil {
3✔
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())
3✔
4270
        var indexKey [8 + 8]byte
3✔
4271
        byteOrder.PutUint64(indexKey[:8], updateUnix)
3✔
4272
        byteOrder.PutUint64(indexKey[8:], edge.ChannelID)
3✔
4273

3✔
4274
        updateIndex, err := edges.CreateBucketIfNotExists(edgeUpdateIndexBucket)
3✔
4275
        if err != nil {
3✔
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 &&
3✔
4284
                !bytes.Equal(edgeBytes[:], unknownPolicy) {
6✔
4285

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

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

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

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

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

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

3✔
4323
        return edges.Put(edgeKey[:], b.Bytes()[:])
3✔
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 {
3✔
4337

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

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

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

4355
        return disabledEdgePolicyIndex.Delete(disabledEdgeKey[:])
3✔
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 {
3✔
4362

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

3✔
4367
        if edges.Get(edgeKey[:]) != nil {
3✔
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)
3✔
4373
}
4374

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

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

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

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

4392
        edgeReader := bytes.NewReader(edgeBytes)
3✔
4393

3✔
4394
        ep, err := deserializeChanEdgePolicy(edgeReader)
3✔
4395
        switch {
3✔
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:
×
4399
                return nil, nil
×
4400

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

4405
        return ep, nil
3✔
4406
}
4407

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

3✔
4412
        edgeInfo := edgeIndex.Get(chanID)
3✔
4413
        if edgeInfo == nil {
3✔
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]
3✔
4422
        edge1, err := fetchChanEdgePolicy(edges, chanID, node1Pub)
3✔
4423
        if err != nil {
3✔
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]
3✔
4431
        edge2, err := fetchChanEdgePolicy(edges, chanID, node2Pub)
3✔
4432
        if err != nil {
3✔
4433
                return nil, nil, fmt.Errorf("%w: node2Pub=%x", ErrEdgeNotFound,
×
4434
                        node2Pub)
×
4435
        }
×
4436

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

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

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

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

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

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

4478
        if _, err := w.Write(to); err != nil {
3✔
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
3✔
4487
        if edge.MessageFlags.HasMaxHtlc() {
6✔
4488
                err := binary.Write(&opaqueBuf, byteOrder, uint64(edge.MaxHTLC))
3✔
4489
                if err != nil {
3✔
4490
                        return err
×
4491
                }
×
4492
        }
4493

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

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

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

×
4514
                return nil, deserializeErr
×
4515
        }
×
4516

4517
        return edge, deserializeErr
3✔
4518
}
4519

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

3✔
4523
        edge := &models.ChannelEdgePolicy{}
3✔
4524

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

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

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

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

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

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

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

3✔
4568
        if _, err := r.Read(edge.ToNode[:]); err != nil {
3✔
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(
3✔
4575
                r, 0, MaxAllowedExtraOpaqueBytes, "blob",
3✔
4576
        )
3✔
4577
        switch {
3✔
4578
        case err == io.ErrUnexpectedEOF:
×
4579
        case err == io.EOF:
×
4580
        case err != nil:
×
4581
                return nil, err
×
4582
        }
4583

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

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

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

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

4604
        return edge, nil
3✔
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