From 9bc9f7d54a13ab1a822cab5a34d4d2d19787b736 Mon Sep 17 00:00:00 2001 From: Matt Kocubinski Date: Tue, 18 Jun 2024 13:06:17 -0500 Subject: [PATCH] simple dot graph gen --- go.mod | 1 + go.sum | 2 ++ tree.go | 31 +++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+) diff --git a/go.mod b/go.mod index 9ab51838..06bca749 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/ferranbt/fastssz go 1.18 require ( + github.com/emicklei/dot v1.6.2 github.com/golang/snappy v0.0.3 github.com/minio/sha256-simd v1.0.0 github.com/mitchellh/mapstructure v1.3.2 diff --git a/go.sum b/go.sum index 3411b81d..241ece30 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,8 @@ github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emicklei/dot v1.6.2 h1:08GN+DD79cy/tzN6uLCT84+2Wk9u+wvqP+Hkx/dIR8A= +github.com/emicklei/dot v1.6.2/go.mod h1:DeV7GvQtIw4h2u73RKBkkFdvVAz0D9fzeJrgPW6gy/s= github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA= github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= diff --git a/tree.go b/tree.go index e60a0d93..9fbfcab8 100644 --- a/tree.go +++ b/tree.go @@ -5,7 +5,10 @@ import ( "encoding/hex" "errors" "fmt" + "io" "math" + + "github.com/emicklei/dot" ) // Proof represents a merkle proof against a general index. @@ -86,6 +89,34 @@ type Node struct { value []byte } +func (n *Node) Draw(w io.Writer) { + g := dot.NewGraph(dot.Directed) + n.draw(1, g) + g.Write(w) +} + +func (n *Node) draw(levelOrder int, g *dot.Graph) dot.Node { + var h string + if n.left != nil || n.right != nil { + h = hex.EncodeToString(n.Hash()) + } + if n.value != nil { + h = hex.EncodeToString(n.value) + } + dn := g.Node(fmt.Sprintf("n%d", levelOrder)). + Label(fmt.Sprintf("%d\n%s..%s", levelOrder, h[:3], h[len(h)-3:])) + + if n.left != nil { + ln := n.left.draw(2*levelOrder, g) + g.Edge(dn, ln).Label("0") + } + if n.right != nil { + rn := n.right.draw(2*levelOrder+1, g) + g.Edge(dn, rn).Label("1") + } + return dn +} + func (n *Node) Show(maxDepth int) { fmt.Printf("--- Show node ---\n") n.show(0, maxDepth)