Skip to content
137 changes: 136 additions & 1 deletion openverifiablellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@
MERKLE_CHUNK_SIZE_BYTES = 1024 * 1024 # 1MB

# Merkle Tree Chunk-Level Hashing for Large Files
def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = 1024 * 1024) -> str:
def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = MERKLE_CHUNK_SIZE_BYTES) -> str:
if chunk_size <= 0:
raise ValueError("chunk_size must be a positive integer")

path = Path(file_path)
leaves = []

Expand All @@ -41,6 +44,61 @@ def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = 1024 * 10

return leaves[0].hex()

def generate_merkle_proof(
file_path: Union[str, Path],
chunk_index: int,
chunk_size: int = MERKLE_CHUNK_SIZE_BYTES
):
Comment thread
aniket866 marked this conversation as resolved.
Resolved
"""
Generate Merkle proof for a specific chunk index.

Returns:
List of tuples (sibling_hash_hex, is_left)
"""
path = Path(file_path)

if chunk_size <= 0:
raise ValueError("chunk_size must be a positive integer")

leaves = []

# Build leaf level
with path.open("rb") as f:
while chunk := f.read(chunk_size):
leaf_hex = compute_sha256(chunk)
leaves.append(bytes.fromhex(leaf_hex))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

if not leaves:
raise ValueError("Cannot generate proof for empty file")

if chunk_index < 0 or chunk_index >= len(leaves):
raise IndexError("Chunk index out of range")

proof = []
index = chunk_index

while len(leaves) > 1:
# If odd number of nodes, duplicate last
if len(leaves) % 2 == 1:
leaves.append(leaves[-1])

sibling_index = index ^ 1
sibling = leaves[sibling_index]

is_left = sibling_index < index
proof.append((sibling.hex(), is_left))

# Build next level
next_level = []
for i in range(0, len(leaves), 2):
combined = leaves[i] + leaves[i + 1]
parent_hex = compute_sha256(combined)
next_level.append(bytes.fromhex(parent_hex))

index //= 2
leaves = next_level

return proof

# extract clean wikipage from actual wikipage
def extract_text_from_xml(input_path):
Expand Down Expand Up @@ -124,6 +182,83 @@ def generate_manifest(raw_path, processed_path):

logger.info("Manifest written to %s", manifest_path)

def export_merkle_proof(
proof,
chunk_index: int,
chunk_size: int,
output_path: Union[str, Path]
):
"""
Export Merkle proof to a JSON file for portable verification.
"""
data = {
"chunk_index": chunk_index,
"chunk_size": chunk_size,
"proof": proof,
}

output_path = Path(output_path)
with output_path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=2)

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

def load_merkle_proof(
proof_path: Union[str, Path]
):
"""
Load Merkle proof from a JSON file.
"""
proof_path = Path(proof_path)

with proof_path.open("r", encoding="utf-8") as f:
return json.load(f)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


def verify_merkle_proof(
chunk_bytes: bytes,
proof,
merkle_root: str
) -> bool:
"""
Verify a Merkle proof for given chunk bytes.
"""
try:
current_hash = bytes.fromhex(compute_sha256(chunk_bytes))
expected_root = bytes.fromhex(merkle_root)
except (TypeError, ValueError):
return False

if not isinstance(proof, (list, tuple)):
return False

for step in proof:
if not isinstance(step, (tuple, list)) or len(step) != 2:
return False

sibling_hex, is_left = step

if not isinstance(sibling_hex, str) or not isinstance(is_left, bool):
return False

try:
sibling = bytes.fromhex(sibling_hex)
except (TypeError, ValueError):
return False

# Ensure correct hash length
if len(sibling) != hashlib.sha256().digest_size:
return False

if is_left:
combined = sibling + current_hash
else:
combined = current_hash + sibling

parent_hex = compute_sha256(combined)
current_hash = bytes.fromhex(parent_hex)

return current_hash == expected_root

# helpers:Update compute_sha256() to support bytes input directly.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
def compute_sha256(
*,
Expand Down
49 changes: 49 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,3 +194,52 @@ def test_merkle_root_empty_file(tmp_path):
expected = hashlib.sha256(b"").hexdigest()

assert root == expected

# --------------- Merkle proof generation ------------------------------------

def test_merkle_proof_verification(tmp_path):
file = tmp_path / "data.txt"
content = b"hello world this is merkle proof test"
file.write_bytes(content)

root = utils.compute_merkle_root(file, chunk_size=8)
proof = utils.generate_merkle_proof(file, chunk_index=1, chunk_size=8)

with file.open("rb") as f:
f.seek(8)
chunk = f.read(8)
# Positive case
assert utils.verify_merkle_proof(chunk, proof, root)

# Negative case: tampered chunk
tampered_chunk = bytearray(chunk)
tampered_chunk[0] ^= 1
assert not utils.verify_merkle_proof(bytes(tampered_chunk), proof, root)

# Negative case: tampered proof
bad_proof = proof.copy()
bad_proof[0] = ("00" * 32, proof[0][1])
assert not utils.verify_merkle_proof(chunk, bad_proof, root)

def test_export_and_load_merkle_proof(tmp_path):
file = tmp_path / "data.txt"
content = b"portable proof verification example"
file.write_bytes(content)

root = utils.compute_merkle_root(file, chunk_size=8)
proof = utils.generate_merkle_proof(file, chunk_index=1, chunk_size=8)

proof_file = tmp_path / "proof.json"

utils.export_merkle_proof(
proof,
chunk_index=1,
chunk_size=8,
output_path=proof_file
)

with file.open("rb") as f:
f.seek(8)
chunk = f.read(8)

assert utils.verify_merkle_proof_from_file(chunk, proof_file, root)
Loading