You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.8 KiB

6 years ago
  1. package merkletree
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "github.com/fatih/color"
  6. )
  7. func (mt *MerkleTree) printLevel(parent Hash, iLevel int, maxLevel int) {
  8. for i := 0; i < iLevel; i++ {
  9. fmt.Print(" ")
  10. }
  11. fmt.Print("level ")
  12. fmt.Print(iLevel)
  13. fmt.Print(" - ")
  14. fmt.Print("'" + parent.Hex() + "' = ")
  15. nodeType, _, nodeBytes, err := mt.Get(parent)
  16. if err != nil {
  17. color.Red(err.Error())
  18. }
  19. var node treeNode
  20. if nodeType == byte(normalNodeType) {
  21. node = parseNodeBytes(nodeBytes)
  22. color.Blue("'" + node.ChildL.Hex() + "' - '" + node.ChildR.Hex() + "'")
  23. } else if nodeType == byte(valueNodeType) {
  24. color.Green("value")
  25. } else if nodeType == byte(finalNodeType) { //typ==FINAL_NODE
  26. fmt.Print("[FinalTree]:")
  27. color.Cyan("final tree node: " + HashBytes(nodeBytes).Hex())
  28. _, _, leafNodeBytes, err := mt.Get(HashBytes(nodeBytes))
  29. if err != nil {
  30. color.Red(err.Error())
  31. }
  32. for i := 0; i < iLevel; i++ {
  33. fmt.Print(" ")
  34. }
  35. color.Cyan(" leaf value: 0x" + hex.EncodeToString(leafNodeBytes))
  36. } else {
  37. //EMPTY_NODE
  38. fmt.Print("[EmptyBranch]:")
  39. fmt.Println(EmptyNodeValue.Bytes())
  40. }
  41. iLevel++
  42. if len(node.ChildR) > 0 && iLevel < maxLevel && nodeType != byte(EmptyNodeType) && nodeType != byte(finalNodeType) {
  43. mt.printLevel(node.ChildL, iLevel, maxLevel)
  44. mt.printLevel(node.ChildR, iLevel, maxLevel)
  45. }
  46. }
  47. // PrintFullMT prints the tree in the terminal, all the levels with all the nodes
  48. func (mt *MerkleTree) PrintFullMT() {
  49. mt.printLevel(mt.root, 0, mt.numLevels-1)
  50. fmt.Print("root: ")
  51. color.Yellow(mt.Root().Hex())
  52. }
  53. // PrintLevelsMT prints the tree in the terminal until a specified depth
  54. func (mt *MerkleTree) PrintLevelsMT(maxLevel int) {
  55. mt.printLevel(mt.root, 0, mt.numLevels-1-maxLevel)
  56. fmt.Print("root: ")
  57. color.Yellow(mt.Root().Hex())
  58. }