-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverify_blocks.py
More file actions
72 lines (53 loc) · 2.26 KB
/
verify_blocks.py
File metadata and controls
72 lines (53 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
import hashlib
import re
from typing import List, Tuple, Union
def sha256_hash(data: Union[bytes, str]) -> str:
if isinstance(data, str):
data = data.encode()
return hashlib.sha256(data).hexdigest()
def extract_difficulty(block_contents):
difficulty_pattern = re.compile(b'<difficulty>([0-9a-fA-F]+)</difficulty>')
if isinstance(block_contents, str):
block_contents = block_contents.encode()
match = difficulty_pattern.search(block_contents)
if match:
return match.group(1).decode()
else:
return None
def extract_prior_block_info(block_content: str, is_first_block: bool) -> Tuple[str, str]:
prior_block_hash_re = re.compile('<priorBlockHash>\s*<hash>([a-zA-Z0-9]+)</hash>\s*<file>(.*)<file/>\s*</priorBlockHash>')
match = prior_block_hash_re.search(block_content)
if match:
prior_block_hash = match.group(1)
prior_block_file = match.group(2) if not is_first_block else ''
return prior_block_hash, prior_block_file
return '', ''
def verify_block(block_path: str, previous_hash: str, is_first_block: bool) -> Tuple[bool, str, str]:
with open(block_path, 'rb') as f:
block_contents = f.read()
prior_block_hash, prior_block_file = extract_prior_block_info(block_contents.decode(), is_first_block)
if not is_first_block:
if prior_block_hash != previous_hash:
return False, None, None
block_hash = sha256_hash(block_contents)
difficulty = extract_difficulty(block_contents)
if difficulty is None:
return False, None, None
target = int(difficulty, 16)
if int(block_hash, 16) > target:
return False, block_hash, difficulty
return True, block_hash, difficulty
if __name__ == "__main__":
previous_hash=""
block_dir = "./blk"
block_files = os.listdir(block_dir)
block_files.sort(key=lambda f: int(f.split(".")[0]))
for block_file in block_files:
block_path = os.path.join(block_dir, block_file)
is_first_block = block_file == "0.blk"
print("verifying block: ", block_path)
is_valid, previous_hash, difficulty = verify_block(block_path, previous_hash, is_first_block)
if not is_valid:
print(f"Invalid block: {block_path}")
break