Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
105 changes: 99 additions & 6 deletions openverifiablellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,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 @@ -40,6 +43,96 @@ 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))

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

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(chunk_bytes))
expected_root = bytes.fromhex(merkle_root)
except (TypeError, ValueError):
return False

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

sibling_hex, is_left = step

try:
sibling = bytes.fromhex(sibling_hex)
except (TypeError, ValueError):
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

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 @@ -124,7 +217,7 @@ def generate_manifest(raw_path, processed_path):
logger.info("Manifest written to %s", manifest_path)

# helpers:Update compute_sha256() to support bytes input directly.
def compute_sha256(file_path: Union[str, Path, bytes, bytearray]) -> str:
def compute_sha256(data: Union[str, Path, bytes, bytearray]) -> str:
"""
Compute SHA256 hash of a file OR raw bytes.
This is used for both raw and processed files to ensure integrity.
Expand All @@ -133,12 +226,12 @@ def compute_sha256(file_path: Union[str, Path, bytes, bytearray]) -> str:
"""
sha256 = hashlib.sha256()

# If bytes provided
if isinstance(file_path, (bytes, bytearray)):
sha256.update(file_path)
# If raw bytes provided
if isinstance(data, (bytes, bytearray)):
sha256.update(data)
return sha256.hexdigest()

path = Path(file_path)
path = Path(data)

with path.open("rb") as f:
while chunk := f.read(8192):
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)