"""Shared 1,024-byte-leaf Bao tree (`fleetmesh_core.textile.bao`).
Byte-for-byte identical to `@fleetmesh/textile`'s `baoCore.ts`: leaves are
`sha256(0x00 || chunk)`, parents `sha256(0x01 || left || right)`, and an odd node at
the end of a level is paired with itself. That is the TREE root. The Bao root - the
identity of every fiber, strand and schema - wraps it with the length:
`sha256(0x02 || u64be(byte_length) || tree_root)` (constants.json textile.bao).
The wrap is there because pairing an odd node with itself lets different bytes share
a tree root: three 1,024-byte chunks and the same three with the last repeated have
one (audit 2026-11-18, textile #17). The length tells them apart.
Files travel in 8 MiB segments (`2**BAO_SUBTREE_POW` leaves). A segment's own root is
its TREE root (`bao_tree_root`), so segments combine: `promote_segment_root` lifts a
short trailing segment to the full subtree height and `combine_segment_roots` folds the
segment tree roots and wraps the result with the total length, which equals
`bao_root_1024` of the whole file. The node's `RhioBaoTree` and other tools delegate
here: this module is the one Python implementation.
"""
from __future__ import annotations
import hashlib
from typing import Sequence, Tuple
BAO_LEAF_SIZE = 1024
BAO_SUBTREE_POW = 13
BAO_SEGMENT_SIZE = BAO_LEAF_SIZE * (1 << BAO_SUBTREE_POW) # 8,388,608 bytes (8 MiB)
# The tree root of no bytes: one empty leaf.
EMPTY_BAO_TREE_ROOT_HEX = hashlib.sha256(b'\x00').hexdigest()
def wrap_root(tree_root_hex: str, byte_length: int) -> str:
"""The Bao root: `sha256(0x02 || u64be(byte_length) || tree_root)`."""
n = int(byte_length)
if n < 0 or n >= 1 << 64:
raise ValueError('byte_length out of range')
return hashlib.sha256(b'\x02' + n.to_bytes(8, 'big') + bytes.fromhex(tree_root_hex.strip())).hexdigest()
EMPTY_BAO_ROOT_HEX = wrap_root(EMPTY_BAO_TREE_ROOT_HEX, 0)
def _fold(layer: list) -> bytes:
"""Pair a layer of node digests up to a single root (odd node paired with itself)."""
while len(layer) > 1:
layer = [
hashlib.sha256(b'\x01' + layer[i] + (layer[i + 1] if i + 1 < len(layer) else layer[i])).digest()
for i in range(0, len(layer), 2)
]
return layer[0]
def bao_leaf_count(size_bytes: int, chunk_size: int = BAO_LEAF_SIZE) -> int:
"""The number of `chunk_size`-byte leaves `size_bytes` occupies (minimum 1)."""
return max(1, (max(0, int(size_bytes)) + chunk_size - 1) // chunk_size)
def bao_tree_root(raw: bytes) -> Tuple[str, int]:
"""`(tree_root_hex, leaf_count)` for `raw`: the tree alone, no length.
What a segment or a chunk is checked and combined by. Not an identity: different
bytes can share it. A caller checking a chunk against it also checks the chunk's
length."""
if not raw:
return EMPTY_BAO_TREE_ROOT_HEX, 1
lvl = [
hashlib.sha256(b'\x00' + raw[i:i + BAO_LEAF_SIZE]).digest()
for i in range(0, len(raw), BAO_LEAF_SIZE)
]
return _fold(lvl).hex(), len(lvl)
def bao_root_1024(raw: bytes) -> Tuple[str, int]:
"""Return `(root_hex, leaf_count)` for `raw`: the Bao root, length included."""
tree, leaves = bao_tree_root(raw)
return wrap_root(tree, len(raw)), leaves
def promote_segment_root(
segment_root_hex: str,
segment_size: int,
*,
is_single_segment: bool = False,
chunk_size: int = BAO_LEAF_SIZE,
subtree_pow: int = BAO_SUBTREE_POW,
) -> str:
"""Lift a segment's standalone root to the `2**subtree_pow`-leaf subtree height.
Every non-final segment of a multi-segment file already has that many leaves; a
shorter trailing segment is paired with itself at each missing layer. A file of one
segment is its own root and is returned unchanged.
"""
clean_hex = segment_root_hex.strip().lower()
if is_single_segment:
return clean_hex
n_leaves = bao_leaf_count(segment_size, chunk_size=chunk_size)
steps_done = (n_leaves - 1).bit_length()
node = bytes.fromhex(clean_hex)
for _ in range(max(0, subtree_pow - steps_done)):
node = hashlib.sha256(b'\x01' + node + node).digest()
return node.hex()
def combine_segment_roots(
segments: Sequence[Tuple[str, int]],
*,
chunk_size: int = BAO_LEAF_SIZE,
subtree_pow: int = BAO_SUBTREE_POW,
) -> str:
"""The whole file's Bao root from its `(segment_tree_root_hex, segment_byte_size)` list.
The segment roots are TREE roots (`bao_tree_root`); the result is wrapped with the
total length, so it equals `bao_root_1024` of the whole file."""
if not segments:
return EMPTY_BAO_ROOT_HEX
is_single = len(segments) == 1
layer = [
bytes.fromhex(
promote_segment_root(
root_hex, seg_size, is_single_segment=is_single, chunk_size=chunk_size, subtree_pow=subtree_pow
)
)
for root_hex, seg_size in segments
]
return wrap_root(_fold(layer).hex(), sum(int(size) for _, size in segments))
[docs]def canonical_bao_hex(seed: str) -> str:
return bao_root_1024(seed.encode("utf-8"))[0]