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

lightningnetwork / lnd / 15569071323

10 Jun 2025 08:00PM UTC coverage: 58.363% (+0.03%) from 58.331%
15569071323

Pull #9752

github

web-flow
Merge 3e7a64ce6 into 32592dbd2
Pull Request #9752: routerrpc: reject payment to invoice that don't have payment secret or blinded paths

6 of 13 new or added lines in 2 files covered. (46.15%)

990 existing lines in 11 files now uncovered.

97788 of 167550 relevant lines covered (58.36%)

1.81 hits per line

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

86.61
/graph/db/graph_cache.go
1
package graphdb
2

3
import (
4
        "fmt"
5
        "sync"
6

7
        "github.com/btcsuite/btcd/btcutil"
8
        "github.com/lightningnetwork/lnd/graph/db/models"
9
        "github.com/lightningnetwork/lnd/lnwire"
10
        "github.com/lightningnetwork/lnd/routing/route"
11
)
12

13
// DirectedChannel is a type that stores the channel information as seen from
14
// one side of the channel.
15
type DirectedChannel struct {
16
        // ChannelID is the unique identifier of this channel.
17
        ChannelID uint64
18

19
        // IsNode1 indicates if this is the node with the smaller public key.
20
        IsNode1 bool
21

22
        // OtherNode is the public key of the node on the other end of this
23
        // channel.
24
        OtherNode route.Vertex
25

26
        // Capacity is the announced capacity of this channel in satoshis.
27
        Capacity btcutil.Amount
28

29
        // OutPolicySet is a boolean that indicates whether the node has an
30
        // outgoing policy set. For pathfinding only the existence of the policy
31
        // is important to know, not the actual content.
32
        OutPolicySet bool
33

34
        // InPolicy is the incoming policy *from* the other node to this node.
35
        // In path finding, we're walking backward from the destination to the
36
        // source, so we're always interested in the edge that arrives to us
37
        // from the other node.
38
        InPolicy *models.CachedEdgePolicy
39

40
        // Inbound fees of this node.
41
        InboundFee lnwire.Fee
42
}
43

44
// DeepCopy creates a deep copy of the channel, including the incoming policy.
45
func (c *DirectedChannel) DeepCopy() *DirectedChannel {
3✔
46
        channelCopy := *c
3✔
47

3✔
48
        if channelCopy.InPolicy != nil {
6✔
49
                inPolicyCopy := *channelCopy.InPolicy
3✔
50
                channelCopy.InPolicy = &inPolicyCopy
3✔
51

3✔
52
                // The fields for the ToNode can be overwritten by the path
3✔
53
                // finding algorithm, which is why we need a deep copy in the
3✔
54
                // first place. So we always start out with nil values, just to
3✔
55
                // be sure they don't contain any old data.
3✔
56
                channelCopy.InPolicy.ToNodePubKey = nil
3✔
57
                channelCopy.InPolicy.ToNodeFeatures = nil
3✔
58
        }
3✔
59

60
        return &channelCopy
3✔
61
}
62

63
// GraphCache is a type that holds a minimal set of information of the public
64
// channel graph that can be used for pathfinding.
65
type GraphCache struct {
66
        nodeChannels map[route.Vertex]map[uint64]*DirectedChannel
67
        nodeFeatures map[route.Vertex]*lnwire.FeatureVector
68

69
        mtx sync.RWMutex
70
}
71

72
// NewGraphCache creates a new graphCache.
73
func NewGraphCache(preAllocNumNodes int) *GraphCache {
3✔
74
        return &GraphCache{
3✔
75
                nodeChannels: make(
3✔
76
                        map[route.Vertex]map[uint64]*DirectedChannel,
3✔
77
                        // A channel connects two nodes, so we can look it up
3✔
78
                        // from both sides, meaning we get double the number of
3✔
79
                        // entries.
3✔
80
                        preAllocNumNodes*2,
3✔
81
                ),
3✔
82
                nodeFeatures: make(
3✔
83
                        map[route.Vertex]*lnwire.FeatureVector,
3✔
84
                        preAllocNumNodes,
3✔
85
                ),
3✔
86
        }
3✔
87
}
3✔
88

89
// Stats returns statistics about the current cache size.
90
func (c *GraphCache) Stats() string {
3✔
91
        c.mtx.RLock()
3✔
92
        defer c.mtx.RUnlock()
3✔
93

3✔
94
        numChannels := 0
3✔
95
        for node := range c.nodeChannels {
6✔
96
                numChannels += len(c.nodeChannels[node])
3✔
97
        }
3✔
98
        return fmt.Sprintf("num_node_features=%d, num_nodes=%d, "+
3✔
99
                "num_channels=%d", len(c.nodeFeatures), len(c.nodeChannels),
3✔
100
                numChannels)
3✔
101
}
102

