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

lightningnetwork / lnd / 15574102646

11 Jun 2025 01:44AM UTC coverage: 68.554% (+9.9%) from 58.637%
15574102646

Pull #9652

github

web-flow
Merge eb863e46a into 92a5d35cf
Pull Request #9652: lnwallet/chancloser: fix flake in TestRbfCloseClosingNegotiationLocal

11 of 12 new or added lines in 1 file covered. (91.67%)

7276 existing lines in 84 files now uncovered.

134508 of 196208 relevant lines covered (68.55%)

44569.29 hits per line

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

86.23
/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,166✔
46
        channelCopy := *c
3,166✔
47

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

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

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

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

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

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

1,442✔
110
        c.nodeFeatures[node] = features
1,442✔
111
}
1,442✔
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,403✔
119

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

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

6✔
127
                return
6✔
128
        }
6✔
129

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

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

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

173
        c.nodeChannels[node][edge.ChannelID] = edge
6,800✔
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.
180
func (c *GraphCache) UpdatePolicy(policy *models.ChannelEdgePolicy, fromNode,
181
        toNode route.Vertex, edge1 bool) {
6,151✔
182

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

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

×
190
                        return
×
191
                }
×
192

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

×
UNCOV
198
                        return
×
199
                }
×
200

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

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

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

227
        updatePolicy(fromNode)
6,151✔
228
        updatePolicy(toNode)
6,151✔
229
}
230

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

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

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

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

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

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

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

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

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

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

×
277
                return
×
278
        }
×
279

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

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

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

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

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

317
        toNodeCallback := func() route.Vertex {
1,974✔
318
                return node
902✔
319
        }
902✔
320

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

334
                channelsCopy[i] = channelCopy
3,158✔
335
                i++
3,158✔
336
        }
337

338
        return channelsCopy
1,072✔
339
}
340

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

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

359
        return nil
1,070✔
360
}
361

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

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

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

383
        return nil
4✔
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 {
944✔
389
        c.mtx.RLock()
944✔
390
        defer c.mtx.RUnlock()
944✔
391

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

399
        return features
922✔
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