diff --git a/openverifiablellm/utils.py b/openverifiablellm/utils.py index 06cd11e7..3180b3fa 100644 --- a/openverifiablellm/utils.py +++ b/openverifiablellm/utils.py @@ -14,18 +14,21 @@ 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 = [] with path.open("rb") as f: while chunk := f.read(chunk_size): # reuse compute_sha256 - leaf_hex = compute_sha256(chunk) + leaf_hex = compute_sha256(data=chunk) leaves.append(bytes.fromhex(leaf_hex)) if not leaves: - return compute_sha256(b"") + return compute_sha256(data=b"") while len(leaves) > 1: next_level = [] @@ -34,13 +37,113 @@ def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = 1024 * 10 right = leaves[i + 1] if i + 1 < len(leaves) else left combined = left + right - parent_hex = compute_sha256(combined) + parent_hex = compute_sha256(data=combined) next_level.append(bytes.fromhex(parent_hex)) leaves = next_level return leaves[0].hex() +def generate_merkle_proof( + file_path: Union[str, Path], + chunk_index: int, + chunk_size: int = MERKLE_CHUNK_SIZE_BYTES +): + """ + 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(data=chunk) + leaves.append(bytes.fromhex(leaf_hex)) + + 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(data=combined) + next_level.append(bytes.fromhex(parent_hex)) + + index //= 2 + leaves = next_level + + return proof + +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(data=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(data=combined) + current_hash = bytes.fromhex(parent_hex) + + return current_hash == expected_root # extract clean wikipage from actual wikipage def extract_text_from_xml(input_path): @@ -103,8 +206,8 @@ def generate_manifest(raw_path, processed_path): manifest = { "wikipedia_dump": raw_path.name, "dump_date": extract_dump_date(raw_path.name), - "raw_sha256": compute_sha256(str(raw_path)), - "processed_sha256": compute_sha256(str(processed_path)), + "raw_sha256": compute_sha256(file_path=raw_path), + "processed_sha256": compute_sha256(file_path=processed_path), # ---------------- ADDED FIELDS ---------------- "raw_merkle_root": compute_merkle_root(raw_path, chunk_size=MERKLE_CHUNK_SIZE_BYTES), diff --git a/tests/test_util.py b/tests/test_util.py index 843c90eb..560e5fb6 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -194,3 +194,29 @@ 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)