Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 109 additions & 6 deletions openverifiablellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand All @@ -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
):
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(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:
Comment thread
aniket866 marked this conversation as resolved.
Resolved
"""
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

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
# extract clean wikipage from actual wikipage
def extract_text_from_xml(input_path):
Expand Down Expand Up @@ -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),
Expand Down
26 changes: 26 additions & 0 deletions tests/test_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Loading