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

lightningnetwork / lnd / 26288553680

22 May 2026 12:45PM UTC coverage: 62.306% (+0.003%) from 62.303%
26288553680

Pull #10813

github

web-flow
Merge fad749d02 into cc49b3773
Pull Request #10813: Drop tor v2 onion production, keep wire codec faithful

63 of 122 new or added lines in 12 files covered. (51.64%)

31622 existing lines in 494 files now uncovered.

143913 of 230977 relevant lines covered (62.31%)

19152.0 hits per line

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

94.32
/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 {
1,602✔
46
        channelCopy := *c
1,602✔
47

1,602✔
48
        if channelCopy.InPolicy != nil {
3,176✔
49
                inPolicyCopy := *channelCopy.InPolicy
1,574✔
50
                channelCopy.InPolicy = &inPolicyCopy
1,574✔
51

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

60
        return &channelCopy
1,602✔
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 {
175✔
74
        return &GraphCache{
175✔
75
                nodeChannels: make(
175✔
76
                        map[route.Vertex]map[uint64]*DirectedChannel,
175✔
77
                        // A channel connects two nodes, so we can look it up
175✔
78
                        // from both sides, meaning we get double the number of
175✔
79
                        // entries.
175✔
80
                        preAllocNumNodes*2,
175✔
81
                ),
175✔
82
                nodeFeatures: make(
175✔
83
                        map[route.Vertex]*lnwire.FeatureVector,
175✔
84
                        preAllocNumNodes,
175✔
85
                ),
175✔
86
        }
175✔
87
}
175✔
88

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

410✔
94
        numChannels := 0
410✔
95
        for node := range c.nodeChannels {
918✔
96
                numChannels += len(c.nodeChannels[node])
508✔
97
        }
508✔
98
        return fmt.Sprintf("num_node_features=%d, num_nodes=%d, "+
410✔
99
                "num_channels=%d", len(c.nodeFeatures), len(c.nodeChannels),
410✔
100
                numChannels)
410✔
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) {
1,136✔
106

1,136✔
107
        c.mtx.Lock()
1,136✔
108
        defer c.mtx.Unlock()
1,136✔
109

1,136✔
110
        c.nodeFeatures[node] = features
1,136✔
111
}
1,136✔
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.CachedEdgeInfo,
118
        policy1, policy2 *models.CachedEdgePolicy) {
2,314✔
119

2,314✔
120
        if info == nil {
2,314✔
121
                return
×
122
        }
×
123

124
        // Create the edge entry for both nodes. We always add the channel
125
        // structure to the cache, even if both policies are currently disabled,
126
        // so that later policy updates can find and update the channel entry.
127
        c.mtx.Lock()
2,314✔
128
        c.updateOrAddEdge(info.NodeKey1Bytes, &DirectedChannel{
2,314✔
129
                ChannelID: info.ChannelID,
2,314✔
130
                IsNode1:   true,
2,314✔
131
                OtherNode: info.NodeKey2Bytes,
2,314✔
132
                Capacity:  info.Capacity,
2,314✔
133
        })
2,314✔
134
        c.updateOrAddEdge(info.NodeKey2Bytes, &DirectedChannel{
2,314✔
135
                ChannelID: info.ChannelID,
2,314✔
136
                IsNode1:   false,
2,314✔
137
                OtherNode: info.NodeKey1Bytes,
2,314✔
138
                Capacity:  info.Capacity,
2,314✔
139
        })
2,314✔
140
        c.mtx.Unlock()
2,314✔
141

2,314✔
142
        // Skip adding policies if both are disabled, as the channel is
2,314✔
143
        // currently unusable for routing. However, we still add the channel
2,314✔
144
        // structure above so that policy updates can later enable it.
2,314✔
145
        if policy1 != nil && policy1.IsDisabled &&
2,314✔
146
                policy2 != nil && policy2.IsDisabled {
2,319✔
147

5✔
148
                log.Debugf("Skipping policies for channel %v: both "+
5✔
149
                        "policies are disabled (channel structure still "+
5✔
150
                        "cached for future updates)", info.ChannelID)
5✔
151

5✔
152
                return
5✔
153
        }
5✔
154

155
        // The policy's node is always the to_node. So if policy 1 has to_node
156
        // of node 2 then we have the policy 1 as seen from node 1.
157
        if policy1 != nil {
3,014✔
158
                fromNode, toNode := info.NodeKey1Bytes, info.NodeKey2Bytes
701✔
159
                if !policy1.IsNode1 {
702✔
UNCOV
160
                        fromNode, toNode = toNode, fromNode
1✔
UNCOV
161
                }
1✔
162
                c.UpdatePolicy(policy1, fromNode, toNode)
701✔
163
        }
164
        if policy2 != nil {
3,014✔
165
                fromNode, toNode := info.NodeKey2Bytes, info.NodeKey1Bytes
701✔
166
                if policy2.IsNode1 {
702✔
UNCOV
167
                        fromNode, toNode = toNode, fromNode
1✔
UNCOV
168
                }
1✔
169
                c.UpdatePolicy(policy2, fromNode, toNode)
701✔
170
        }
171
}
172

