/** * GraphViz visualization for IAVL trees. * * Generates DOT format graphs for visualizing tree structure, useful for * debugging and understanding tree operations. * * Based on Go IAVL tree_dotgraph.go */ import { attribute, Digraph, Edge, Node as GraphvizNode, toDot, } from "ts-graphviz"; import type { ImmutableTree, } from "../immutable-tree.js"; import type { Node as IavlNode, } from "../node.js"; import type { ProofInnerNode, } from "../proof/proof-inner-node.js"; import { bytesToHex, } from "../utils/bytes.js"; /** * Options for customizing graph visualization. */ export interface GraphOptions { /** * Maximum length for displaying keys and values */ maxLabelLength?: number /** * Whether to show node versions */ showVersions?: boolean /** * Whether to show node heights */ showHeights?: boolean /** * Whether to show hash values */ showHashes?: boolean /** * Path to highlight in the visualization */ highlightPath?: ProofInnerNode[] /** * Whether to show node keys */ showNodeKeys?: boolean } /** * Default options for graph visualization. */ const DEFAULT_OPTIONS: Required = { maxLabelLength: 16, showVersions: true, showHeights: true, showHashes: true, highlightPath: [], showNodeKeys: false, }; /** * Creates a GraphViz DOT representation of an IAVL tree. * * Based on Go IAVL WriteDotGraphv2 * * @param tree - The tree to visualize * @param options - Visualization options * @returns DOT format string */ export async function writeDOTGraph( tree: ImmutableTree, options: GraphOptions = { }, ): Promise { const opts = { ...DEFAULT_OPTIONS, ...options, }; const graph = new Digraph("IAVL_Tree", { [attribute.rankdir]: "TB", // Top to bottom layout [attribute.nodesep]: 0.5, // Node separation [attribute.ranksep]: 1.0, // Rank separation }); // Track nodes in highlight path const highlightNodes = new Set(); if (opts.highlightPath.length > 0) { for (const pathNode of opts.highlightPath) { if (pathNode.left) { highlightNodes.add(bytesToHex(pathNode.left)); } if (pathNode.right) { highlightNodes.add(bytesToHex(pathNode.right)); } } } // Helper to create node label function createLabel(node: IavlNode): string { const parts: string[] = []; // Key const keyStr = truncateString( node.key && node.key.length > 0 ? bytesToHex(node.key) : "(empty)", opts.maxLabelLength, ); parts.push(`Key: ${keyStr}`); // Value for leaf nodes if (node.isLeaf() && node.value) { const valueStr = truncateString( bytesToHex(node.value), opts.maxLabelLength, ); parts.push(`Val: ${valueStr}`); } // Height for branch nodes if (!node.isLeaf() && opts.showHeights) { parts.push(`H: ${node.subtreeHeight}`); } // Version if (opts.showVersions) { const version = node.nodeKey?.version || 0n; parts.push(`V: ${version}`); } // Hash if (opts.showHashes && node.hash) { const hashStr = truncateString(bytesToHex(node.hash), 8); parts.push(`#: ${hashStr}`); } // Node key if (opts.showNodeKeys && node.nodeKey) { parts.push(`NK: ${node.nodeKey.version}-${node.nodeKey.nonce}`); } return parts.join("\\n"); } // Traverse tree and create graph async function traverse( node: IavlNode | null, parent?: GraphvizNode, edgeLabel?: string, ): Promise { if (!node) return undefined; // Create unique node ID based on hash const nodeId = node.hash ? bytesToHex(node.hash) : `node_${Math.random()}`; const label = createLabel(node); // Determine node attributes const attrs: Record = { [attribute.label]: label, [attribute.shape]: node.isLeaf() ? "ellipse" : "box", }; // Style leaf nodes if (node.isLeaf()) { attrs[attribute.style] = "filled"; attrs[attribute.fillcolor] = "lightgray"; } // Highlight nodes in path if (node.hash && highlightNodes.has(bytesToHex(node.hash))) { attrs[attribute.style] = "filled"; attrs[attribute.fillcolor] = "lightblue"; attrs[attribute.penwidth] = "2"; } // Create graph node const graphNode = new GraphvizNode(nodeId, attrs); graph.addNode(graphNode); // Add edge from parent if exists if (parent && edgeLabel) { const edge = new Edge([parent, graphNode], { [attribute.label]: edgeLabel, }); graph.addEdge(edge); } // Recursively traverse children if (!node.isLeaf()) { // Load left child (may be cached or need to load from storage) const leftChild = await node.getLeftNode(tree.ndb); if (leftChild) { await traverse(leftChild, graphNode, "L"); } // Load right child (may be cached or need to load from storage) const rightChild = await node.getRightNode(tree.ndb); if (rightChild) { await traverse(rightChild, graphNode, "R"); } } return graphNode; } // Start traversal from root const root = tree.getRoot(); if (root) { await traverse(root); } return toDot(graph); } /** * Writes a DOT graph to a file. * * Usage: * ```typescript * await writeDOTGraphToFile("tree.dot", tree); * // Then visualize with: dot tree.dot -Tpng -o tree.png * ``` * * Based on Go IAVL WriteDOTGraphToFile * * @param filename - Output file path * @param tree - Tree to visualize * @param options - Visualization options */ export async function writeDOTGraphToFile( filename: string, tree: ImmutableTree, options: GraphOptions = { }, ): Promise { const dot = await writeDOTGraph(tree, options); // Use dynamic import for Node.js fs module const { promises: fs, } = await import("fs"); await fs.writeFile(filename, dot, "utf8"); } /** * Generates a simplified graph focused on tree structure. * Shows only keys and basic structure without additional metadata. * * @param tree - Tree to visualize * @returns Simplified DOT format string */ export async function writeSimpleDOTGraph(tree: ImmutableTree): Promise { return writeDOTGraph(tree, { showVersions: false, showHeights: false, showHashes: false, showNodeKeys: false, maxLabelLength: 32, }); } /** * Generates a detailed graph with all available information. * Useful for debugging tree state and structure. * * @param tree - Tree to visualize * @returns Detailed DOT format string */ export async function writeDetailedDOTGraph(tree: ImmutableTree): Promise { return writeDOTGraph(tree, { showVersions: true, showHeights: true, showHashes: true, showNodeKeys: true, maxLabelLength: 64, }); } /** * Helper to truncate strings for display. */ function truncateString(str: string, maxLength: number): string { if (str.length <= maxLength) return str; const half = Math.floor((maxLength - 3) / 2); return str.slice(0, half) + "..." + str.slice(-half); } /** * Creates a graph showing the path taken for a proof. * * @param tree - Tree containing the proof path * @param key - Key for which proof was generated * @returns DOT format string with highlighted proof path */ export async function writeProofPathGraph( tree: ImmutableTree, key: Uint8Array, ): Promise { // Get proof to extract path const proof = await tree.getProof(key); // Extract path nodes from proof const pathNodes: ProofInnerNode[] = []; // For exist proofs, extract path from proof structure if (proof.exist) { // Path nodes would be in the proof path // This would require extracting from the ICS23 proof structure // For now, we'll use empty path } return writeDOTGraph(tree, { highlightPath: pathNodes, showHashes: true, }); } /** * Utility class for building and manipulating tree graphs. */ export class TreeGraphBuilder { private graph: Digraph; private nodeMap: Map; constructor(name = "IAVL_Tree") { this.graph = new Digraph(name); this.nodeMap = new Map(); } /** * Adds a node to the graph. */ addNode(id: string, label: string, attrs?: Record): GraphvizNode { const node = new GraphvizNode(id, { [attribute.label]: label, ...attrs, }); this.graph.addNode(node); this.nodeMap.set(id, node); return node; } /** * Adds an edge between nodes. */ addEdge(fromId: string, toId: string, label?: string): void { const from = this.nodeMap.get(fromId); const to = this.nodeMap.get(toId); if (from && to) { const edge = new Edge([from, to], label ? { [attribute.label]: label, } : { }); this.graph.addEdge(edge); } } /** * Gets the DOT representation. */ toDot(): string { return toDot(this.graph); } /** * Builds a graph from an IAVL tree. */ static async fromTree( tree: ImmutableTree, options?: GraphOptions, ): Promise { const builder = new TreeGraphBuilder(); const opts = { ...DEFAULT_OPTIONS, ...options, }; async function traverse(node: IavlNode | null, parentId?: string): Promise { if (!node) return; const nodeId = node.hash ? bytesToHex(node.hash) : `node_${Math.random()}`; const keyStr = node.key && node.key.length > 0 ? bytesToHex(node.key) : "(empty)"; const label = truncateString(keyStr, opts.maxLabelLength); // Add node const attrs: Record = { }; if (node.isLeaf()) { attrs[attribute.style] = "filled"; attrs[attribute.fillcolor] = "lightgray"; } builder.addNode(nodeId, label, attrs); // Add edge from parent if (parentId) { builder.addEdge(parentId, nodeId); } // Traverse children if (!node.isLeaf()) { // Load left child (may be cached or need to load from storage) const leftChild = await node.getLeftNode(tree.ndb); if (leftChild) { await traverse(leftChild, nodeId); } // Load right child (may be cached or need to load from storage) const rightChild = await node.getRightNode(tree.ndb); if (rightChild) { await traverse(rightChild, nodeId); } } } const root = tree.getRoot(); if (root) { await traverse(root); } return builder; } }