Recursive python:
import hashlib
from typing import List
from anytree import Node, RenderTree, AsciiStyle
def hash_function(data: str) -> str:
return hashlib.sha256(data.encode()).hexdigest()
def combine_hashes(hash1: str, hash2: str) -> str:
return hash_function(hash1 hash2)
def build_merkle_tree_recursive(nodes: List[Node]) -> Node:
if len(nodes) == 1:
return nodes[0]
if len(nodes) % 2 != 0:
last_node = nodes[-1]
nodes.append(Node(last_node.name))
parent_nodes = []
for i in range(0, len(nodes), 2):
combined_hash = combine_hashes(nodes[i].name, nodes[i 1].name)
parent_node = Node(f"{combined_hash[:3]}...{combined_hash[-3:]}", children=[nodes[i], nodes[i 1]])
parent_nodes.append(parent_node)
return build_merkle_tree_recursive(parent_nodes)
def print_recursive_tree(root: Node) -> None:
for pre, fill, node in RenderTree(root, style=AsciiStyle()):
print("%s%s" % (pre,
node.name))
# Sample input similar to the provided image
input_data = "solana,rust,anchor,svm,merkle-trees,poh"
data_list = [item.strip() for item in input_data.split(",")]
# Convert the data list to nodes
initial_nodes = [Node(f"{hash_function(item)[:3]}...{hash_function(item)[-3:]}") for item in data_list]
# Build the Merkle tree recursively
merkle_tree_root = build_merkle_tree_recursive(initial_nodes)
# Print the tree
print_recursive_tree(merkle_tree_root)