173
// updateOrAddEdge makes sure the edge information for a node is either updated
174
// if it already exists or is added to that node's list of channels.
175
func (c *GraphCache) updateOrAddEdge(node route.Vertex, edge *DirectedChannel) {
4,624✔
176
        if len(c.nodeChannels[node]) == 0 {
5,692✔
177
                c.nodeChannels[node] = make(map[uint64]*DirectedChannel)
1,068✔
178
        }
1,068✔
179

180
        c.nodeChannels[node][edge.ChannelID] = edge
4,624✔
181
}
182

183
// UpdatePolicy updates a single policy on both the from and to node. The order
184
// of the from and to node is not strictly important. But we assume that a
185
// channel edge was added beforehand so that the directed channel struct already
186
// exists in the cache.
187
func (c *GraphCache) UpdatePolicy(policy *models.CachedEdgePolicy, fromNode,
188
        toNode route.Vertex) {
4,302✔
189

4,302✔
190
        c.mtx.Lock()
4,302✔
191
        defer c.mtx.Unlock()
4,302✔
192

4,302✔
193
        updatePolicy := func(nodeKey route.Vertex) {
12,902✔
194
                if len(c.nodeChannels[nodeKey]) == 0 {
8,600✔
195
                        log.Debugf("Node=%v not found in graph cache", nodeKey)
×
196

×
197
                        return
×
198
                }
×
199

200
                channel, ok := c.nodeChannels[nodeKey][policy.ChannelID]
8,600✔
201
                if !ok {
8,600✔
202
                        log.Debugf("Channel=%v not found in graph cache",
×
203
                                policy.ChannelID)
×
204

×
205
                        return
×
206
                }
×
207

208
                // Edge 1 is defined as the policy for the direction of node1 to
209
                // node2.
210
                switch {
8,600✔
211
                // This is node 1, and it is edge 1, so this is the outgoing
212
                // policy for node 1.
213
                case channel.IsNode1 && policy.IsNode1:
2,159✔
214
                        channel.OutPolicySet = true
2,159✔
215
                        policy.InboundFee.WhenSome(func(fee lnwire.Fee) {
2,325✔
216
                                channel.InboundFee = fee
166✔
217
                        })
166✔
218

219
                // This is node 2, and it is edge 2, so this is the outgoing
220
                // policy for node 2.
221
                case !channel.IsNode1 && !policy.IsNode1:
2,147✔
222
                        channel.OutPolicySet = true
2,147✔
223
                        policy.InboundFee.WhenSome(func(fee lnwire.Fee) {
2,312✔
224
                                channel.InboundFee = fee
165✔
225
                        })
165✔
226

227
                // The other two cases left mean it's the inbound policy for the
228
                // node.
229
                default:
4,302✔
230
                        channel.InPolicy = policy
4,302✔
231
                }
232
        }
233

234
        updatePolicy(fromNode)
4,302✔
235
        updatePolicy(toNode)
4,302✔
236
}
237

238
// RemoveNode completely removes a node and all its channels (including the
239
// peer's side).
240
func (c *GraphCache) RemoveNode(node route.Vertex) {
69✔
241
        c.mtx.Lock()
69✔
242
        defer c.mtx.Unlock()
69✔
243

69✔
244
        delete(c.nodeFeatures, node)
69✔
245

69✔
246
        // First remove all channels from the other nodes' lists.
69✔
247
        for _, channel := range c.nodeChannels[node] {
70✔
UNCOV
248
                c.removeChannelIfFound(channel.OtherNode, channel.ChannelID)
1✔
UNCOV
249
        }
1✔
250

251
        // Then remove our whole node completely.
252
        delete(c.nodeChannels, node)
69✔
253
}
254

255
// RemoveChannel removes a single channel between two nodes.
256
func (c *GraphCache) RemoveChannel(node1, node2 route.Vertex, chanID uint64) {
268✔
257
        c.mtx.Lock()
268✔
258
        defer c.mtx.Unlock()
268✔
259

268✔
260
        // Remove that one channel from both sides.
268✔
261
        c.removeChannelIfFound(node1, chanID)
268✔
262
        c.removeChannelIfFound(node2, chanID)
268✔
263
}
268✔
264

265
// removeChannelIfFound removes a single channel from one side.
266
func (c *GraphCache) removeChannelIfFound(node route.Vertex, chanID uint64) {
533✔
267
        if len(c.nodeChannels[node]) == 0 {
711✔
UNCOV
268
                return
178✔
UNCOV
269
        }
178✔
270

271
        delete(c.nodeChannels[node], chanID)
355✔
272
}
273