103
// AddNodeFeatures adds a graph node and its features to the cache.
104
func (c *GraphCache) AddNodeFeatures(node route.Vertex,
105
        features *lnwire.FeatureVector) {
3✔
106

3✔
107
        c.mtx.Lock()
3✔
108
        defer c.mtx.Unlock()
3✔
109

3✔
110
        c.nodeFeatures[node] = features
3✔
111
}
3✔
112

113
// AddChannel adds a non-directed channel, meaning that the order of policy 1
114
// and policy 2 does not matter, the directionality is extracted from the info
115
// and policy flags automatically. The policy will be set as the outgoing policy
116
// on one node and the incoming policy on the peer's side.
117
func (c *GraphCache) AddChannel(info *models.ChannelEdgeInfo,
118
        policy1 *models.ChannelEdgePolicy, policy2 *models.ChannelEdgePolicy) {
3✔
119

3✔
120
        if info == nil {
3✔
121
                return
×
122
        }
×
123

124
        if policy1 != nil && policy1.IsDisabled() &&
3✔
125
                policy2 != nil && policy2.IsDisabled() {
6✔
126

3✔
127
                return
3✔
128
        }
3✔
129

130
        // Create the edge entry for both nodes.
131
        c.mtx.Lock()
3✔
132
        c.updateOrAddEdge(info.NodeKey1Bytes, &DirectedChannel{
3✔
133
                ChannelID: info.ChannelID,
3✔
134
                IsNode1:   true,
3✔
135
                OtherNode: info.NodeKey2Bytes,
3✔
136
                Capacity:  info.Capacity,
3✔
137
        })
3✔
138
        c.updateOrAddEdge(info.NodeKey2Bytes, &DirectedChannel{
3✔
139
                ChannelID: info.ChannelID,
3✔
140
                IsNode1:   false,
3✔
141
                OtherNode: info.NodeKey1Bytes,
3✔
142
                Capacity:  info.Capacity,
3✔
143
        })
3✔
144
        c.mtx.Unlock()
3✔
145

3✔
146
        // The policy's node is always the to_node. So if policy 1 has to_node
3✔
147
        // of node 2 then we have the policy 1 as seen from node 1.
3✔
148
        if policy1 != nil {
6✔
149
                fromNode, toNode := info.NodeKey1Bytes, info.NodeKey2Bytes
3✔
150
                if policy1.ToNode != info.NodeKey2Bytes {
3✔
151
                        fromNode, toNode = toNode, fromNode
×
152
                }
×
153
                isEdge1 := policy1.ChannelFlags&lnwire.ChanUpdateDirection == 0
3✔
154
                c.UpdatePolicy(policy1, fromNode, toNode, isEdge1)
155
        }
6✔
156
        if policy2 != nil {
3✔
157
                fromNode, toNode := info.NodeKey2Bytes, info.NodeKey1Bytes
3✔
UNCOV
158
                if policy2.ToNode != info.NodeKey1Bytes {
×
159
                        fromNode, toNode = toNode, fromNode
×
160
                }
3✔
161
                isEdge1 := policy2.ChannelFlags&lnwire.ChanUpdateDirection == 0
162
                c.UpdatePolicy(policy2, fromNode, toNode, isEdge1)
163
        }
164
}
165

166
// updateOrAddEdge makes sure the edge information for a node is either updated
3✔
167
// if it already exists or is added to that node's list of channels.
6✔
168
func (c *GraphCache) updateOrAddEdge(node route.Vertex, edge *DirectedChannel) {
3✔
169
        if len(c.nodeChannels[node]) == 0 {
3✔
170
                c.nodeChannels[node] = make(map[uint64]*DirectedChannel)
171
        }
3✔
172

173
        c.nodeChannels[node][edge.ChannelID] = edge
174
}
175

