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

lightningnetwork / lnd / 15951470896

29 Jun 2025 04:23AM UTC coverage: 67.594% (-0.01%) from 67.606%
15951470896

Pull #9751

github

web-flow
Merge 599d9b051 into 6290edf14
Pull Request #9751: multi: update Go to 1.23.10 and update some packages

135088 of 199851 relevant lines covered (67.59%)

21909.44 hits per line

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

96.79
/autopilot/simple_graph.go
1
package autopilot
2

3
import "context"
4

5
// diameterCutoff is used to discard nodes in the diameter calculation.
6
// It is the multiplier for the eccentricity of the highest-degree node,
7
// serving as a cutoff to discard all nodes with a smaller hop distance. This
8
// number should not be set close to 1 and is a tradeoff for computation cost,
9
// where 0 is maximally costly.
10
const diameterCutoff = 0.75
11

12
// SimpleGraph stores a simplified adj graph of a channel graph to speed
13
// up graph processing by eliminating all unnecessary hashing and map access.
14
type SimpleGraph struct {
15
        // Nodes is a map from node index to NodeID.
16
        Nodes []NodeID
17

18
        // Adj stores nodes and neighbors in an adjacency list.
19
        Adj [][]int
20
}
21

22
// NewSimpleGraph creates a simplified graph from the current channel graph.
23
// Returns an error if the channel graph iteration fails due to underlying
24
// failure.
25
func NewSimpleGraph(ctx context.Context, g ChannelGraph) (*SimpleGraph, error) {
210✔
26
        nodes := make(map[NodeID]int)
210✔
27
        adj := make(map[int][]int)
210✔
28
        nextIndex := 0
210✔
29

210✔
30
        // getNodeIndex returns the integer index of the passed node.
210✔
31
        // The returned index is then used to create a simplified adjacency list
210✔
32
        // where each node is identified by its index instead of its pubkey, and
210✔
33
        // also to create a mapping from node index to node pubkey.
210✔
34
        getNodeIndex := func(node Node) int {
7,906✔
35
                key := NodeID(node.PubKey())
7,696✔
36
                nodeIndex, ok := nodes[key]
7,696✔
37

7,696✔
38
                if !ok {
9,568✔
39
                        nodes[key] = nextIndex
1,872✔
40
                        nodeIndex = nextIndex
1,872✔
41
                        nextIndex++
1,872✔
42
                }
1,872✔
43

44
                return nodeIndex
7,696✔
45
        }
46

47
        // Iterate over each node and each channel and update the adj and the
48
        // node index.
49
        err := g.ForEachNode(ctx, func(ctx context.Context, node Node) error {
2,082✔
50
                u := getNodeIndex(node)
1,872✔
51

1,872✔
52
                return node.ForEachChannel(
1,872✔
53
                        ctx, func(_ context.Context,
1,872✔
54
                                edge ChannelEdge) error {
7,696✔
55

5,824✔
56
                                v := getNodeIndex(edge.Peer)
5,824✔
57

5,824✔
58
                                adj[u] = append(adj[u], v)
5,824✔
59

5,824✔
60
                                return nil
5,824✔
61
                        },
5,824✔
62
                )
63
        })
64
        if err != nil {
210✔
65
                return nil, err
×
66
        }
×
67

68
        graph := &SimpleGraph{
210✔
69
                Nodes: make([]NodeID, len(nodes)),
210✔
70
                Adj:   make([][]int, len(nodes)),
210✔
71
        }
210✔
72

210✔
73
        // Fill the adj and the node index to node pubkey mapping.
210✔
74
        for nodeID, nodeIndex := range nodes {
2,082✔
75
                graph.Adj[nodeIndex] = adj[nodeIndex]
1,872✔
76
                graph.Nodes[nodeIndex] = nodeID
1,872✔
77
        }
1,872✔
78

79
        // We prepare to give some debug output about the size of the graph.
80
        totalChannels := 0
210✔
81
        for _, channels := range graph.Adj {
2,082✔
82
                totalChannels += len(channels)
1,872✔
83
        }
1,872✔
84

85
        // The number of channels is double counted, so divide by two.
86
        log.Debugf("Initialized simple graph with %d nodes and %d "+
210✔
87
                "channels", len(graph.Adj), totalChannels/2)
210✔
88
        return graph, nil
210✔
89
}
90

91
// maxVal is a helper function to get the maximal value of all values of a map.
92
func maxVal(mapping map[int]uint32) uint32 {
22✔
93
        maxValue := uint32(0)
22✔
94
        for _, value := range mapping {
212✔
95
                maxValue = max(maxValue, value)
190✔
96
        }
190✔
97
        return maxValue
22✔
98
}
99

100
// degree determines the number of edges for a node in the graph.
101
func (graph *SimpleGraph) degree(node int) int {
9✔
102
        return len(graph.Adj[node])
9✔
103
}
9✔
104

105
// nodeMaxDegree determines the node with the max degree and its degree.
106
func (graph *SimpleGraph) nodeMaxDegree() (int, int) {
1✔
107
        var maxNode, maxDegree int
1✔
108
        for node := range graph.Adj {
10✔
109
                degree := graph.degree(node)
9✔
110
                if degree > maxDegree {
11✔
111
                        maxNode = node
2✔
112
                        maxDegree = degree
2✔
113
                }
2✔
114
        }
115
        return maxNode, maxDegree
1✔
116
}
117

