1414MERKLE_CHUNK_SIZE_BYTES = 1024 * 1024 # 1MB
1515
1616# Merkle Tree Chunk-Level Hashing for Large Files
17- def compute_merkle_root (file_path : Union [str , Path ], chunk_size : int = 1024 * 1024 ) -> str :
17+ def compute_merkle_root (file_path : Union [str , Path ], chunk_size : int = MERKLE_CHUNK_SIZE_BYTES ) -> str :
18+ if chunk_size <= 0 :
19+ raise ValueError ("chunk_size must be a positive integer" )
20+
1821 path = Path (file_path )
1922 leaves = []
2023
2124 with path .open ("rb" ) as f :
2225 while chunk := f .read (chunk_size ):
2326 # reuse compute_sha256
24- leaf_hex = compute_sha256 (chunk )
27+ leaf_hex = compute_sha256 (data = chunk )
2528 leaves .append (bytes .fromhex (leaf_hex ))
2629
2730 if not leaves :
28- return compute_sha256 (b"" )
31+ return compute_sha256 (data = b"" )
2932
3033 while len (leaves ) > 1 :
3134 next_level = []
@@ -34,13 +37,113 @@ def compute_merkle_root(file_path: Union[str, Path], chunk_size: int = 1024 * 10
3437 right = leaves [i + 1 ] if i + 1 < len (leaves ) else left
3538
3639 combined = left + right
37- parent_hex = compute_sha256 (combined )
40+ parent_hex = compute_sha256 (data = combined )
3841 next_level .append (bytes .fromhex (parent_hex ))
3942
4043 leaves = next_level
4144
4245 return leaves [0 ].hex ()
4346
47+ def generate_merkle_proof (
48+ file_path : Union [str , Path ],
49+ chunk_index : int ,
50+ chunk_size : int = MERKLE_CHUNK_SIZE_BYTES
51+ ):
52+ """
53+ Generate Merkle proof for a specific chunk index.
54+
55+ Returns:
56+ List of tuples (sibling_hash_hex, is_left)
57+ """
58+ path = Path (file_path )
59+
60+ if chunk_size <= 0 :
61+ raise ValueError ("chunk_size must be a positive integer" )
62+
63+ leaves = []
64+
65+ # Build leaf level
66+ with path .open ("rb" ) as f :
67+ while chunk := f .read (chunk_size ):
68+ leaf_hex = compute_sha256 (data = chunk )
69+ leaves .append (bytes .fromhex (leaf_hex ))
70+
71+ if not leaves :
72+ raise ValueError ("Cannot generate proof for empty file" )
73+
74+ if chunk_index < 0 or chunk_index >= len (leaves ):
75+ raise IndexError ("Chunk index out of range" )
76+
77+ proof = []
78+ index = chunk_index
79+
80+ while len (leaves ) > 1 :
81+ # If odd number of nodes, duplicate last
82+ if len (leaves ) % 2 == 1 :
83+ leaves .append (leaves [- 1 ])
84+
85+ sibling_index = index ^ 1
86+ sibling = leaves [sibling_index ]
87+
88+ is_left = sibling_index < index
89+ proof .append ((sibling .hex (), is_left ))
90+
91+ # Build next level
92+ next_level = []
93+ for i in range (0 , len (leaves ), 2 ):
94+ combined = leaves [i ] + leaves [i + 1 ]
95+ parent_hex = compute_sha256 (data = combined )
96+ next_level .append (bytes .fromhex (parent_hex ))
97+
98+ index //= 2
99+ leaves = next_level
100+
101+ return proof
102+
103+ def verify_merkle_proof (
104+ chunk_bytes : bytes ,
105+ proof ,
106+ merkle_root : str
107+ ) -> bool :
108+ """
109+ Verify a Merkle proof for given chunk bytes.
110+ """
111+ try :
112+ current_hash = bytes .fromhex (compute_sha256 (data = chunk_bytes ))
113+ expected_root = bytes .fromhex (merkle_root )
114+ except (TypeError , ValueError ):
115+ return False
116+
117+ if not isinstance (proof , (list , tuple )):
118+ return False
119+
120+ for step in proof :
121+ if not isinstance (step , (tuple , list )) or len (step ) != 2 :
122+ return False
123+
124+ sibling_hex , is_left = step
125+
126+ if not isinstance (sibling_hex , str ) or not isinstance (is_left , bool ):
127+ return False
128+
129+ try :
130+ sibling = bytes .fromhex (sibling_hex )
131+ except (TypeError , ValueError ):
132+ return False
133+
134+ # Ensure correct hash length
135+ if len (sibling ) != hashlib .sha256 ().digest_size :
136+ return False
137+
138+ if is_left :
139+ combined = sibling + current_hash
140+ else :
141+ combined = current_hash + sibling
142+
143+ parent_hex = compute_sha256 (data = combined )
144+ current_hash = bytes .fromhex (parent_hex )
145+
146+ return current_hash == expected_root
44147
45148# extract clean wikipage from actual wikipage
46149def extract_text_from_xml (input_path ):
@@ -103,8 +206,8 @@ def generate_manifest(raw_path, processed_path):
103206 manifest = {
104207 "wikipedia_dump" : raw_path .name ,
105208 "dump_date" : extract_dump_date (raw_path .name ),
106- "raw_sha256" : compute_sha256 (str ( raw_path ) ),
107- "processed_sha256" : compute_sha256 (str ( processed_path ) ),
209+ "raw_sha256" : compute_sha256 (file_path = raw_path ),
210+ "processed_sha256" : compute_sha256 (file_path = processed_path ),
108211
109212 # ---------------- ADDED FIELDS ----------------
110213 "raw_merkle_root" : compute_merkle_root (raw_path , chunk_size = MERKLE_CHUNK_SIZE_BYTES ),
0 commit comments