Skip to content
52 changes: 52 additions & 0 deletions openverifiablellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,58 @@ 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_from_file(
chunk_bytes: bytes,
proof_path: Union[str, Path],
merkle_root: str
) -> bool:
"""
Verify chunk using proof stored in a JSON file.
"""
try:
data = load_merkle_proof(proof_path)
except (OSError, json.JSONDecodeError) as e:
logger.warning("Failed to load proof file %s: %s", proof_path, e)
return False

proof = data.get("proof")
if proof is None:
return False
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

return verify_merkle_proof(chunk_bytes, proof, merkle_root)

# helpers:Update compute_sha256() to support bytes input directly.
def compute_sha256(file_path: Union[str, Path, bytes, bytearray]) -> str:
"""
Expand Down
23 changes: 23 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,3 +220,26 @@ 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(chunk, proof_file, root)