forked from Nexell-AI-Network/nexelliad
-
Notifications
You must be signed in to change notification settings - Fork 2
/
test_consensus_render_to_dot.go
executable file
·83 lines (66 loc) · 2.08 KB
/
test_consensus_render_to_dot.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
package consensus
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os/exec"
"strings"
"github.com/Nautilus-Network/nautiliad/domain/consensus/model"
)
// RenderDAGToDot is a helper function for debugging tests.
// It requires graphviz installed.
func (tc *testConsensus) RenderDAGToDot(filename string) error {
dotScript, _ := tc.convertToDot()
return renderDotScript(dotScript, filename)
}
func (tc *testConsensus) convertToDot() (string, error) {
var dotScriptBuilder strings.Builder
dotScriptBuilder.WriteString("digraph {\n\trankdir = TB; \n")
edges := []string{}
blocksIterator, err := tc.blockStore.AllBlockHashesIterator(tc.databaseContext)
if err != nil {
return "", err
}
defer blocksIterator.Close()
stagingArea := model.NewStagingArea()
for ok := blocksIterator.First(); ok; ok = blocksIterator.Next() {
hash, err := blocksIterator.Get()
if err != nil {
return "", err
}
dotScriptBuilder.WriteString(fmt.Sprintf("\t\"%s\";\n", hash))
parents, err := tc.dagTopologyManagers[0].Parents(stagingArea, hash)
if err != nil {
return "", err
}
for _, parentHash := range parents {
edges = append(edges, fmt.Sprintf("\t\"%s\" -> \"%s\";", hash, parentHash))
}
}
dotScriptBuilder.WriteString("\n")
dotScriptBuilder.WriteString(strings.Join(edges, "\n"))
dotScriptBuilder.WriteString("\n}")
return dotScriptBuilder.String(), nil
}
func renderDotScript(dotScript string, filename string) error {
command := exec.Command("dot", "-Tsvg")
stdin, err := command.StdinPipe()
if err != nil {
return fmt.Errorf("Error creating stdin pipe: %s", err)
}
spawn("renderDotScript", func() {
defer stdin.Close()
_, err = io.WriteString(stdin, dotScript)
if err != nil {
panic(fmt.Errorf("Error writing dotScript into stdin pipe: %s", err))
}
})
var stderr bytes.Buffer
command.Stderr = &stderr
svg, err := command.Output()
if err != nil {
return fmt.Errorf("Error getting output of dot: %s\nstderr:\n%s", err, stderr.String())
}
return ioutil.WriteFile(filename, svg, 0600)
}