274
// getChannels returns a copy of the passed node's channels or nil if there
275
// isn't any.
276
func (c *GraphCache) getChannels(node route.Vertex) []*DirectedChannel {
553✔
277
        c.mtx.RLock()
553✔
278
        defer c.mtx.RUnlock()
553✔
279

553✔
280
        channels, ok := c.nodeChannels[node]
553✔
281
        if !ok {
564✔
282
                return nil
11✔
283
        }
11✔
284

285
        features, ok := c.nodeFeatures[node]
546✔
286
        if !ok {
705✔
287
                // If the features were set to nil explicitly, that's fine here.
159✔
288
                // The router will overwrite the features of the destination
159✔
289
                // node with those found in the invoice if necessary. But if we
159✔
290
                // didn't yet get a node announcement we want to mimic the
159✔
291
                // behavior of the old DB based code that would always set an
159✔
292
                // empty feature vector instead of leaving it nil.
159✔
293
                features = lnwire.EmptyFeatureVector()
159✔
294
        }
159✔
295

296
        toNodeCallback := func() route.Vertex {
998✔
297
                return node
452✔
298
        }
452✔
299

300
        i := 0
546✔
301
        channelsCopy := make([]*DirectedChannel, len(channels))
546✔
302
        for _, channel := range channels {
2,144✔
303
                // We need to copy the channel and policy to avoid it being
1,598✔
304
                // updated in the cache if the path finding algorithm sets
1,598✔
305
                // fields on it (currently only the ToNodeFeatures of the
1,598✔
306
                // policy).
1,598✔
307
                channelCopy := channel.DeepCopy()
1,598✔
308
                if channelCopy.InPolicy != nil {
3,169✔
309
                        channelCopy.InPolicy.ToNodePubKey = toNodeCallback
1,571✔
310
                        channelCopy.InPolicy.ToNodeFeatures = features
1,571✔
311
                }
1,571✔
312

313
                channelsCopy[i] = channelCopy
1,598✔
314
                i++
1,598✔
315
        }
316

317
        return channelsCopy
546✔
318
}
319

320
// ForEachChannel invokes the given callback for each channel of the given node.
321
func (c *GraphCache) ForEachChannel(node route.Vertex,
322
        cb func(channel *DirectedChannel) error) error {
553✔
323

553✔
324
        // Obtain a copy of the node's channels. We need do this in order to
553✔
325
        // avoid deadlocks caused by interaction with the graph cache, channel
553✔
326
        // state and the graph database from multiple goroutines. This snapshot
553✔
327
        // is only used for path finding where being stale is acceptable since
553✔
328
        // the real world graph and our representation may always become
553✔
329
        // slightly out of sync for a short time and the actual channel state
553✔
330
        // is stored separately.
553✔
331
        channels := c.getChannels(node)
553✔
332
        for _, channel := range channels {
2,134✔
333
                if err := cb(channel); err != nil {
1,596✔
334
                        return err
15✔
335
                }
15✔
336
        }
337

338
        return nil
542✔
339
}
340

341
// ForEachNode iterates over the adjacency list of the graph, executing the
342
// call back for each node and the set of channels that emanate from the given
343
// node.
344
//
345
// NOTE: This method should be considered _read only_, the channels or nodes
346
// passed in MUST NOT be modified.
347
func (c *GraphCache) ForEachNode(cb func(node route.Vertex,
UNCOV
348
        channels map[uint64]*DirectedChannel) error) error {
123✔
UNCOV
349

123✔
UNCOV
350
        c.mtx.RLock()
123✔
UNCOV
351
        defer c.mtx.RUnlock()
123✔
UNCOV
352

123✔
UNCOV
353
        for node, channels := range c.nodeChannels {
1,390✔
UNCOV
354
                // We don't make a copy here since this is a read-only RPC
1,267✔
UNCOV
355
                // call. We also don't need the node features either for this
1,267✔
UNCOV
356
                // call.
1,267✔
UNCOV
357
                if err := cb(node, channels); err != nil {
1,267✔
358
                        return err
×
359
                }
×
360
        }
361

UNCOV
362
        return nil
123✔
363
}
364

365
// GetFeatures returns the features of the node with the given ID. If no
366
// features are known for the node, an empty feature vector is returned.
367
func (c *GraphCache) GetFeatures(node route.Vertex) *lnwire.FeatureVector {
474✔
368
        c.mtx.RLock()
474✔
369
        defer c.mtx.RUnlock()
474✔
370

474✔
371
        features, ok := c.nodeFeatures[node]
474✔
372
        if !ok || features == nil {
558✔
373
                // The router expects the features to never be nil, so we return
84✔
374
                // an empty feature set instead.
84✔
375
                return lnwire.EmptyFeatureVector()
84✔
376
        }
84✔
377

378
        return features
394✔
379
}
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

© 2026 Coveralls, Inc