Skip to content
73 changes: 71 additions & 2 deletions openverifiablellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
import defusedxml.ElementTree as ET
from pathlib import Path
import sys
from typing import Union
import hashlib
import logging
import json
import platform
from typing import Union, Optional
from typing import Union, Optional, Dict, Any, List, Tuple
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

logger = logging.getLogger(__name__)
MERKLE_CHUNK_SIZE_BYTES = 1024 * 1024 # 1MB
Expand Down Expand Up @@ -227,6 +226,76 @@ def generate_manifest(raw_path, processed_path):

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

def export_merkle_proof(
proof: List[Tuple[str, bool]],
chunk_index: int,
chunk_size: int,
output_path: Union[str, Path]
) -> None:
"""
Export Merkle proof to a JSON file for portable verification.
"""

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

if not isinstance(proof, list):
raise ValueError("proof must be a list")

if chunk_index < 0:
raise ValueError("chunk_index must be non-negative")

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]
) -> Dict[str, Any]:
"""
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


# Content before line 270 remains unchanged
# Entire function definition from lines 270-314 should be deleted
def verify_merkle_proof_from_file(
proof_file_path: Union[str, Path],
chunk_data: bytes,
expected_root: str
) -> bool:
proof_file_path = Path(proof_file_path)

if not proof_file_path.exists():
raise FileNotFoundError(f"Proof file not found: {proof_file_path}")

with proof_file_path.open("r", encoding="utf-8") as f:
data = json.load(f)

if not isinstance(data, dict):
raise ValueError("Malformed proof file: expected JSON object")

required_keys = {"chunk_index", "chunk_size", "proof"}
if not required_keys.issubset(data.keys()):
raise ValueError("Malformed proof file: missing required keys")

proof = data["proof"]

if not isinstance(proof, list):
raise ValueError("Malformed proof: proof must be a list")

return verify_merkle_proof(chunk_data, proof, expected_root)

# helpers:Update compute_sha256() to support bytes input directly.
def compute_sha256(
*,
Expand Down
27 changes: 27 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,30 @@ def test_merkle_proof_verification(tmp_path):
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(
proof_file_path=proof_file,
chunk_data=chunk,
expected_root=root,
)
Loading