"""Deterministic Merkle construction study; not a production proof verifier.""" import argparse import hashlib import itertools import json from pathlib import Path SCHEMA = "hesela.merkle-padding.v1" def leaf(data): return hashlib.sha256(b"\x00" + data).digest() def parent(left, right): return hashlib.sha256(b"\x01" + left + right).digest() def duplicate_last(entries): """Return root and pre-padding equal-sibling levels (zero is leaf level).""" if not entries: raise ValueError("This illustrative duplicate-last construction is nonempty") nodes = [leaf(x) for x in entries] equal_levels = [] level = 0 while len(nodes) > 1: if any(nodes[i] == nodes[i + 1] for i in range(0, len(nodes) - 1, 2)): equal_levels.append(level) if len(nodes) % 2: nodes.append(nodes[-1]) nodes = [parent(nodes[i], nodes[i + 1]) for i in range(0, len(nodes), 2)] level += 1 return nodes[0], equal_levels def split_tree(entries): """RFC 9162 section 2.1.1 shape and role prefixes, SHA-256 selected here.""" n = len(entries) if not n: return hashlib.sha256(b"").digest() if n == 1: return leaf(entries[0]) k = 1 << ((n - 1).bit_length() - 1) return parent(split_tree(entries[:k]), split_tree(entries[k:])) def symbolic(entries, padding): """Independent recursive formal expression; no hashes or level-wise loop.""" n = len(entries) if n == 0: return ("empty",) if n == 1: return ("leaf", entries[0].hex()) k = 1 << ((n - 1).bit_length() - 1) left = symbolic(entries[:k], padding) right = symbolic(entries[k:], padding) if padding: right_height = (n - k - 1).bit_length() for _ in range(k.bit_length() - 1 - right_height): right = ("node", right, right) return ("node", left, right) def evaluate(expression): if expression[0] == "empty": return hashlib.sha256(b"").digest() if expression[0] == "leaf": return leaf(bytes.fromhex(expression[1])) return parent(evaluate(expression[1]), evaluate(expression[2])) def root_and_count_match(entries, expected_root, expected_count): """Expected values must come from an independent trusted source.""" if not entries: return False return len(entries) == expected_count and duplicate_last(entries)[0] == expected_root def row(case, original, candidate): a = tuple(x.encode("ascii") for x in original) b = tuple(x.encode("ascii") for x in candidate) ar, al = duplicate_last(a) br, bl = duplicate_last(b) return { "case": case, "original": list(original), "candidate": list(candidate), "originalCount": len(a), "candidateCount": len(b), "originalHex": [x.hex() for x in a], "candidateHex": [x.hex() for x in b], "duplicateLast": { "originalRoot": ar.hex(), "candidateRoot": br.hex(), "sameRoot": ar == br, "sameExpression": symbolic(a, True) == symbolic(b, True), "originalEqualSiblingLevels": al, "candidateEqualSiblingLevels": bl, }, "splitTree": { "originalRoot": split_tree(a).hex(), "candidateRoot": split_tree(b).hex(), "sameRoot": split_tree(a) == split_tree(b), }, "trustedRootAndCountAccepts": root_and_count_match(b, ar, len(a)), } def exhaustive(max_length=10): by_digest = {True: {}, False: {}} by_expression = {True: {}, False: {}} count_bound = {} total = 0 for n in range(1, max_length + 1): for entries in itertools.product((b"A", b"B"), repeat=n): total += 1 for padding in (True, False): expr = symbolic(entries, padding) digest = duplicate_last(entries)[0] if padding else split_tree(entries) if evaluate(expr) != digest: raise RuntimeError("Recursive oracle disagrees with root implementation") previous = by_digest[padding].setdefault(digest, expr) if previous != expr: raise RuntimeError("Unexpected distinct-expression hash equality") by_expression[padding].setdefault(expr, []).append(entries) if padding: key = (n, digest) if count_bound.setdefault(key, entries) != entries: raise RuntimeError("Unexpected same-count structural ambiguity") summaries = {} for padding, label in ((True, "duplicateLast"), (False, "splitTree")): groups = list(by_expression[padding].values()) summaries[label] = { "distinctExpressions": len(groups), "distinctRoots": len(by_digest[padding]), "ambiguousGroups": sum(len(g) > 1 for g in groups), "listsInAmbiguousGroups": sum(len(g) for g in groups if len(g) > 1), "largestGroup": max(map(len, groups)), } return { "alphabetHex": ["41", "42"], "minLength": 1, "maxLength": max_length, "lists": total, "rootOracleComparisons": 2 * total, "sameCountDistinctListAliases": 0, "scope": "Exhaustive within this finite synthetic domain; not a collision-resistance proof or event probability.", **summaries, } def generate(): pairs = [ ("repeat-last-leaf", "ABC", "ABCC"), ("repeat-last-subtree", "ABCDEF", "ABCDEFEF"), ("odd-five-to-six", "ABCDE", "ABCDEE"), ("changed-entry-control", "ABC", "ABD"), ("reordered-control", "ABC", "ACB"), ("legitimate-repeat-control", "AA", "AA"), ] return { "schemaVersion": SCHEMA, "kind": "deterministic synthetic computation", "hash": "SHA-256", "leafPrefixHex": "00", "nodePrefixHex": "01", "rows": [row(*args) for args in pairs], "exhaustive": exhaustive(), "limits": [ "Not Bitcoin serialization, double-SHA256, consensus validation or a CT proof implementation.", "No disk failure, hardware experiment, performance or incident-rate measurement.", "Count matching assumes an independently trusted expected count and root.", "Equal-sibling flags are diagnostics, not a general storage rejection policy.", ], } def serialized(): return json.dumps(generate(), indent=2, ensure_ascii=True) + "\n" if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) mode = parser.add_mutually_exclusive_group() mode.add_argument("--output", type=Path) mode.add_argument("--check", type=Path) args = parser.parse_args() value = serialized() if args.check: if args.check.read_text() != value: raise SystemExit("Committed result differs from exact regeneration") print("Exact regeneration PASS") elif args.output: args.output.write_text(value) else: print(value, end="")