176
// UpdatePolicy updates a single policy on both the from and to node. The order
177
// of the from and to node is not strictly important. But we assume that a
178
// channel edge was added beforehand so that the directed channel struct already
179
// exists in the cache.
3✔
180
func (c *GraphCache) UpdatePolicy(policy *models.ChannelEdgePolicy, fromNode,
3✔
181
        toNode route.Vertex, edge1 bool) {
3✔
182

3✔
183
        c.mtx.Lock()
3✔
184
        defer c.mtx.Unlock()
6✔
185

3✔
UNCOV
186
        updatePolicy := func(nodeKey route.Vertex) {
×
UNCOV
187
                if len(c.nodeChannels[nodeKey]) == 0 {
×
188
                        log.Warnf("Node=%v not found in graph cache", nodeKey)
×
189

×
190
                        return
191
                }
3✔
192

3✔
UNCOV
193
                channel, ok := c.nodeChannels[nodeKey][policy.ChannelID]
×
UNCOV
194
                if !ok {
×
195
                        log.Warnf("Channel=%v not found in graph cache",
×
196
                                policy.ChannelID)
×
197

×
198
                        return
199
                }
200

201
                // Edge 1 is defined as the policy for the direction of node1 to
3✔
202
                // node2.
203
                switch {
204
                // This is node 1, and it is edge 1, so this is the outgoing
3✔
205
                // policy for node 1.
3✔
206
                case channel.IsNode1 && edge1:
6✔
207
                        channel.OutPolicySet = true
3✔
208
                        policy.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
209
                                channel.InboundFee = fee
210
                        })
211

212
                // This is node 2, and it is edge 2, so this is the outgoing
3✔
213
                // policy for node 2.
3✔
214
                case !channel.IsNode1 && !edge1:
6✔
215
                        channel.OutPolicySet = true
3✔
216
                        policy.InboundFee.WhenSome(func(fee lnwire.Fee) {
3✔
217
                                channel.InboundFee = fee
218
                        })
219

220
                // The other two cases left mean it's the inbound policy for the
3✔
221
                // node.
3✔
222
                default:
223
                        channel.InPolicy = models.NewCachedPolicy(policy)
224
                }
225
        }
3✔
226

3✔
227
        updatePolicy(fromNode)
228
        updatePolicy(toNode)
229
}
230

231
// RemoveNode completely removes a node and all its channels (including the
3✔
232
// peer's side).
3✔
233
func (c *GraphCache) RemoveNode(node route.Vertex) {
3✔
234
        c.mtx.Lock()
3✔
235
        defer c.mtx.Unlock()
3✔
236

3✔
237
        delete(c.nodeFeatures, node)
3✔
238

3✔
UNCOV
239
        // First remove all channels from the other nodes' lists.
×
UNCOV
240
        for _, channel := range c.nodeChannels[node] {
×
241
                c.removeChannelIfFound(channel.OtherNode, channel.ChannelID)
242
        }
243

3✔
244
        // Then remove our whole node completely.
245
        delete(c.nodeChannels, node)
246
}
247

3✔
248
// RemoveChannel removes a single channel between two nodes.
3✔
249
func (c *GraphCache) RemoveChannel(node1, node2 route.Vertex, chanID uint64) {
3✔
250
        c.mtx.Lock()
3✔
251
        defer c.mtx.Unlock()
3✔
252

3✔
253
        // Remove that one channel from both sides.
3✔
254
        c.removeChannelIfFound(node1, chanID)
3✔
255
        c.removeChannelIfFound(node2, chanID)
256
}
257

3✔
258
// removeChannelIfFound removes a single channel from one side.
6✔
259
func (c *GraphCache) removeChannelIfFound(node route.Vertex, chanID uint64) {
3✔
260
        if len(c.nodeChannels[node]) == 0 {
3✔
261
                return
262
        }
3✔
263

264
        delete(c.nodeChannels[node], chanID)
265
}
266

267
// UpdateChannel updates the channel edge information for a specific edge. We
3✔
268
// expect the edge to already exist and be known. If it does not yet exist, this
3✔
269
// call is a no-op.
3✔
270
func (c *GraphCache) UpdateChannel(info *models.ChannelEdgeInfo) {
3✔
271
        c.mtx.Lock()
3✔
272
        defer c.mtx.Unlock()
6✔
273

3✔
274
        if len(c.nodeChannels[info.NodeKey1Bytes]) == 0 ||
3✔
275
                len(c.nodeChannels[info.NodeKey2Bytes]) == 0 {
276

3✔
277
                return
6✔
278
        }
3✔
279

3✔
280
        channel, ok := c.nodeChannels[info.NodeKey1Bytes][info.ChannelID]
3✔
281
        if ok {
3✔
282
                // We only expect to be called when the channel is already
3✔
283
                // known.
3✔
284
                channel.Capacity = info.Capacity
3✔
285
                channel.OtherNode = info.NodeKey2Bytes
3✔
286
        }
287

6✔
288
        channel, ok = c.nodeChannels[info.NodeKey2Bytes][info.ChannelID]
3✔
289
        if ok {
3✔
290
                channel.Capacity = info.Capacity
291
                channel.OtherNode = info.NodeKey1Bytes
3✔
292
        }
3✔
293
}
6✔
294

