-
Notifications
You must be signed in to change notification settings - Fork 40
/
dot_graph.go
396 lines (331 loc) · 11.4 KB
/
dot_graph.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
package seth
import (
//we use it only to generate hash that's used to identify a node in graph, so we don't care about this function being weak
//nolint
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/awalterschulze/gographviz"
)
func findShortestPath(calls []*DecodedCall) []string {
callMap := make(map[string]*DecodedCall)
for _, call := range calls {
callMap[call.CommonData.Signature] = call
}
var root *DecodedCall
for _, call := range calls {
if call.CommonData.ParentSignature == "" {
root = call
break
}
}
if root == nil {
return nil // No root found
}
var end *DecodedCall
for i := len(calls) - 1; i >= 0; i-- {
if calls[i].CommonData.Error != "" {
end = calls[i]
break
}
}
if end == nil {
end = calls[len(calls)-1]
}
type node struct {
call *DecodedCall
path []string
}
queue := []node{{call: root, path: []string{root.CommonData.Signature}}}
visited := make(map[string]bool)
for len(queue) > 0 {
currentNode := queue[0]
queue = queue[1:]
currentCall := currentNode.call
currentPath := currentNode.path
if currentCall.CommonData.Signature == end.CommonData.Signature {
return currentPath
}
visited[currentCall.CommonData.Signature] = true
for _, call := range calls {
if call.CommonData.ParentSignature == currentCall.CommonData.Signature && !visited[call.CommonData.Signature] {
newPath := append([]string{}, currentPath...)
newPath = append(newPath, call.CommonData.Signature)
queue = append(queue, node{call: call, path: newPath})
}
}
}
return nil // No path found
}
var defaultTruncateTo = 20
func (t *Tracer) generateDotGraph(txHash string, calls []*DecodedCall, revertErr error) error {
if !t.Cfg.hasOutput(TraceOutput_DOT) {
return nil
}
shortestPath := findShortestPath(calls)
callHashToID := make(map[string]int)
nextID := 1
g := gographviz.NewGraph()
if err := g.SetName("G"); err != nil {
return fmt.Errorf("failed to set graph name: %w", err)
}
if err := g.SetDir(true); err != nil {
return fmt.Errorf("failed to set graph direction: %w", err)
}
nodesAtLevel := make(map[int][]string)
revertedCallIdx := -1
if len(calls) > 0 {
for i, dc := range calls {
if dc.Error != "" {
revertedCallIdx = i
}
}
}
if err := g.AddNode("G", "start", map[string]string{"label": "\"Start\n\"", "shape": "circle", "style": "filled", "fillcolor": "darkseagreen3", "color": "darkslategray", "fontcolor": "darkslategray"}); err != nil {
return fmt.Errorf("failed to add start node: %w", err)
}
for idx, call := range calls {
hash := hashCall(call)
var callID int
_, exists := callHashToID[hash]
if exists {
// This could be also valid if the same call is present twice in the trace, but in typical scenarios that should not happen
L.Warn().Msg("The same call was present twice. This should not happen and might indicate a bug in the tracer. Check debug log for details and contact the Test Tooling team")
marshalled, err := json.Marshal(call)
if err == nil {
L.Debug().Msgf("Call: %v", marshalled)
}
continue
}
callID = nextID
nextID++
callHashToID[hash] = callID
basicNodeID := "node" + strconv.Itoa(callID) + "_basic"
extraNodeID := "node" + strconv.Itoa(callID) + "_extra"
var from, to string
if call.From != "" && call.From != UNKNOWN {
from = call.From
} else {
from = call.FromAddress
}
if call.To != "" && call.To != UNKNOWN {
to = call.To
} else {
to = call.ToAddress
}
basicLabel := fmt.Sprintf("\"%s -> %s\n %s\"", from, to, call.CommonData.Method)
extraLabel := fmt.Sprintf("\"Inputs: %s\nOutputs: %s\"", formatMapForLabel(call.CommonData.Input, defaultTruncateTo), formatMapForLabel(call.CommonData.Output, defaultTruncateTo))
isMajorNode := false
for _, path := range shortestPath {
if path == call.Signature {
isMajorNode = true
break
}
}
style := "filled"
nodeColor := "darkslategray"
fontSize := "14.0"
if !isMajorNode {
style = "dashed"
fontSize = "9.0"
nodeColor = "lightslategray"
}
var subgraphAttrs map[string]string
subgraphAttrs = map[string]string{"color": "darkslategray"}
if call.Error != "" {
subgraphAttrs = map[string]string{"color": "lightcoral"}
nodeColor = "lightcoral"
}
if err := g.AddNode("G", basicNodeID, map[string]string{"label": basicLabel, "shape": "box", "style": style, "fillcolor": "ivory", "color": nodeColor, "fontcolor": "darkslategray", "fontsize": fontSize, "tooltip": formatTooltip(call)}); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
if err := g.AddNode("G", extraNodeID, map[string]string{"label": extraLabel, "shape": "box", "style": style, "fillcolor": "gainsboro", "color": nodeColor, "fontcolor": "darkslategray", "fontsize": fontSize}); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
subGraphName := "cluster_" + strconv.Itoa(callID)
if err := g.AddSubGraph("G", subGraphName, subgraphAttrs); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
if err := g.AddNode(subGraphName, basicNodeID, nil); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
if err := g.AddNode(subGraphName, extraNodeID, map[string]string{"rank": "same"}); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
if idx == 0 {
if err := g.AddEdge("start", basicNodeID, true, nil); err != nil {
return fmt.Errorf("failed to add edge: %w", err)
}
}
if call.CommonData.ParentSignature != "" {
for _, parentCall := range calls {
if parentCall.CommonData.Signature == call.CommonData.ParentSignature {
parentHash := hashCall(parentCall)
parentID := callHashToID[parentHash]
parentBasicNodeID := "node" + strconv.Itoa(parentID) + "_basic"
attrs := map[string]string{"fontsize": fontSize, "label": fmt.Sprintf(" \"(%s)\"", ordinalNumber(idx))}
if call.Error != "" {
attrs["color"] = "lightcoral"
attrs["fontcolor"] = "lightcoral"
} else {
attrs["color"] = "darkslategray"
attrs["fontcolor"] = "darkslategray"
}
if err := g.AddEdge(parentBasicNodeID, basicNodeID, true, attrs); err != nil {
return fmt.Errorf("failed to add edge: %w", err)
}
break
}
}
}
}
// Create dummy nodes to adjust vertical positions
for level, nodes := range nodesAtLevel {
for i, node := range nodes {
if i > 0 {
dummyNode := fmt.Sprintf("dummy_%d_%d", level, i)
if err := g.AddNode("G", dummyNode, map[string]string{"label": "\"\"", "shape": "none", "height": "0.1", "width": "0.1"}); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
if err := g.AddEdge(nodes[i-1], dummyNode, true, map[string]string{"style": "invis"}); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
if err := g.AddEdge(dummyNode, node, true, map[string]string{"style": "invis"}); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
}
}
}
if revertErr != nil {
revertNode := fmt.Sprintf("revert_node_%d", nextID-1)
if err := g.AddNode("G", revertNode, map[string]string{"label": fmt.Sprintf("\"%s\"", revertErr.Error()), "shape": "rectangle", "style": "filled", "color": "lightcoral", "fillcolor": "lightcoral", "fontcolor": "darkslategray"}); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
hash := hashCall(calls[revertedCallIdx])
revertParentNodeId, ok := callHashToID[hash]
if !ok {
return fmt.Errorf("failed to find parent node for revert node. This should never happen and likely indicates a bug in code")
}
parentBasicNodeID := "node" + strconv.Itoa(revertParentNodeId) + "_basic"
if err := g.AddEdge(revertNode, parentBasicNodeID, true, map[string]string{"style": "filled", "fillcolor": "lightcoral", "color": "lightcoral", "fontcolor": "darkslategray"}); err != nil {
return fmt.Errorf("failed to add node: %w", err)
}
} else {
if err := g.AddNode("G", "end", map[string]string{"label": "\"End\n\"", "shape": "circle", "style": "filled", "fillcolor": "darkseagreen3", "color": "darkslategray", "fontcolor": "darkslategray"}); err != nil {
return fmt.Errorf("failed to add end node: %w", err)
}
hash := hashCall(calls[len(calls)-1])
lastNodeId, ok := callHashToID[hash]
if !ok {
return fmt.Errorf("failed to find parent node for revert node. This should never happen and likely indicates a bug in code")
}
parentBasicNodeID := "node" + strconv.Itoa(lastNodeId) + "_basic"
if err := g.AddEdge(parentBasicNodeID, "end", true, nil); err != nil {
return fmt.Errorf("failed to add edge: %w", err)
}
}
dirPath := filepath.Join(t.Cfg.ArtifactsDir, "dot_graphs")
err := os.MkdirAll(dirPath, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
filePath := filepath.Join(dirPath, fmt.Sprintf("%s.dot", txHash))
f, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("error creating file: %v", err)
}
defer func() { _ = f.Close() }()
if _, err := f.WriteString(g.String()); err != nil {
return fmt.Errorf("error writing to file: %v", err)
}
L.Debug().Msgf("DOT graph saved to %s", filePath)
L.Debug().Msgf("To view run: xdot %s", filePath)
return nil
}
func formatTooltip(call *DecodedCall) string {
basicTooltip := fmt.Sprintf("\"BASIC\nFrom: %s\nTo: %s\nType: %s\nGas Used/Limit: %s\nValue: %d\n\nINPUTS%s\n\nOUTPUTS%s\n\nEVENTS%s\n\"",
call.FromAddress, call.ToAddress, call.CommonData.CallType, fmt.Sprintf("%d/%d", call.GasUsed, call.GasLimit), call.Value, formatMapForTooltip(call.CommonData.Input), formatMapForTooltip(call.CommonData.Output), formatEvent(call.Events))
if call.Comment == "" {
return basicTooltip
}
return fmt.Sprintf("%s\nCOMMENT\n%s", basicTooltip, call.Comment)
}
func formatEvent(events []DecodedCommonLog) string {
if len(events) == 0 {
return "\n{}"
}
parts := make([]string, 0, len(events))
for _, event := range events {
parts = append(parts, fmt.Sprintf("\n%s %s", event.Signature, formatMapForTooltip(event.EventData)))
}
return strings.Join(parts, "\n")
}
func prepareMapParts(m map[string]interface{}, truncateTo int) []string {
if len(m) == 0 {
return []string{}
}
parts := make([]string, 0, len(m))
for k, v := range m {
value := fmt.Sprint(v)
if truncateTo != -1 && len(value) > truncateTo {
value = value[:truncateTo] + "..."
}
parts = append(parts, fmt.Sprintf("%s: %v", k, value))
}
return parts
}
func formatMapForTooltip(m map[string]interface{}) string {
if len(m) == 0 {
return "\n{}"
}
parts := prepareMapParts(m, -1)
return "\n" + strings.Join(parts, "\n")
}
func formatMapForLabel(m map[string]interface{}, truncateTo int) string {
if len(m) == 0 {
return "{}"
}
parts := prepareMapParts(m, truncateTo)
return "\n" + strings.Join(parts, "\\l") + "\\l"
}
func hashCall(call *DecodedCall) string {
//we use it only to generate hash that's used to identify a node in graph, so we don't care about this function being weak
//nolint
h := sha1.New()
h.Write([]byte(fmt.Sprintf("%v", call)))
return hex.EncodeToString(h.Sum(nil))
}
func ordinalNumber(n int) string {
if n <= 0 {
return strconv.Itoa(n)
}
var suffix string
switch n % 10 {
case 1:
if n%100 == 11 {
suffix = "th"
} else {
suffix = "st"
}
case 2:
if n%100 == 12 {
suffix = "th"
} else {
suffix = "nd"
}
case 3:
if n%100 == 13 {
suffix = "th"
} else {
suffix = "rd"
}
default:
suffix = "th"
}
return strconv.Itoa(n) + suffix
}