FatUnc6969's picture
Publish reviewed Borderland v8 research artifact
2719bf4 verified
Raw History Blame Contribute Delete
4.56 kB
import hashlib
import json
from pathlib import Path
from .domain import WorldSpec, RecordRevision, ArchiveSpec, canonical
def source_hash():
root=Path(__file__).parent
digest=hashlib.sha256()
for path in [root/name for name in ('domain.py','engine.py','worlds.py','plant.py','replay.py')]:
digest.update(str(path.relative_to(root)).encode()); digest.update(path.read_bytes())
return digest.hexdigest()
def verify_replay(path):
from .engine import Campaign
try:
lines=[json.loads(line) for line in Path(path).read_text(encoding='utf-8').splitlines()]
header=lines[0]
if type(header) is not dict: raise ValueError('replay header must be an object')
if header.get('visibility')!='private':
return dict(verified=False,mismatches=['public replay is view-only; trusted world configuration absent'],view_only=True)
if header.get('source_hash') != source_hash():
return dict(verified=False,mismatches=['source_hash mismatch; use required pinned source '+str(header.get('source_hash'))])
values=header['world']
if type(values) is not dict: raise ValueError('replay world must be an object')
version=values.get('generation_version')
if version not in (2,3):
return dict(verified=False,mismatches=['generation mismatch; historical worlds require their pinned source'])
expected_spec_hash=hashlib.sha256(canonical(values).encode()).hexdigest()
values['restoration_order']=tuple(values['restoration_order'])
archive=values['archive']
if version == 3:
from .plant import decode_infrastructure, decode_clause, Charter, CharterRevision
values['infrastructure']=decode_infrastructure(values['infrastructure'])
archive['pages']=tuple(tuple(tuple(CharterRevision(**{**record,'body':decode_clause(record['body'])}) for record in page) for page in scroll) for scroll in archive['pages'])
values['archive']=Charter(**archive)
else:
archive['pages']=tuple(tuple(tuple(RecordRevision(**record) for record in page) for page in scroll) for scroll in archive['pages'])
values['archive']=ArchiveSpec(**archive)
world=WorldSpec(**values); env=Campaign(world); mismatches=[]
events=lines[1:]
if any(type(event) is not dict for event in events): raise ValueError('replay events must be objects')
if header.get('format')!='borderland-replay-v'+str(version): mismatches.append('unsupported replay format or missing save commitments')
if version == 3 and header.get('generation_version') != version: mismatches.append('generation header')
if type(header.get('event_count')) is not int or header['event_count']!=len(events): mismatches.append('event count')
if not events or events[0].get('kind')!='reset': mismatches.append('missing initial reset')
if header['source_hash']!=source_hash(): mismatches.append('source_hash')
if header.get('spec_hash')!=expected_spec_hash: mismatches.append('spec_hash')
previous=None
for index,event in enumerate(events):
if event['index']!=index: mismatches.append('event index '+str(index))
expected=hashlib.sha256(canonical(event['transition']).encode()).hexdigest()
if event.get('before_public_digest')!=previous or event.get('after_public_digest')!=expected: mismatches.append('event chain '+str(index))
previous=expected
if event['kind']=='reset':
if index!=0 or event['input'] is not None: mismatches.append('unexpected reset '+str(index))
actual=env.reset()
elif event['kind']=='action': actual=env.step(event['input'])
elif event['kind']=='note': actual=env.replace_notebook(event['input'])
else:
mismatches.append('unknown event '+str(index)); continue
if canonical(actual.to_dict())!=canonical(event['transition']): mismatches.append('transition '+str(index))
if header.get('final_public_digest')!=previous: mismatches.append('final public digest')
if header.get('final_outcome')!=env.observe().outcome: mismatches.append('final outcome')
return dict(verified=not mismatches,mismatches=mismatches,events=len(events),view_only=False,outcome=env.observe().outcome,episode_complete=env.observe().done)
except (OSError,ValueError,TypeError,KeyError,IndexError) as error:
return dict(verified=False,mismatches=[str(error)])