3✔
295
// getChannels returns a copy of the passed node's channels or nil if there
3✔
296
// isn't any.
3✔
297
func (c *GraphCache) getChannels(node route.Vertex) []*DirectedChannel {
3✔
298
        c.mtx.RLock()
3✔
299
        defer c.mtx.RUnlock()
6✔
300

3✔
301
        channels, ok := c.nodeChannels[node]
3✔
302
        if !ok {
3✔
303
                return nil
304
        }
3✔
305

3✔
306
        features, ok := c.nodeFeatures[node]
307
        if !ok {
308
                // If the features were set to nil explicitly, that's fine here.
3✔
309
                // The router will overwrite the features of the destination
310
                // node with those found in the invoice if necessary. But if we
311
                // didn't yet get a node announcement we want to mimic the
312
                // behavior of the old DB based code that would always set an
313
                // empty feature vector instead of leaving it nil.
3✔
314
                features = lnwire.EmptyFeatureVector()
3✔
315
        }
3✔
316

3✔
317
        toNodeCallback := func() route.Vertex {
3✔
318
                return node
3✔
319
        }
3✔
320

3✔
321
        i := 0
3✔
322
        channelsCopy := make([]*DirectedChannel, len(channels))
3✔
323
        for _, channel := range channels {
6✔
324
                // We need to copy the channel and policy to avoid it being
6✔
325
                // updated in the cache if the path finding algorithm sets
3✔
326
                // fields on it (currently only the ToNodeFeatures of the
3✔
327
                // policy).
328
                channelCopy := channel.DeepCopy()
329
                if channelCopy.InPolicy != nil {
3✔
330
                        channelCopy.InPolicy.ToNodePubKey = toNodeCallback
331
                        channelCopy.InPolicy.ToNodeFeatures = features
332
                }
333

334
                channelsCopy[i] = channelCopy
335
                i++
336
        }
337

338
        return channelsCopy
UNCOV
339
}
×
UNCOV
340

×
UNCOV
341
// ForEachChannel invokes the given callback for each channel of the given node.
×
UNCOV
342
func (c *GraphCache) ForEachChannel(node route.Vertex,
×
UNCOV
343
        cb func(channel *DirectedChannel) error) error {
×
UNCOV
344

×
UNCOV
345
        // Obtain a copy of the node's channels. We need do this in order to
×
UNCOV
346
        // avoid deadlocks caused by interaction with the graph cache, channel
×
UNCOV
347
        // state and the graph database from multiple goroutines. This snapshot
×
UNCOV
348
        // is only used for path finding where being stale is acceptable since
×
UNCOV
349
        // the real world graph and our representation may always become
×
UNCOV
350
        // slightly out of sync for a short time and the actual channel state
×
351
        // is stored separately.
352
        channels := c.getChannels(node)
UNCOV
353
        for _, channel := range channels {
×
354
                if err := cb(channel); err != nil {
355
                        return err
356
                }
357
        }
358

3✔
359
        return nil
3✔
360
}
3✔
361

3✔
362
// ForEachNode iterates over the adjacency list of the graph, executing the
3✔
363
// call back for each node and the set of channels that emanate from the given
6✔
364
// node.
3✔
365
//
3✔
366
// NOTE: This method should be considered _read only_, the channels or nodes
3✔
367
// passed in MUST NOT be modified.
3✔
368
func (c *GraphCache) ForEachNode(cb func(node route.Vertex,
369
        channels map[uint64]*DirectedChannel) error) error {
3✔
370

371
        c.mtx.RLock()
372
        defer c.mtx.RUnlock()
373

374
        for node, channels := range c.nodeChannels {
375
                // We don't make a copy here since this is a read-only RPC
376
                // call. We also don't need the node features either for this
377
                // call.
378
                if err := cb(node, channels); err != nil {
379
                        return err
380
                }
381
        }
382

383
        return nil
384
}
385

386
// GetFeatures returns the features of the node with the given ID. If no
387
// features are known for the node, an empty feature vector is returned.
388
func (c *GraphCache) GetFeatures(node route.Vertex) *lnwire.FeatureVector {
389
        c.mtx.RLock()
390
        defer c.mtx.RUnlock()
391

392
        features, ok := c.nodeFeatures[node]
393
        if !ok || features == nil {
394
                // The router expects the features to never be nil, so we return
395
                // an empty feature set instead.
396
                return lnwire.EmptyFeatureVector()
397
        }
398

399
        return features
400
}
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