118
// shortestPathLengths performs a breadth-first-search from a node to all other
119
// nodes, returning the lengths of the paths.
120
func (graph *SimpleGraph) shortestPathLengths(node int) map[int]uint32 {
21✔
121
        // level indicates the shell of the search around the root node.
21✔
122
        var level uint32
21✔
123
        graphOrder := len(graph.Adj)
21✔
124

21✔
125
        // nextLevel tracks which nodes should be visited in the next round.
21✔
126
        nextLevel := make([]int, 0, graphOrder)
21✔
127

21✔
128
        // The root node is put as a starting point for the exploration.
21✔
129
        nextLevel = append(nextLevel, node)
21✔
130

21✔
131
        // Seen tracks already visited nodes and tracks how far away they are.
21✔
132
        seen := make(map[int]uint32, graphOrder)
21✔
133

21✔
134
        // Mark the root node as seen.
21✔
135
        seen[node] = level
21✔
136

21✔
137
        // thisLevel contains the nodes that are explored in the round.
21✔
138
        thisLevel := make([]int, 0, graphOrder)
21✔
139

21✔
140
        // Abort if we have an empty graph.
21✔
141
        if len(graph.Adj) == 0 {
21✔
142
                return seen
×
143
        }
×
144

145
        // We discover other nodes in a ring-like structure as long as we don't
146
        // have more nodes to explore.
147
        for len(nextLevel) > 0 {
103✔
148
                level++
82✔
149

82✔
150
                // We swap the queues for efficient memory management.
82✔
151
                thisLevel, nextLevel = nextLevel, thisLevel
82✔
152

82✔
153
                // Visit all neighboring nodes of the level and mark them as
82✔
154
                // seen if they were not discovered before.
82✔
155
                for _, thisNode := range thisLevel {
225✔
156
                        for _, neighbor := range graph.Adj[thisNode] {
609✔
157
                                _, ok := seen[neighbor]
466✔
158
                                if !ok {
634✔
159
                                        nextLevel = append(nextLevel, neighbor)
168✔
160
                                        seen[neighbor] = level
168✔
161
                                }
168✔
162

163
                                // If we have seen all nodes, we return early.
164
                                if len(seen) == graphOrder {
487✔
165
                                        return seen
21✔
166
                                }
21✔
167
                        }
168
                }
169

170
                // Empty the queue to be used in the next level.
171
                thisLevel = thisLevel[:0:cap(thisLevel)]
61✔
172
        }
173

174
        return seen
×
175
}
176

177
// nodeEccentricity calculates the eccentricity (longest shortest path to all
178
// other nodes) of a node.
179
func (graph *SimpleGraph) nodeEccentricity(node int) uint32 {
19✔
180
        pathLengths := graph.shortestPathLengths(node)
19✔
181
        return maxVal(pathLengths)
19✔
182
}
19✔
183

184
// nodeEccentricities calculates the eccentricities for the given nodes.
185
func (graph *SimpleGraph) nodeEccentricities(nodes []int) map[int]uint32 {
3✔
186
        eccentricities := make(map[int]uint32, len(graph.Adj))
3✔
187
        for _, node := range nodes {
22✔
188
                eccentricities[node] = graph.nodeEccentricity(node)
19✔
189
        }
19✔
190
        return eccentricities
3✔
191
}
192

193
// Diameter returns the maximal eccentricity (longest shortest path
194
// between any node pair) in the graph.
195
//
196
// Note: This method is exact but expensive, use DiameterRadialCutoff instead.
197
func (graph *SimpleGraph) Diameter() uint32 {
1✔
198
        nodes := make([]int, len(graph.Adj))
1✔
199
        for a := range nodes {
10✔
200
                nodes[a] = a
9✔
201
        }
9✔
202
        eccentricities := graph.nodeEccentricities(nodes)
1✔
203
        return maxVal(eccentricities)
1✔
204
}
205

206
// DiameterRadialCutoff is a method to efficiently evaluate the diameter of a
207
// graph. The highest-degree node is usually central in the graph. We can
208
// determine its eccentricity (shortest-longest path length to any other node)
209
// and use it as an approximation for the radius of the network. We then
210
// use this radius to compute a cutoff. All the nodes within a distance of the
211
// cutoff are discarded, as they represent the inside of the graph. We then
212
// loop over all outer nodes and determine their eccentricities, from which we
213
// get the diameter.
214
func (graph *SimpleGraph) DiameterRadialCutoff() uint32 {
1✔
215
        // Determine the reference node as the node with the highest degree.
1✔
216
        nodeMaxDegree, _ := graph.nodeMaxDegree()
1✔
217

1✔
218
        distances := graph.shortestPathLengths(nodeMaxDegree)
1✔
219
        eccentricityMaxDegreeNode := maxVal(distances)
1✔
220

1✔
221
        // We use the eccentricity to define a cutoff for the interior of the
1✔
222
        // graph from the reference node.
1✔
223
        cutoff := uint32(float32(eccentricityMaxDegreeNode) * diameterCutoff)
1✔
224
        log.Debugf("Cutoff radius is %d hops (max-degree node's "+
1✔
225
                "eccentricity is %d)", cutoff, eccentricityMaxDegreeNode)
1✔
226

1✔
227
        // Remove the nodes that are close to the reference node.
1✔
228
        var nodes []int
1✔
229
        for node, distance := range distances {
10✔
230
                if distance > cutoff {
10✔
231
                        nodes = append(nodes, node)
1✔
232
                }
1✔
233
        }
234
        log.Debugf("Evaluated nodes: %d, discarded nodes %d",
1✔
235
                len(nodes), len(graph.Adj)-len(nodes))
1✔
236

1✔
237
        // Compute the diameter of the remaining nodes.
1✔
238
        eccentricities := graph.nodeEccentricities(nodes)
1✔
239
        return maxVal(eccentricities)
1✔
240
}
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