File size: 4,866 Bytes
19591f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/env python3
"""Validate release integrity and derived views; optionally run original mathematics.

Standard library only. The optional mathematics run operates in a temporary
copy so original reports and release checksums stay unchanged.
"""
from pathlib import Path, PurePosixPath
import argparse
import hashlib
import json
import re
import shutil
import subprocess
import sys
import tempfile

ROOT = Path(__file__).resolve().parents[1]
EXPECTED_COUNTS = {'artifacts':36, 'manuscript_pages':41, 'claims':17, 'certificates':4}

def require(condition, message):
    if not condition:
        raise ValueError(message)

def check_sums(root):
    entries = {}
    for line in (root/'SHA256SUMS.txt').read_text(encoding='utf-8').splitlines():
        if not line.strip():
            continue
        match = re.fullmatch(r'([a-f0-9]{64})  (.+)', line)
        require(match is not None, 'Invalid checksum line')
        digest, name = match.groups()
        rel = PurePosixPath(name)
        require(not rel.is_absolute() and '..' not in rel.parts and '\\' not in name
                and name != 'SHA256SUMS.txt' and name not in entries, 'Invalid checksum path')
        path = root/name
        require(path.is_file() and not path.is_symlink(), 'Missing regular file: '+name)
        require(hashlib.sha256(path.read_bytes()).hexdigest() == digest, 'Checksum mismatch: '+name)
        entries[name] = digest
    require(bool(entries), 'Empty checksum manifest')
    return entries

def validate():
    release = check_sums(ROOT)
    original = check_sums(ROOT/'research')
    rows = {}
    for name, count in EXPECTED_COUNTS.items():
        rows[name] = [json.loads(line) for line in (ROOT/'data'/(name+'.jsonl')).read_text(encoding='utf-8').splitlines() if line.strip()]
        require(len(rows[name]) == count, 'Wrong record count: '+name)
        require(len({tuple(sorted(row)) for row in rows[name]}) == 1, 'Inconsistent fields: '+name)
    artifact_paths = set()
    for row in rows['artifacts']:
        path = ROOT/row['path']
        require(row['artifact_id'] == row['path'] and row['path'] not in artifact_paths, 'Duplicate artifact')
        artifact_paths.add(row['path'])
        require(path.is_file() and path.stat().st_size == row['size_bytes'], 'Artifact size mismatch')
        require(hashlib.sha256(path.read_bytes()).hexdigest() == row['sha256'], 'Artifact hash mismatch')
    require(artifact_paths == {'research/'+name for name in original} | {'research/SHA256SUMS.txt'}, 'Incomplete original artifact index')
    require([row['page_number'] for row in rows['manuscript_pages']] == list(range(1,42)), 'Page order mismatch')
    require(all(row['text'].strip() and row['page_count'] == 41 for row in rows['manuscript_pages']), 'Empty page text or wrong page count')
    require(rows['manuscript_pages'][-1]['content_role'] == 'literary_dedication', 'Dedication role missing')
    require('Maciej Nowicki' in rows['manuscript_pages'][-1]['text'], 'Dedication text missing')
    source_claims = json.loads((ROOT/'research/RESEARCH_STATUS.json').read_text(encoding='utf-8'))['proven_results']
    for row, claim in zip(rows['claims'], source_claims):
        reconstructed = {'id':row['claim_id'], 'statement':row['statement']}
        if row['qualification']:
            reconstructed['qualification'] = row['qualification']
        reconstructed.update(json.loads(row['details_json']))
        require(reconstructed == claim, 'Claim view mismatch: '+row['claim_id'])
    for row in rows['certificates']:
        payload = json.loads(row['payload_json'])
        require(payload == json.loads((ROOT/row['source_path']).read_text(encoding='utf-8')), 'Certificate view mismatch')
        require(row['n'] == payload['n'] and row['kind'] == payload['kind'] and row['support_size'] == len(payload['p']), 'Certificate metadata mismatch')
    print('PASS: '+str(len(release))+' release checksum entries; '+str(len(original))+' original checksum entries; four consistent JSONL views.')

def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--mathematics', action='store_true', help='Run original exact-arithmetic suite in a temporary copy')
    args=parser.parse_args()
    try:
        validate()
        if args.mathematics:
            with tempfile.TemporaryDirectory(prefix='neiru-siha-verification-') as tmp:
                work=Path(tmp)/'research'
                shutil.copytree(ROOT/'research',work)
                subprocess.run([sys.executable,str(work/'verify_all.py')],cwd=work,check=True)
            print('PASS: original mathematics suite; released files unchanged.')
        return 0
    except (ValueError, OSError, subprocess.CalledProcessError) as exc:
        print('FAIL: '+str(exc),file=sys.stderr)
        return 1

if __name__ == '__main__':
    raise SystemExit(main())