Files
praxisandClaude Fable 5.2 8a24c445b0 Content pipeline and operator tools
367 files, from working commit b1a079a.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-19 01:32:48 +02:00

830 lines
76 KiB
Python

#!/usr/bin/env python3
"""Read public DBCs, resolve manifests or inventory candidates; never infer order.
Uses the reviewed local Tortoise libmpq API, built outside its source tree.
No launcher execution, account files, WDB caches, downloads or client writes.
"""
import argparse
import ctypes as C
import hashlib
import json
import os
from pathlib import Path
from pathlib import PurePosixPath
import re
import struct
import subprocess
from turtle_data import DBC, TABLES, inventory_table, dependency_closure
ROOT = Path(__file__).resolve().parents[1]
NAMES = tuple(dict.fromkeys(TABLES + ('Item', 'ItemDisplayInfo', 'ItemSet', 'Map', 'AreaTable', 'CreatureDisplayInfo', 'CreatureModelData')))
def canonical_sha256(value):
"""Pin the supplied JSON document, independent of whitespace/key order."""
return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':'),ensure_ascii=False,allow_nan=False).encode()).hexdigest()
# These are reviewed PE32 natural-call boundaries in octo-loader-static.json,
# not addresses to invoke. New executable contracts require a reviewed update.
LOADED_CONTENT_CONTRACTS={'open':('0x6477a0',8),'read':('0x648460',24)}
BLOCK_FILL_CONTRACT=dict(entry_va='0x65702d',runtime_entry_sha256='141355574503375215310ad8a76e63490f2f566cc55021745837fda8bb0d3429',
verified=True,buffer_register='esi',actual_register='ebx',owner_frame_offset=-52,offset_frame_offset=-12,
lower_request_frame_offset=-8,async_frame_offset=24,return_frame_offset=4,source_read_return=0x64853b,outer_inner_offset=60,
inner_function_va='0x656b40',runtime_inner_sha256='411c1b71bdcfc173c4a1c77c2e535e4a28a07942f8d9268468a0085281bda05e',
outer_function_va='0x648460',runtime_outer_sha256='cbfceae78aa0fc594940bc0267aba96fe2efbc7c6f7e064a1db1605e99afb4f3',
outer_frame_offset=0,outer_return_frame_offset=4,outer_entry_sp_delta=4,outer_argument_bytes=24)
def _uint(value,bits=32,positive=False):
if type(value) is not int or not int(positive)<=value<2**bits:raise ValueError('Invalid bounded integer in load observation')
return value
def _relative_capture(value):
if not isinstance(value,str) or not value or '\\' in value or '\0' in value or PurePosixPath(value).is_absolute() or '..' in PurePosixPath(value).parts or str(PurePosixPath(value))!=value or not value.endswith('.dbc'):
raise ValueError('Require a safe relative captured DBC path')
return value
def _validate_transmog_contract(observation,loader,analysis):
"""Check one explicitly reviewed ordinary hook recipe; never execute it."""
if (not isinstance(analysis,dict) or type(analysis.get('schema_version')) is not int or analysis['schema_version']!=1 or
analysis.get('kind')!='installed-octo-read-only-transmog-read-analysis' or analysis.get('source_installation')!=loader['source_installation'] or
_hash(observation.get('transmog_analysis_sha256'))!=canonical_sha256(analysis)):
raise ValueError('Missing or changed reviewed ordinary transmog analysis')
module=analysis.get('module',{});exe=analysis.get('executable',{})
if (not isinstance(module,dict) or module.get('basename')!='transmogfix.dll' or module.get('sha256')!='cd9e4c6ce033b0923cf045269f590f5e0b886bd03f43bd81406670d781452210' or
module.get('bytes')!=12800 or module.get('pe32') is not True or module.get('size_of_image')!=69632 or
not isinstance(exe,dict) or exe.get('sha256')!=loader['executable']['sha256']):raise ValueError('Reviewed transmog module or executable identity differs')
slot=analysis.get('call_frame_contract',{}).get('original_mpq_actual_count_slot',{})
expected_slot=dict(instruction_va='0x648528',bytes=24,hex='8d451850575152c7451800000000e805e6000085c08b4d18',
sha256='12c73ac58d356d9108b39428678a4636e2ad0cc743cf52f487ba811515b83b74',original_frame_offset=24,source_argument_index=4)
if not isinstance(slot,dict) or any(slot.get(key)!=value or type(slot.get(key)) is not type(value) for key,value in expected_slot.items()):raise ValueError('Reviewed original actual-count temporary slot differs')
known={r['file'].casefold():r for r in loader.get('public_module_candidates',[])}
launch=observation.get('launch_method',{})
if (not isinstance(launch,dict) or launch.get('method')!='unmodified-pinned-official-loader' or launch.get('sha256')!='228d7bb5e3b5b0c2062d6c5f40c38c2a173e4c80d8a5d9e4077be800431b48a3' or
launch.get('bytes')!=88576 or launch.get('pe_machine')!='0x14c' or launch.get('pe_optional_magic')!='0x10b' or launch.get('arguments')!=['WoW.exe']):raise ValueError('Ordinary hook observation requires the pinned official loader')
for key in ('copy_manifest_sha256','dll_manifest_sha256','cache_sha256'):_hash(launch.get(key))
companion=launch.get('companion',{})
if companion!={'basename':'VfPatcher.dll','sha256':'f283b6b5ad8042e7995eff9768c150042dd47de6e5f00ffe530d2e67743df81d','bytes':72704}:raise ValueError('Official loader companion differs')
requested=launch.get('requested_modules')
if not isinstance(requested,list) or not 1<=len(requested)<=64:raise ValueError('Bounded official module list required')
requested_by_name={}
for row in requested:
if not isinstance(row,dict) or not isinstance(row.get('basename'),str):raise ValueError('Malformed requested official module')
name=row['basename'].casefold();pin=known.get(name)
if name in requested_by_name or pin is None or row.get('sha256')!=pin.get('sha256') or type(row.get('bytes')) is not int or row['bytes']!=pin.get('bytes'):raise ValueError('Requested official module identity differs')
requested_by_name[name]=row
if 'transmogfix.dll' not in requested_by_name:raise ValueError('Reviewed transmog module was not requested')
for phase in ('initial','final'):
inventory=observation.get('module_inventory_'+phase,{})
if not isinstance(inventory,dict) or inventory.get('available') is not True or inventory.get('scope')!='mapped-private-game-executable-files-only' or inventory.get('file_hashes_only') is not True:raise ValueError('Mapped official module inventory unavailable')
rows=inventory.get('modules')
if not isinstance(rows,list) or not 1<=len(rows)<=128:raise ValueError('Mapped official module bound')
present={}
for row in rows:
if not isinstance(row,dict) or not isinstance(row.get('basename'),str) or not re.fullmatch(r'[A-Za-z0-9_.-]{1,124}\.(?:dll|exe)',row['basename'],re.I):raise ValueError('Invalid mapped module filename')
name=row['basename'].casefold()
if name in present or type(row.get('bytes')) is not int or not 0<row['bytes']<=67108864:raise ValueError('Ambiguous mapped module identity')
_hash(row.get('sha256'));present[name]=row
pin=requested_by_name.get(name)
if pin is not None and (row['sha256'],row['bytes'])!=(pin['sha256'],pin['bytes']):raise ValueError('Mapped requested module changed')
if phase=='final':
if not set(requested_by_name)<=set(present):raise ValueError('Requested official modules are absent from final inventory')
game=present.get('wow.exe',{})
if (game.get('sha256'),game.get('bytes'))!=(loader['executable']['sha256'],loader['executable']['bytes']):raise ValueError('Final original game module identity differs')
def body(name,length,expected):
rows=[r for r in analysis.get('byte_evidence',[]) if r.get('name')==name]
if len(rows)!=1:raise ValueError('Ambiguous reviewed hook body')
try:raw=bytes.fromhex(rows[0]['file_body_hex'])
except (KeyError,TypeError,ValueError):raise ValueError('Reviewed hook body unavailable')
if len(raw)!=length or rows[0].get('bytes')!=length or rows[0].get('file_sha256')!=expected or hashlib.sha256(raw).hexdigest()!=expected:raise ValueError('Reviewed hook body hash differs')
return raw
predicate=body('special_wrapper_predicate',38,'2c3753e090a96b7eb0713147ce1375380a1e3b83442f602544f82a61a1239342')
originals={r['va']:r for r in loader.get('byte_evidence',[])};base=None
specs=(('read',0x648460,6,0x18dd,111,96,0x41bc,'14971d846d4211e84c9e90fe5d94df3d709b027aee30462b7280b9a42b4553a9'),
('close',0x648730,7,0x194c,42,33,0x41ec,'b15934539f7741171d94ef860deba08dd3ca6c6d65374e233df81231d890d35e'))
for name,entry,overwritten,rva,length,relocation,pointer_rva,file_hash in specs:
contract=observation.get('contracts',{}).get(name+'_hook')
if not isinstance(contract,dict) or contract.get('variant')!='transmogfix-ordinary-v1' or contract.get('verified') is not True:raise ValueError('Missing reviewed ordinary read/close hook contract')
current=_uint(contract.get('module_base'),positive=True)
if current%4096 or current+69632>2**32 or (base is not None and current!=base):raise ValueError('Hook runtime module base changed')
base=current
for key,value in dict(module_basename='transmogfix.dll',module_sha256=module['sha256'],module_image_size=69632,mapping_scope='pinned-private-runtime-module',
entry_va=hex(entry),hook_rva=hex(rva),predicate_rva='0x29bc',trampoline_pointer_rva=hex(pointer_rva),original_continuation_va=hex(entry+overwritten)).items():
if contract.get(key)!=value:raise ValueError('Ordinary hook code ownership or ABI recipe changed')
original=bytes.fromhex(originals[hex(entry)]['hex'])
if len(original)<overwritten:raise ValueError('Original overwritten instruction bytes unavailable')
detour=b'\xe9'+struct.pack('<I',(base+rva-entry-5)&0xffffffff)+b'\x90'*(overwritten-5)
if contract.get('entry_hex')!=detour.hex() or contract.get('runtime_entry_sha256')!=hashlib.sha256(detour+original[overwritten:]).hexdigest():raise ValueError('Runtime E9/NOP detour recipe differs')
runtime=bytearray(body(name+'_hook',length,file_hash))
if struct.unpack_from('<I',runtime,relocation)[0]!=0x10000000+pointer_rva:raise ValueError('Reviewed HIGHLOW relocation differs')
struct.pack_into('<I',runtime,relocation,base+pointer_rva)
if contract.get('runtime_hook_sha256')!=hashlib.sha256(runtime).hexdigest() or contract.get('runtime_predicate_sha256')!=hashlib.sha256(predicate).hexdigest():raise ValueError('Runtime rebased hook or predicate hash differs')
trampoline=_uint(contract.get('trampoline_va'),positive=True);size=overwritten+5
if trampoline+size>2**32:raise ValueError('Trampoline address overflow')
expected=original[:overwritten]+b'\xe9'+struct.pack('<I',(entry+overwritten-trampoline-size)&0xffffffff)
if contract.get('trampoline_hex')!=expected.hex():raise ValueError('Unknown or chained trampoline recipe')
tail='0b3abd13be3e35883ff1f95a5c0c3b844dfc8b4d0c47851e0660bafe8266172b' if name=='read' else hashlib.sha256(original[overwritten:]).hexdigest()
if contract.get('runtime_original_tail_sha256')!=tail:raise ValueError('Original unmodified hook tail differs')
if name=='read' and observation['contracts']['read'].get('runtime_entry_sha256')!=contract['runtime_entry_sha256']:raise ValueError('Read contract and detour hashes differ')
profile=dict(version=1,method=launch['method'],loader_sha256=launch['sha256'],loader_bytes=launch['bytes'],
pe_machine=launch['pe_machine'],pe_optional_magic=launch['pe_optional_magic'],arguments=launch['arguments'],
companion=launch['companion'],dll_manifest_sha256=launch['dll_manifest_sha256'],requested_modules=requested)
return base,profile
def validate_loaded_content(scan,observation,capture_bytes,loader_analysis,*,expected_client=None,block_analysis=None,transmog_analysis=None):
"""Validate a declared natural-read trace against captured public DBC bytes.
Pure validation cannot attest that an observer really ran. It verifies its
pinned contracts, identities, per-call returns and complete content coverage;
it never upgrades a supplied trace to independently reproduced runtime proof.
Equal archive candidates stay a set, with no invented backing archive.
"""
resolution=resolve_candidates(scan,expected_client=expected_client)
if any(r['status']=='blocked-archive-provenance' for r in resolution['tables']):raise ValueError('Incomplete candidate archive provenance')
if not isinstance(loader_analysis,dict) or loader_analysis.get('kind')!='installed-octo-read-only-static-loader-analysis' or loader_analysis.get('source_installation')!=resolution['source_installation']:
raise ValueError('Require matching reviewed loader analysis')
executable=loader_analysis.get('executable',{})
executable_hash=_hash(executable.get('sha256'))
if executable.get('machine')!='0x14c' or executable.get('image_base')!='0x400000':raise ValueError('Require reviewed PE32 loader identity')
image_bytes=_uint(executable.get('bytes'),positive=True)
if not isinstance(observation,dict) or type(observation.get('schema_version')) is not int or observation['schema_version']!=1 or observation.get('kind')!='octo-observed-dbc-content':raise ValueError('Require typed schema1 loaded-content observation')
mode=observation.get('capture_mode','per-read-v1')
if mode not in ('per-read-v1','mpq-block-fills-v1'):raise ValueError('Unknown observed-content capture mode')
block_mode=mode=='mpq-block-fills-v1'
read_variant=observation.get('read_contract','original-v1')
if read_variant not in ('original-v1','transmogfix-ordinary-v1'):raise ValueError('Unknown source read contract variant')
hook_mode=read_variant=='transmogfix-ordinary-v1'
if hook_mode and block_mode:raise ValueError('Hook-aware block capture is not reviewed')
if not block_mode and block_analysis is not None:raise ValueError('Block analysis requires explicit block capture mode')
if not hook_mode and transmog_analysis is not None:raise ValueError('Transmog analysis requires explicit ordinary read variant')
if observation.get('source_installation')!=resolution['source_installation'] or _hash(observation.get('scan_sha256'))!=resolution['scan_sha256'] or _hash(observation.get('loader_analysis_sha256'))!=canonical_sha256(loader_analysis):raise ValueError('Observed source, scan or loader identity changed')
identity=observation.get('client_identity')
if not isinstance(identity,dict) or _hash(identity.get('client_sha256'))!=executable_hash:raise ValueError('Observed executable differs from reviewed loader')
build,locale=identity.get('client_build'),identity.get('locale')
if build is not None and (not isinstance(build,str) or not re.fullmatch(r'[0-9]+(?:\.[0-9]+){2,3}',build)):raise ValueError('Invalid observed client build')
if locale is not None and (not isinstance(locale,str) or not re.fullmatch('[a-z]{2}[A-Z]{2}',locale)):raise ValueError('Invalid observed locale')
for key in ('client_sha256','client_build','locale'):
if resolution['client_identity'][key] is not None and identity.get(key)!=resolution['client_identity'][key]:raise ValueError('Observed client identity conflicts with source scan')
declared_locale=loader_analysis.get('observations',{}).get('declared_config_locale')
if locale is not None and declared_locale is not None and locale!=declared_locale:raise ValueError('Observed locale conflicts with reviewed declaration')
observer=observation.get('observer')
if not isinstance(observer,dict) or observer.get('pointer_bits')!=32 or type(observer.get('pointer_bits')) is not int:raise ValueError('Require explicit PE32 observer ABI')
_hash(observer.get('code_sha256'))
contracts=observation.get('contracts')
evidence=loader_analysis.get('byte_evidence')
allowed_extras={'actual_counts','block_fill'} if block_mode else {'actual_counts'}
if hook_mode:allowed_extras|={'read_hook','close_hook'}
if not isinstance(contracts,dict) or not set(LOADED_CONTENT_CONTRACTS)<=set(contracts) or set(contracts)-set(LOADED_CONTENT_CONTRACTS)-allowed_extras or not isinstance(evidence,list):raise ValueError('Missing reviewed open/read contracts')
def verify_prefix(address,contract,reviewed=None):
pinned=[r for r in (evidence if reviewed is None else reviewed) if r.get('va')==address]
if len(pinned)!=1 or not isinstance(contract,dict) or contract.get('entry_va')!=address or contract.get('verified') is not True:raise ValueError('Unverified or changed natural-call contract')
if _hash(contract.get('runtime_entry_sha256'))!=_hash(pinned[0].get('sha256')):raise ValueError('Runtime natural-call prefix differs from reviewed bytes')
try:prefix=bytes.fromhex(pinned[0]['hex'])
except (KeyError,TypeError,ValueError):raise ValueError('Malformed reviewed instruction bytes')
if len(prefix)!=pinned[0].get('bytes') or hashlib.sha256(prefix).hexdigest()!=pinned[0]['sha256']:raise ValueError('Reviewed instruction hash mismatch')
for name,(address,arguments) in LOADED_CONTENT_CONTRACTS.items():
contract=contracts[name]
if not (hook_mode and name=='read'):verify_prefix(address,contract)
elif not isinstance(contract,dict) or contract.get('entry_va')!=address or contract.get('verified') is not True:raise ValueError('Missing ordinary hooked read entry contract')
if contract.get('argument_bytes')!=arguments or type(contract.get('argument_bytes')) is not int:raise ValueError('Changed callee-pop contract')
hook_base,loader_profile=_validate_transmog_contract(observation,loader_analysis,transmog_analysis) if hook_mode else (None,None)
if block_mode:
if not isinstance(block_analysis,dict) or type(block_analysis.get('schema_version')) is not int or block_analysis['schema_version']!=1 or block_analysis.get('kind')!='installed-octo-read-only-static-block-analysis' or block_analysis.get('source_installation')!=resolution['source_installation'] or _hash(observation.get('block_analysis_sha256'))!=canonical_sha256(block_analysis):raise ValueError('Missing or changed reviewed MPQ block analysis')
block_exe=block_analysis.get('executable',{})
if not isinstance(block_exe,dict) or any(block_exe.get(key)!=executable.get(key) for key in ('sha256','machine','image_base')):raise ValueError('MPQ block analysis executable differs')
contract=contracts.get('block_fill');block_evidence=block_analysis.get('byte_evidence')
if not isinstance(contract,dict) or contract.get('verified') is not True or contract!=BLOCK_FILL_CONTRACT or block_analysis.get('block_fill_contract')!=BLOCK_FILL_CONTRACT or not isinstance(block_evidence,list):raise ValueError('Changed MPQ block-fill register/frame contract')
for address,hash_key in ((contract['entry_va'],'runtime_entry_sha256'),(contract['inner_function_va'],'runtime_inner_sha256'),(contract['outer_function_va'],'runtime_outer_sha256')):
verify_prefix(address,dict(entry_va=address,runtime_entry_sha256=contract[hash_key],verified=True),block_evidence)
count_contracts=contracts.get('actual_counts',[]);count_points={}
if not isinstance(count_contracts,list) or len(count_contracts)>2:raise ValueError('Bounded actual-count contracts required')
for contract in count_contracts:
if not isinstance(contract,dict) or contract.get('entry_va') not in ('0x648540','0x6484dd'):raise ValueError('Unknown actual-count observation point')
pc=contract['entry_va'];verify_prefix(pc,contract)
if pc in count_points or contract.get('register')!=('ecx' if pc=='0x648540' else 'esi'):raise ValueError('Actual-count register contract changed')
count_points[pc]=contract
captures=observation.get('captures')
if not isinstance(captures,list) or not 1<=len(captures)<=len(NAMES) or not isinstance(capture_bytes,dict):raise ValueError('Bounded captured-table set required')
rows=[];seen_tables=set();seen_files=set();seen_generations=set();total_bytes=0;total_reads=0;total_blocks=0
def call(row,arguments,generation):
if not isinstance(row,dict) or row.get('handle_generation')!=generation or type(row.get('handle_generation')) is not int:raise ValueError('Observed handle generation changed')
entry=_uint(row.get('entry_sp'),positive=True);returned=_uint(row.get('return_sp'),positive=True)
caller=_uint(row.get('return_address'),positive=True)
thread=_uint(row.get('thread_id'),positive=True)
if _uint(row.get('return_thread_id'),positive=True)!=thread or entry%4 or returned!=entry+4+arguments or not 0x401000<=caller<0x400000+image_bytes:raise ValueError('Natural-call stack, caller or thread contract failed')
def hooked_read(read,capture):
frame=read.get('hook_frame');h=read['entry_sp']
if read.get('read_contract')!='transmogfix-ordinary-v1' or not isinstance(frame,dict) or h<48:raise ValueError('Missing original nested hook frame')
expected=dict(hook_frame_pointer=h-4,original_entry_sp=h-44,original_frame_pointer=h-48,
saved_hook_frame_pointer=h-4,original_return_address=hook_base+0x1941,
original_return_sp=h-16,original_return_thread_id=read['thread_id'],original_result=1)
if any(type(frame.get(key)) is not int or frame[key]!=value for key,value in expected.items()):raise ValueError('Ordinary nested read frame or return differs')
arguments=frame.get('source_arguments');copied=frame.get('original_arguments_at_count')
if not isinstance(arguments,list) or not isinstance(copied,list) or len(arguments)!=6 or len(copied)!=6:raise ValueError('Missing six original hook arguments')
for value in arguments+copied:_uint(value)
# Original READ uses its initially-null fifth argument as temporary
# actual-count storage ([original EBP+24]) before COUNT 0x648540.
# All other copied arguments must still match the hook-entry values.
if (type(frame.get('actual_count_frame_offset')) is not int or frame['actual_count_frame_offset']!=24 or
copied[4]!=read['actual'] or any(arguments[i]!=copied[i] for i in (0,1,2,3,5))):raise ValueError('Original delegated read arguments or temporary count differ')
wrapper=_uint(capture['open'].get('wrapper_handle'),positive=True)
if (arguments[0]!=wrapper or not arguments[1] or arguments[1]+read['actual']>2**32 or arguments[2]!=read['requested'] or
arguments[3]!=read['actual_count_pointer'] or arguments[4]!=0 or type(read.get('file_type')) is not int or read['file_type'] not in (2,3)):
raise ValueError('Special, asynchronous or unrelated hook read is unsupported')
proof=read['actual_count_proof']
if proof.get('method')!='verified-count-pc' or proof.get('pc')!='0x648540':raise ValueError('Hooked MPQ read requires the verified nested actual-count PC')
def blocks(capture,raw,generation):
if capture.get('capture_method')!='mpq-block-fills-v1' or 'reads' in capture:raise ValueError('Block capture method must be explicit and separate from reads')
binding=capture.get('block_binding');call(binding,24,generation)
wrapper=_uint(binding.get('wrapper_handle'),positive=True);inner=_uint(binding.get('inner_handle'),positive=True)
if wrapper%4 or inner%4 or wrapper==inner or type(capture['open'].get('wrapper_handle')) is not int or capture['open']['wrapper_handle']!=wrapper:raise ValueError('Block wrapper does not own the selected opened file')
if binding['thread_id']!=capture['open']['thread_id'] or type(binding.get('result')) is not int or binding['result']!=1 or type(binding.get('file_type')) is not int or binding['file_type'] not in (2,3):raise ValueError('Block binding lacks a genuine completed MPQ read')
_uint(binding.get('requested'),positive=True);_uint(binding.get('actual_count_pointer'))
if binding['requested']>67108864 or type(binding.get('asynchronous_pointer')) is not int or binding['asynchronous_pointer']!=0:raise ValueError('Invalid asynchronous or oversized block binding')
rows=capture.get('blocks')
if not isinstance(rows,list) or not 1<=len(rows)<=100000:raise ValueError('Bounded nonempty MPQ fill trace required')
offset=0
for row in rows:
if not isinstance(row,dict) or row.get('observation_pc')!='0x65702d' or type(row.get('handle_generation')) is not int or row['handle_generation']!=generation or type(row.get('thread_id')) is not int or row['thread_id']!=binding['thread_id']:raise ValueError('MPQ fill PC, handle or thread ownership changed')
frame=_uint(row.get('frame_pointer'),positive=True);buffer=_uint(row.get('buffer_address'),positive=True)
actual=_uint(row.get('actual'),positive=True);requested=_uint(row.get('lower_requested'),positive=True)
if frame%4 or frame<52 or frame+24>=2**32 or buffer+actual>2**32 or not actual<=requested<=67108864:raise ValueError('MPQ fill buffer/count/frame bound')
if type(row.get('inner_owner')) is not int or row['inner_owner']!=inner or type(row.get('source_read_return')) is not int or row['source_read_return']!=0x64853b or type(row.get('asynchronous_pointer')) is not int or row['asynchronous_pointer']!=0:raise ValueError('MPQ fill source frame or owner differs')
if type(row.get('offset')) is not int or row['offset']!=offset or offset+actual>len(raw):raise ValueError('Overlapping, missing or oversized MPQ fill range')
if _hash(row.get('sha256'))!=hashlib.sha256(memoryview(raw)[offset:offset+actual]).hexdigest():raise ValueError('MPQ fill segment differs from captured bytes')
offset+=actual
if offset!=len(raw):raise ValueError('MPQ fill trace does not cover full DBC')
final=capture.get('final_read');call(final,24,generation)
outer_frame=_uint(final.get('outer_frame_pointer'),positive=True)
if outer_frame%4 or outer_frame+4!=final['entry_sp'] or type(final.get('source_frame_pointer')) is not int or final['source_frame_pointer']!=rows[-1]['frame_pointer'] or final['source_frame_pointer']>=outer_frame:raise ValueError('Final MPQ fill did not complete through its original outer frame')
if type(final.get('result')) is not int or final['result']!=1 or final['thread_id']!=binding['thread_id'] or type(final.get('wrapper_handle')) is not int or final['wrapper_handle']!=wrapper or type(final.get('inner_handle')) is not int or final['inner_handle']!=inner:raise ValueError('Final MPQ read failed or changed ownership')
return len(rows)
for capture in captures:
if not isinstance(capture,dict) or capture.get('table') not in NAMES:raise ValueError('Unknown captured table')
table=capture['table'];file=_relative_capture(capture.get('file'));generation=_uint(capture.get('handle_generation'),positive=True)
if table in seen_tables or file in seen_files or generation in seen_generations:raise ValueError('Duplicate captured table, file or handle generation')
seen_tables.add(table);seen_files.add(file);seen_generations.add(generation)
if capture.get('name')!='DBFilesClient\\'+table+'.dbc' or capture.get('finished') is not True or capture.get('seek_status')!='none-observed':raise ValueError('Incomplete, redirected or seek-ambiguous table observation')
raw=capture_bytes.get(file)
if not isinstance(raw,bytes) or not 20<=len(raw)<=67108864 or type(capture.get('bytes')) is not int or capture['bytes']!=len(raw) or _hash(capture.get('sha256'))!=hashlib.sha256(raw).hexdigest():raise ValueError('Captured DBC bytes/hash mismatch')
total_bytes+=len(raw)
if total_bytes>268435456:raise ValueError('Captured batch byte bound')
magic,count,fields,size,strings=struct.unpack_from('<4s4I',raw)
if magic!=b'WDBC' or not 1<=fields<=512 or count>100000 or size!=fields*4 or len(raw)!=20+count*size+strings:raise ValueError('Captured DBC schema/length mismatch')
ids=[struct.unpack_from('<I',raw,20+i*size)[0] for i in range(count)]
if len(set(ids))!=count:raise ValueError('Duplicate captured DBC row IDs')
call(capture.get('open'),8,generation)
read_count=0;block_count=0
if block_mode:
block_count=blocks(capture,raw,generation);total_blocks+=block_count
if total_blocks>250000:raise ValueError('Batch MPQ fill trace bound')
else:
if 'blocks' in capture or capture.get('capture_method','per-read-v1')!='per-read-v1':raise ValueError('Unexpected block evidence in per-read capture')
reads=capture.get('reads')
if not isinstance(reads,list) or not 1<=len(reads)<=100000:raise ValueError('Bounded nonempty read trace required')
read_count=len(reads);total_reads+=read_count
if total_reads>250000:raise ValueError('Batch read trace bound')
offset=0
for read in reads:
call(read,24,generation)
requested=_uint(read.get('requested'),positive=True);actual=_uint(read.get('actual'),positive=True)
if type(read.get('result')) is not int or read['result']!=1 or type(read.get('offset')) is not int or read['offset']!=offset or not actual<=requested<=67108864 or offset+actual>len(raw):raise ValueError('Failed, overlapping or incomplete natural read')
pointer=_uint(read.get('actual_count_pointer'))
proof=read.get('actual_count_proof')
if not isinstance(proof,dict) or type(proof.get('value')) is not int or proof['value']!=actual or proof.get('handle_generation')!=generation or type(proof.get('handle_generation')) is not int or proof.get('thread_id')!=read['thread_id'] or type(proof.get('thread_id')) is not int:raise ValueError('Missing correlated actual-read-count proof')
if proof.get('method')=='actual-count-pointer':
if not pointer or type(proof.get('pointer')) is not int or proof['pointer']!=pointer:raise ValueError('Actual-count pointer was absent or changed')
elif proof.get('method')=='verified-count-pc':
if proof.get('pc') not in count_points:raise ValueError('Unverified actual-count PC')
else:raise ValueError('Unknown actual-count proof method')
if hook_mode:hooked_read(read,capture)
elif 'hook_frame' in read:raise ValueError('Hook frame supplied without an explicit reviewed variant')
if _hash(read.get('sha256'))!=hashlib.sha256(memoryview(raw)[offset:offset+actual]).hexdigest():raise ValueError('Read segment differs from captured bytes')
offset+=actual
if offset!=len(raw):raise ValueError('Natural read trace does not cover full DBC')
matches=[dict(r) for group in resolution['tables'] if group['table']==table for r in group['candidates'] if (r['sha256'],r['rows'],r['fields'],r['bytes'])==(capture['sha256'],count,fields,len(raw))]
if not matches:raise ValueError('Loaded content has no exact pinned candidate match')
row=dict(table=table,sha256=capture['sha256'],bytes=len(raw),rows=count,fields=fields,read_count=read_count,
candidate_matches=matches,backing_archive=None,content_status='matched-observed-bytes',runtime_effective_independently_verified=False)
if block_mode:row.update(block_count=block_count,capture_method=mode)
rows.append(row)
if set(capture_bytes)!=seen_files:raise ValueError('Unused or missing captured byte payload')
result=dict(schema_version=1,kind='octo-loaded-content-validation',source_installation=resolution['source_installation'],
scan_sha256=resolution['scan_sha256'],observation_sha256=canonical_sha256(observation),loader_analysis_sha256=canonical_sha256(loader_analysis),
client_identity={key:identity.get(key) for key in ('client_sha256','client_build','locale')},observer_code_sha256=observer['code_sha256'],
validation_scope='declared-natural-read-trace-and-captured-bytes',trace_contracts_validated=True,captured_content_rehashed=True,
tables=sorted(rows,key=lambda r:r['table']),table_count=len(rows),read_count=total_reads,
runtime_observation_independently_reproduced=False,original_archives_rehashed=False,patch_precedence_verified=False,
postload_semantics_verified=False,converted=False,engine_loaded=False,gameplay_verified=False,
limits=['A structurally valid supplied trace is not independently reproduced execution evidence.',
'All exact content-equivalent candidate archives are retained; no backing archive or global lookup priority is inferred.',
'Captured source file bytes do not establish post-load hooks, destination engine loading or gameplay compatibility.'])
if block_mode:result.update(capture_mode=mode,block_count=total_blocks,block_analysis_sha256=canonical_sha256(block_analysis))
if hook_mode:
context={key:result[key] for key in ('source_installation','scan_sha256','client_identity')}
context.update(read_contract=read_variant,official_loader_profile_sha256=canonical_sha256(loader_profile))
result.update(read_contract=read_variant,transmog_analysis_sha256=canonical_sha256(transmog_analysis),ordinary_hook_contracts_validated=True,
official_loader_profile=loader_profile,official_loader_profile_sha256=canonical_sha256(loader_profile),analysis_context=context,
analysis_context_recipe=dict(version=2,dataset_prefix='observed-content:',hash='canonical-json-sha256',fields=list(context)))
return result
def inventory_loaded_content(scan,observation,capture_bytes,loader_analysis,*,expected_client=None,block_analysis=None,transmog_analysis=None):
"""Bridge validated observed bytes into the existing typed source model.
Only captured tables enter this partial analysis dataset. Unobserved archive
candidates never fill missing references. Separate observed tables with the
same pinned source context can later share the existing dependency_closure.
"""
validation=validate_loaded_content(scan,observation,capture_bytes,loader_analysis,expected_client=expected_client,block_analysis=block_analysis,transmog_analysis=transmog_analysis)
context=validation.get('analysis_context') or {key:validation[key] for key in ('source_installation','scan_sha256','client_identity')}
dataset='observed-content:'+canonical_sha256(context)
captures={r['table']:r for r in observation['captures']};inventories=[]
class CapturedDBCPath:
# Reuse the existing DBC decoder without a temporary file or another
# schema implementation. It needs only name and read_bytes().
def __init__(self,name,raw):self.name=name;self.raw=raw
def read_bytes(self):return self.raw
for row in validation['tables']:
table=row['table'];capture=captures[table]
source=dict(dataset=dataset,provenance='selected-by-pinned-evidence',**context,
content_sha256=row['sha256'],observation_sha256=validation['observation_sha256'],
loader_analysis_sha256=validation['loader_analysis_sha256'],selection_scope='observed-file-content-only',backing_archive=None)
if 'transmog_analysis_sha256' in validation:source['transmog_analysis_sha256']=validation['transmog_analysis_sha256']
inventory=inventory_table(table,DBC(CapturedDBCPath(table+'.dbc',capture_bytes[capture['file']])),source)
inventory['observed_content']=dict(status=row['content_status'],candidate_matches=row['candidate_matches'],
postload_semantics_verified=False)
inventories.append(inventory)
roots=[r['identity'] for inventory in inventories for r in inventory['records'] if r['identity'][1]]
closure=dependency_closure(inventories,roots)
observed={r['table'] for r in validation['tables']};missing={}
for table,ident in closure['missing']:missing.setdefault(table,[]).append(ident)
resolution=resolve_candidates(scan,expected_client=expected_client)
candidate_counts={r['table']:len(r['candidates']) for r in resolution['tables']}
blockers=[dict(table=table,missing_record_count=len(ids),
status='referenced-id-absent-from-observed-table' if table in observed else 'source-table-not-observed',
unresolved_candidate_count=candidate_counts.get(table,0)) for table,ids in sorted(missing.items())]
blockers.extend(dict(table=r['table'],status='observed-schema-unreviewed',fields=r['schema']['fields'])
for r in inventories if r['schema']['status']!='reviewed-disk-shape')
result=dict(schema_version=1,kind='octo-observed-partial-dependency-inventory',analysis_dataset=dataset,
source_installation=context['source_installation'],scan_sha256=context['scan_sha256'],client_identity=context['client_identity'],
validation=validation,inventories=inventories,declared_reference_closure=closure,blockers=blockers,
table_count=len(inventories),record_count=sum(len(r['records']) for r in inventories),
reference_count=sum(len(r['references']) for r in inventories),read_count=validation['read_count'],
dependency_complete=False,runtime_effective_verified=False,patch_precedence_verified=False,
postload_semantics_verified=False,converted=False,engine_loaded=False,gameplay_verified=False,
limits=['Only validated observed file bytes populate this partial source model; unresolved candidates are not imported.',
'Matching dataset identity permits an explicit analysis join, not a claim of common runtime state or post-load semantics.',
'Declared missing references remain blockers; complete client content, conversion, installation and gameplay are unverified.'])
if 'block_count' in validation:result.update(block_count=validation['block_count'],capture_mode=validation['capture_mode'])
if 'analysis_context' in validation:result.update(analysis_context=context,analysis_context_recipe=validation['analysis_context_recipe'])
return result
def observed_analysis_context(observed,validation,source_identity):
"""Check the shared analysis identity of an observed partial source model.
This verifies document consistency, not observer execution or post-load
semantics. Legacy three-field identities stay unchanged; an explicit hook
context must carry its complete versioned loader/module profile.
"""
documents=(observed,validation,source_identity)
if any(not isinstance(row,dict) for row in documents):raise ValueError('Observed analysis context requires objects')
keys=('source_installation','scan_sha256','client_identity')
context={key:validation.get(key) for key in keys}
_source_path(context['source_installation']);_hash(context['scan_sha256'])
client=context['client_identity']
if not isinstance(client,dict) or set(client)!={'client_sha256','client_build','locale'}:raise ValueError('Observed client identity shape differs')
_hash(client['client_sha256'])
if client['client_build'] is not None and (not isinstance(client['client_build'],str) or not re.fullmatch(r'[0-9]+(?:\.[0-9]+){2,3}',client['client_build'])):raise ValueError('Invalid observed context build')
if client['locale'] is not None and (not isinstance(client['locale'],str) or not re.fullmatch('[a-z]{2}[A-Z]{2}',client['locale'])):raise ValueError('Invalid observed context locale')
if any(any(row.get(key)!=value for key,value in context.items()) for row in (observed,source_identity)):raise ValueError('Observed source analysis identities differ')
markers={'read_contract','official_loader_profile','official_loader_profile_sha256','analysis_context','analysis_context_recipe',
'transmog_analysis_sha256','ordinary_hook_contracts_validated'}
hook=any(markers.intersection(row) for row in documents)
if hook:
if validation.get('read_contract')!='transmogfix-ordinary-v1' or validation.get('ordinary_hook_contracts_validated') is not True:raise ValueError('Incomplete ordinary hook analysis context')
profile=validation.get('official_loader_profile');profile_hash=_hash(validation.get('official_loader_profile_sha256'))
profile_keys={'version','method','loader_sha256','loader_bytes','pe_machine','pe_optional_magic','arguments','companion','dll_manifest_sha256','requested_modules'}
if (not isinstance(profile,dict) or set(profile)!=profile_keys or type(profile.get('version')) is not int or profile['version']!=1 or
profile.get('method')!='unmodified-pinned-official-loader' or profile_hash!=canonical_sha256(profile)):raise ValueError('Ordinary loader profile identity differs')
_hash(profile.get('loader_sha256'));_hash(profile.get('dll_manifest_sha256'))
pin=_hash(validation.get('transmog_analysis_sha256'))
if source_identity.get('transmog_analysis_sha256')!=pin:raise ValueError('Ordinary hook analysis pins differ')
context.update(read_contract='transmogfix-ordinary-v1',official_loader_profile_sha256=profile_hash)
recipe=dict(version=2,dataset_prefix='observed-content:',hash='canonical-json-sha256',fields=list(context))
if any(row.get('analysis_context')!=context or row.get('analysis_context_recipe')!=recipe for row in (observed,validation)):raise ValueError('Ordinary hook context recipe differs')
if any(source_identity.get(key)!=value for key,value in context.items()):raise ValueError('Inventory ordinary hook context differs')
# Redundant optional markers may not contradict their canonical owner.
for row in documents:
for key,value in (('read_contract',context['read_contract']),('official_loader_profile_sha256',profile_hash),('transmog_analysis_sha256',pin)):
if key in row and row[key]!=value:raise ValueError('Conflicting ordinary hook context marker')
dataset='observed-content:'+canonical_sha256(context)
if observed.get('analysis_dataset')!=dataset or source_identity.get('dataset')!=dataset:raise ValueError('Observed analysis dataset hash differs')
return context
def _hash(value):
if not isinstance(value,str) or not re.fullmatch('[0-9a-f]{64}',value):raise ValueError('Require a lowercase SHA256 identity')
return value
def _source_path(value):
if not isinstance(value,str) or not value.startswith('/') or '\\' in value or '\0' in value or '..' in PurePosixPath(value).parts or str(PurePosixPath(value))!=value:raise ValueError('Require a normalized absolute source installation path')
return value
def _archive(value):
if not isinstance(value,str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]{0,123}\.[mM][pP][qQ]',value):raise ValueError('Unsafe archive basename')
return value
def resolve_candidates(scan,evidence=None,expected_client=None):
"""Pure manifest resolution; never scan, rehash files, or infer load order.
Optional evidence schema1 pins canonical_sha256(scan), source_installation,
verified=true, and verification={method, artifact, sha256}. Its policy is
either selections={table:archive} or archive_load_order=[...] with an explicit
winner='first'/'last'. The latter must cover the entire scanned inventory.
Supplied evidence is not independently proved by this manifest-only tool.
"""
if not isinstance(scan,dict):raise ValueError('Require a scan manifest object')
source=_source_path(scan.get('source_installation'))
if expected_client is not None and source!=_source_path(str(expected_client)):raise ValueError('Scan belongs to a different source installation')
identity={key:scan.get(key) for key in ('client_sha256','client_build','locale')}
if identity['client_sha256'] is not None:_hash(identity['client_sha256'])
if identity['client_build'] is not None and (not isinstance(identity['client_build'],str) or not re.fullmatch(r'[0-9]+(?:\.[0-9]+){2,3}',identity['client_build'])):raise ValueError('Invalid declared client build')
if identity['locale'] is not None and (not isinstance(identity['locale'],str) or not re.fullmatch('[a-z]{2}[A-Z]{2}',identity['locale'])):raise ValueError('Invalid declared locale')
if 'reader_source_sha256' in scan:_hash(scan['reader_source_sha256'])
raw_archives=scan.get('archives');raw_candidates=scan.get('candidates')
if not isinstance(raw_archives,list) or len(raw_archives)>128 or not isinstance(raw_candidates,list) or len(raw_candidates)>128*len(NAMES):raise ValueError('Scan inventory bounds')
archives={}
for row in raw_archives:
if not isinstance(row,dict):raise ValueError('Invalid archive record')
name=_archive(row.get('file'))
if name in archives:raise ValueError('Duplicate archive identity')
if type(row.get('bytes')) is not int or not 0<=row['bytes']<2**63 or type(row.get('open_result')) is not int:raise ValueError('Invalid archive metadata')
if row.get('sha256') is not None:_hash(row['sha256'])
archives[name]=row
tables={name:[] for name in NAMES};seen=set();hash_schemas={}
for row in raw_candidates:
if not isinstance(row,dict) or row.get('table') not in tables:raise ValueError('Unknown candidate table')
table=row['table'];archive=_archive(row.get('archive'));key=(archive,table)
if row.get('path',archive+'/'+table+'.dbc')!=archive+'/'+table+'.dbc':raise ValueError('Candidate path differs from its safe archive/table identity')
if key in seen:raise ValueError('Duplicate archive/table candidate')
seen.add(key);sha=_hash(row.get('sha256'))
count,fields,size=(row.get(k) for k in ('rows','fields','bytes'))
if any(type(v) is not int for v in (count,fields,size)) or not 0<=count<=100000 or not 1<=fields<=512 or not 20+count*fields*4<=size<=67108864:raise ValueError('Invalid candidate DBC schema/bounds')
schema=(count,fields,size)
if sha in hash_schemas and hash_schemas[sha]!=schema:raise ValueError('Identical file hash has conflicting schema metadata')
hash_schemas[sha]=schema
tables[table].append(dict(archive=archive,path=archive+'/'+table+'.dbc',sha256=sha,rows=count,fields=fields,bytes=size))
scan_hash=canonical_sha256(scan);evidence_errors=[];policy=None;proof=None;declared={}
if evidence is not None:
if not isinstance(evidence,dict) or type(evidence.get('schema_version')) is not int or evidence['schema_version']!=1 or evidence.get('verified') is not True:raise ValueError('Require explicitly verified schema1 selection evidence')
if _source_path(evidence.get('source_installation'))!=source:evidence_errors.append('evidence source installation differs')
if _hash(evidence.get('scan_sha256'))!=scan_hash:evidence_errors.append('pinned scan manifest changed')
proof=evidence.get('verification')
if not isinstance(proof,dict) or proof.get('method') not in ('runtime-file-load-trace','reviewed-client-loader-source','reviewed-client-loader-analysis'):raise ValueError('Require a declared source-backed verification method')
artifact=proof.get('artifact')
if not isinstance(artifact,str) or not artifact or artifact=='.' or '\\' in artifact or '\0' in artifact or PurePosixPath(artifact).is_absolute() or '..' in PurePosixPath(artifact).parts or str(PurePosixPath(artifact))!=artifact:raise ValueError('Unsafe verification artifact path')
proof=dict(method=proof['method'],artifact=artifact,sha256=_hash(proof.get('sha256')))
declared={key:evidence.get(key) for key in ('client_sha256','client_build','locale')}
if declared['client_sha256'] is not None:_hash(declared['client_sha256'])
if declared['client_build'] is not None and (not isinstance(declared['client_build'],str) or not re.fullmatch(r'[0-9]+(?:\.[0-9]+){2,3}',declared['client_build'])):raise ValueError('Invalid evidence client build')
if declared['locale'] is not None and (not isinstance(declared['locale'],str) or not re.fullmatch('[a-z]{2}[A-Z]{2}',declared['locale'])):raise ValueError('Invalid evidence locale')
for key,value in identity.items():
if value is not None and declared.get(key) is not None and value!=declared[key]:evidence_errors.append('evidence '+key+' differs')
if ('selections' in evidence)==('archive_load_order' in evidence):raise ValueError('Choose explicit table selections or explicit verified archive order')
if 'selections' in evidence:
policy=evidence['selections']
if not isinstance(policy,dict) or not policy or any(k not in tables for k in policy):raise ValueError('Invalid table selection policy')
for archive in policy.values():_archive(archive)
else:
order=evidence['archive_load_order'];winner=evidence.get('winner')
if not isinstance(order,list) or not order or len(order)>128 or winner not in ('first','last'):raise ValueError('Require bounded verified archive order and explicit winner')
for archive in order:_archive(archive)
if len(set(order))!=len(order):raise ValueError('Duplicate archive load-order identity')
if set(order)!=set(archives):evidence_errors.append('verified archive order does not match scanned inventory')
policy={}
for table,rows in tables.items():
ordered=[name for name in order if any(r['archive']==name for r in rows)]
if ordered:policy[table]=ordered[0 if winner=='first' else -1]
rows=[]
for table,candidates in sorted(tables.items()):
candidates=sorted(candidates,key=lambda r:(r['archive'],r['sha256']))
problems=[];selected=None
for candidate in candidates:
archive=archives.get(candidate['archive'])
if archive is None:problems.append('candidate archive absent from inventory')
elif archive['open_result']!=0:problems.append('candidate archive was not readable')
elif archive.get('sha256') is None:problems.append('candidate archive hash missing')
if not candidates:status='blocked-missing-candidate'
elif problems:status='blocked-archive-provenance'
elif evidence_errors:status='blocked-evidence-drift';problems+=evidence_errors
elif policy is not None and table in policy:
selected=next((r for r in candidates if r['archive']==policy[table]),None)
if selected is None:status='blocked-selected-candidate-missing';problems.append('selected archive/table is absent')
else:status='selected-by-pinned-evidence'
elif len(candidates)==1:status='single-candidate-unverified'
elif len({r['sha256'] for r in candidates})==1:status='agreement-within-scanned-set'
else:status='blocked-ambiguous-candidates'
rows.append(dict(table=table,status=status,candidates=candidates,selected=selected,problems=sorted(set(problems)),runtime_effective_independently_verified=False))
return dict(schema_version=1,kind='octo-manifest-source-resolution',source_installation=source,client_identity=identity,
scan_sha256=scan_hash,evidence_sha256=canonical_sha256(evidence) if evidence is not None else None,
supplied_verification=proof,evidence_declared_identity=declared,evidence_errors=evidence_errors,
validation_scope='manifest-only',files_rehashed=False,verification_artifact_rehashed=False,staging_revalidation_required=True,
tables=rows,limits=['Candidate ordering in this report is presentation only, never archive priority.',
'Content agreement applies only within the scanned candidate set; it is not runtime-effective proof.',
'Supplied verified evidence is hash-pinned input, not independently reproduced by this resolver.',
'Client executable/build/locale remain unknown when absent from the scan; evidence declarations are separate.',
'Before staging, rehash original archives, extracted DBCs and verification artifacts, validate DBC schema and source identity.',
'No extraction, conversion, client installation or gameplay compatibility is established.'])
def digest(path):
h = hashlib.sha256()
with path.open('rb') as f:
for block in iter(lambda: f.read(1024 * 1024), b''): h.update(block)
return h.hexdigest()
def _public_json(path):
if not path.is_file() or path.stat().st_size>16777216:raise ValueError('Require bounded existing public JSON input')
def unique(pairs):
result={}
for key,value in pairs:
if key in result:raise ValueError('Duplicate JSON object field')
result[key]=value
return result
return json.loads(path.read_text(),object_pairs_hook=unique)
def _compact(value):
return (json.dumps(value,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False)+'\n').encode()
def validate_loaded_manifest(scan_path,observation_path,captured_root,output,*,loader_analysis_path=None,expected_client=None,include_inventory=False,block_analysis_path=None,transmog_analysis_path=None):
"""Read existing public capture files only; no source archives or client access."""
scan_path=Path(scan_path);observation_path=Path(observation_path);captured_root=Path(captured_root);output=Path(output)
loader_analysis_path=Path(loader_analysis_path or ROOT/'docs/evidence/data/octo-loader-static.json')
root=captured_root.resolve();destination=output.resolve();staging=output.with_name(output.name+'.staging')
if captured_root.is_symlink() or not captured_root.is_dir() or not root.is_relative_to(ROOT/'runtime'):raise ValueError('Require an existing runtime capture directory')
if not destination.is_relative_to(ROOT/'runtime') or output.suffix!='.json' or not output.parent.is_dir() or output.exists() or output.is_symlink() or staging.exists() or staging.is_symlink():raise ValueError('Require a new runtime JSON output without existing staging')
inputs={name:(path,_public_json(path),digest(path)) for name,path in (('scan',scan_path),('observation',observation_path),('loader',loader_analysis_path))}
observation=inputs['observation'][1];captures=observation.get('captures') if isinstance(observation,dict) else None
if isinstance(observation,dict) and observation.get('capture_mode')=='mpq-block-fills-v1':
path=Path(block_analysis_path or ROOT/'docs/evidence/data/octo-file-block-static.json')
inputs['block_analysis']=(path,_public_json(path),digest(path))
elif block_analysis_path is not None:raise ValueError('Block analysis requires explicit block capture mode')
if isinstance(observation,dict) and observation.get('read_contract')=='transmogfix-ordinary-v1':
path=Path(transmog_analysis_path or ROOT/'docs/evidence/data/octo-transmog-read-contract.json')
inputs['transmog_analysis']=(path,_public_json(path),digest(path))
elif transmog_analysis_path is not None:raise ValueError('Transmog analysis requires explicit ordinary read variant')
if not isinstance(captures,list) or not 1<=len(captures)<=len(NAMES):raise ValueError('Bounded capture manifest required')
payloads={};paths={};total=0
for capture in captures:
if not isinstance(capture,dict):raise ValueError('Invalid capture entry')
relative=_relative_capture(capture.get('file'));path=root/relative
if any(part.is_symlink() for part in (path,*path.parents)) or not path.resolve().is_relative_to(root) or not path.is_file() or not 20<=path.stat().st_size<=67108864:raise ValueError('Require regular bounded DBC capture inside runtime root')
total+=path.stat().st_size
if total>268435456:raise ValueError('Captured batch byte bound')
if relative in payloads:raise ValueError('Duplicate capture path')
payloads[relative]=path.read_bytes();paths[relative]=path
processor=inventory_loaded_content if include_inventory else validate_loaded_content
result=processor(inputs['scan'][1],observation,payloads,inputs['loader'][1],expected_client=expected_client,
block_analysis=inputs['block_analysis'][1] if 'block_analysis' in inputs else None,
transmog_analysis=inputs['transmog_analysis'][1] if 'transmog_analysis' in inputs else None)
# Publication is only after a second physical pass over every existing input.
if any(digest(path)!=sha for path,_,sha in inputs.values()) or any(digest(path)!=hashlib.sha256(payloads[name]).hexdigest() for name,path in paths.items()):raise ValueError('Observation inputs changed before publication')
result['input_file_sha256']={name:sha for name,(_,_,sha) in inputs.items()};result['second_input_pass_verified']=True
with staging.open('xb') as stream:stream.write(_compact(result))
staging.chmod(0o600)
if digest(staging)!=hashlib.sha256(_compact(result)).hexdigest():raise ValueError('Staged loaded-content report changed')
os.link(staging,output)
return result
def _publish_inventory(staging,output,rows):
"""Exclusive directory; only the final atomic manifest link means complete.
Staging files remain available on success or failure. Hard links neither
overwrite files nor duplicate their bytes. A partial output directory must
not be treated as complete while its final manifest is absent.
"""
output.mkdir(mode=0o700)
for row in rows:
target=output/row['path'];target.parent.mkdir(mode=0o700,exist_ok=True)
os.link(staging/row['path'],target)
for row in rows:
path=output/row['path']
if path.stat().st_size!=row['output_bytes'] or digest(path)!=row['output_sha256']:raise ValueError('Published candidate report changed before final manifest')
os.link(staging/'manifest.json',output/'manifest.json')
def inventory_manifest(scan_path,extracted_root,output,*,expected_client=None,spell_dbd=None):
"""Inventory existing extracted candidates independently, without selecting.
Input archive hashes are declared provenance only. This verifies extracted
DBC bytes/schema and converter inputs before publishing compact reports;
original archives and effective patch order require separate staging checks.
"""
scan_path=Path(scan_path);extracted_root=Path(extracted_root);output=Path(output)
if extracted_root.is_symlink() or not extracted_root.is_dir():raise ValueError('Require an existing non-symlink extracted root')
source_root=extracted_root.resolve();destination=output.resolve();staging=output.with_name(output.name+'.staging')
if not destination.is_relative_to(ROOT/'runtime') or destination==ROOT/'runtime' or not output.parent.is_dir() or output.exists() or output.is_symlink() or staging.exists() or staging.is_symlink():
raise ValueError('Require a new runtime output directory with no existing staging or symlink')
if destination.is_relative_to(source_root) or source_root.is_relative_to(destination):raise ValueError('Keep extracted source and inventory output directories separate')
scan=_public_json(scan_path);resolution=resolve_candidates(scan,expected_client=expected_client)
if not scan['candidates']:raise ValueError('Require at least one extracted candidate')
if any(row['status']=='blocked-archive-provenance' for row in resolution['tables']):raise ValueError('Candidate archive provenance is incomplete or unreadable in the source manifest')
spell_dbd=Path(spell_dbd) if spell_dbd is not None else Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/Spell.dbd'
code_inputs={'octo_client_data.py':Path(__file__).resolve(),'turtle_data.py':Path(__file__).resolve().with_name('turtle_data.py'),'Spell.dbd':spell_dbd.resolve()}
code_hashes={name:digest(path) for name,path in code_inputs.items()};scan_raw_hash=digest(scan_path)
# A manifest change between initial parsing and pinning must not silently
# bind reports to different input bytes.
if canonical_sha256(_public_json(scan_path))!=resolution['scan_sha256']:raise ValueError('Source manifest changed while pinning inputs')
converter_identity=canonical_sha256(code_hashes);rows=[];total=0
staging.mkdir(mode=0o700)
def candidate_path(row):
archive=source_root/row['archive'];path=archive/(row['table']+'.dbc')
if archive.is_symlink() or path.is_symlink() or not path.resolve().is_relative_to(source_root) or not path.is_file():raise ValueError('Candidate must be an existing regular file inside extracted root without symlinks')
return path
def checked_dbc(row):
table=DBC(candidate_path(row))
if (table.digest(),table.count,table.fields,len(table.bytes))!=(row['sha256'],row['rows'],row['fields'],row['bytes']):raise ValueError('Extracted candidate hash/schema/count/size differs from pinned manifest: '+row['archive']+'/'+row['table'])
return table
statuses={row['table']:row['status'] for row in resolution['tables']}
for row in sorted(scan['candidates'],key=lambda r:(r['archive'],r['table'])):
table=checked_dbc(row)
candidate_identity=dict(scan_sha256=resolution['scan_sha256'],archive=row['archive'],table=row['table'],sha256=row['sha256'],converter_identity=converter_identity)
provenance=dict(dataset='candidate:'+canonical_sha256(candidate_identity),provenance='candidate-unverified',
source_installation=resolution['source_installation'],candidate=candidate_identity,
client_identity=resolution['client_identity'],candidate_selection_status=statuses[row['table']])
result=inventory_table(row['table'],table,provenance)
relative=Path(row['archive'])/(row['table']+'.inventory.json');target=staging/relative
target.parent.mkdir(mode=0o700,exist_ok=True);raw=_compact(result);total+=len(raw)
if total>2147483648:raise ValueError('Candidate inventory batch exceeds 2GiB output bound')
with target.open('xb') as stream:stream.write(raw)
target.chmod(0o600)
rows.append(dict(archive=row['archive'],table=row['table'],candidate_sha256=row['sha256'],path=relative.as_posix(),
output_sha256=hashlib.sha256(raw).hexdigest(),output_bytes=len(raw),records=len(result['records']),references=len(result['references']),
assets=len(result['assets']),semantic_notes=len(result['semantic_notes']),schema_status=result['schema']['status'],
blocked_records=sum(r['status'].startswith('blocked-') for r in result['records']),selection_status=statuses[row['table']],
runtime_effective_verified=False,converted=False,engine_loaded=False))
# Re-read the actual files and all converter inputs, not merely stat/mtime.
for row in scan['candidates']:checked_dbc(row)
for row in rows:
path=staging/row['path']
if path.stat().st_size!=row['output_bytes'] or digest(path)!=row['output_sha256']:raise ValueError('Staged candidate report changed before publication')
if digest(scan_path)!=scan_raw_hash or canonical_sha256(_public_json(scan_path))!=resolution['scan_sha256'] or any(digest(path)!=code_hashes[name] for name,path in code_inputs.items()):raise ValueError('Scan or converter inputs changed during candidate inventory')
counts={status:sum(row['schema_status']==status for row in rows) for status in sorted({row['schema_status'] for row in rows})}
result=dict(schema_version=1,kind='octo-extracted-candidate-dependency-batch',source_installation=resolution['source_installation'],
client_identity=resolution['client_identity'],scan_sha256=resolution['scan_sha256'],scan_file_sha256=scan_raw_hash,
converter_input_sha256=code_hashes,converter_identity=converter_identity,source_candidates=len(rows),
record_count=sum(row['records'] for row in rows),reference_count=sum(row['references'] for row in rows),
asset_reference_count=sum(row['assets'] for row in rows),total_candidate_output_bytes=total,schema_status_counts=counts,candidates=rows,
verification=dict(extracted_candidates_rehashed=True,extracted_schema_count_size_verified=True,second_input_pass_verified=True,
staged_outputs_rehashed=True,converter_inputs_rehashed=True,original_archives_rehashed=False,
patch_precedence_verified=False,client_executable_rehashed=False),
publication=dict(completion_marker='manifest.json',directory_appearance_is_not_completion=True,staging_retained=True),
runtime_effective_verified=False,dependency_complete=False,converted=False,engine_loaded=False,installed=False,
limits=['Every archive/table candidate is independent; no ambiguous records are merged and no effective winner is selected.',
'Counts include repeated source IDs across distinct archive candidates; they are not unique effective content counts.',
'Archives, client executable identity, locale and build are declared or unknown from the input scan, not newly verified.',
'Before content staging rehash original archives and verify effective patched data selection, locale and client identity.',
'Only declared reviewed relationships are indexed; blocked shapes, opaque fields, missing dependencies and assets require further work.',
'This candidate analysis does not extract, convert, install, grant content or establish actual engine/gameplay compatibility.'])
manifest=staging/'manifest.json'
with manifest.open('xb') as stream:stream.write(_compact(result))
manifest.chmod(0o600)
if output.exists() or output.is_symlink():raise ValueError('Output appeared before publication; preserve staging')
_publish_inventory(staging,output,rows)
return result
def build_reader(source):
files = [source / (n + '.c') for n in ('common', 'explode', 'extract', 'huffman', 'mpq', 'wave')]
inputs = sorted(source.glob('*.h')) + files
fingerprint = hashlib.sha256(b''.join(p.read_bytes() for p in inputs)).hexdigest()
out = ROOT / 'build/octo-data'; out.mkdir(parents=True, exist_ok=True)
lib = out / 'libmpq-readonly.so'; marker = out / 'source.sha256'
if not lib.exists() or not marker.exists() or marker.read_text() != fingerprint:
subprocess.run(['cc', '-shared', '-fPIC', '-O2', '-D_FILE_OFFSET_BITS=64', '-o', str(lib), *map(str, files), '-lz', '-lbz2'], check=True, timeout=60)
marker.write_text(fingerprint)
api = C.CDLL(str(lib))
signatures = {
'archive_open': [C.POINTER(C.c_void_p), C.c_char_p, C.c_int64],
'archive_close': [C.c_void_p],
'file_number': [C.c_void_p, C.c_char_p, C.POINTER(C.c_uint32)],
'file_size_unpacked': [C.c_void_p, C.c_uint32, C.POINTER(C.c_int64)],
'file_read': [C.c_void_p, C.c_uint32, C.c_void_p, C.c_int64, C.POINTER(C.c_int64)],
}
for name, args in signatures.items():
f = getattr(api, 'libmpq__' + name); f.argtypes = args; f.restype = C.c_int32
return api, fingerprint
def read_member(api, handle, name):
index = C.c_uint32()
result = api.libmpq__file_number(handle, name.encode('ascii'), C.byref(index))
if result == -10: return None
if result: raise ValueError(f'MPQ lookup failed: {result}')
size = C.c_int64()
if api.libmpq__file_size_unpacked(handle, index, C.byref(size)) or not 20 <= size.value <= 67108864:
raise ValueError('DBC member size invalid')
data = C.create_string_buffer(size.value); actual = C.c_int64()
result = api.libmpq__file_read(handle, index, data, size, C.byref(actual))
if result or actual.value != size.value: raise ValueError(f'MPQ read failed: {result}')
return data.raw
def compare(candidate, baseline):
if not baseline.exists(): return {'status': 'no_local_comparison_table'}
other = DBC(baseline)
if other.fields != candidate.fields: return {'status': 'schema_width_differs', 'baseline_fields': other.fields}
ids, old = set(candidate.by_id), set(other.by_id)
changed = [i for i in sorted(ids & old) if candidate.by_id[i] != other.by_id[i]]
# String-offset equality/difference alone does not establish string semantics.
return {'status': 'raw_comparison_only', 'baseline_sha256': other.digest(),
'identical_file': candidate.digest() == other.digest(),
'added_ids': sorted(ids - old), 'removed_ids': sorted(old - ids),
'changed_raw_row_ids': changed,
'string_block_identical': candidate.strings == other.strings}
def summary(report):
# Keep full ID deltas in the regenerable private manifest, with a compact
# version-controlled provenance report instead of thousands of raw IDs.
result = json.loads(json.dumps(report))
result['full_manifest_sha256'] = hashlib.sha256((json.dumps(report, indent=2) + '\n').encode()).hexdigest()
for row in result['candidates']:
delta = row['comparison_to_installed_turtle']
for key in ('added_ids', 'removed_ids', 'changed_raw_row_ids'):
if key in delta: delta[key + '_count'] = len(delta.pop(key))
return result
def scan(client, output, comparison, source, names=NAMES):
if not output.resolve().is_relative_to(ROOT) or output.resolve().is_relative_to(client.resolve()):
raise ValueError('Extraction output must stay inside gateway, outside the client')
api, fingerprint = build_reader(source)
archives = sorted(p for p in (client / 'Data').iterdir() if p.is_file() and p.suffix.lower() == '.mpq')
if not archives or len(archives) > 128: raise ValueError('Archive inventory bound')
output.mkdir(parents=True, exist_ok=True)
report = {'source_installation': str(client.resolve()), 'reader_source_sha256': fingerprint,
'effective_patch_order_verified': False, 'archives': [], 'candidates': [],
'limits': ['Each archive is inspected independently; no arbitrary last-patch-wins policy.',
'Client DBCs do not contain complete server-authoritative item stats.',
'Raw row comparison is not semantic equivalence; strings and enums need schema conversion.',
'No live Octo access or client modifications; no maps converted.']}
for archive in archives:
before = archive.stat()
handle = C.c_void_p(); result = api.libmpq__archive_open(C.byref(handle), str(archive).encode(), 0)
row = {'file': archive.name, 'bytes': archive.stat().st_size, 'open_result': result}
report['archives'].append(row)
if result: continue
try:
for name in names:
data = read_member(api, handle, 'DBFilesClient\\' + name + '.dbc')
if data is None: continue
target = output / archive.name / (name + '.dbc'); target.parent.mkdir(exist_ok=True)
target.write_bytes(data); table = DBC(target)
report['candidates'].append({'table': name, 'archive': archive.name, 'sha256': table.digest(),
'rows': table.count, 'fields': table.fields, 'bytes': len(data),
'comparison_to_installed_turtle': compare(table, comparison / (name + '.dbc'))})
finally: api.libmpq__archive_close(handle)
if any(c['archive'] == archive.name for c in report['candidates']): row['sha256'] = digest(archive)
after = archive.stat()
if (before.st_size,before.st_mtime_ns)!=(after.st_size,after.st_mtime_ns):
raise ValueError('Source archive changed during extraction; do not select mixed versions')
(output / 'manifest.json').write_text(json.dumps(report, indent=2) + '\n')
(output / 'summary.json').write_text(json.dumps(summary(report), indent=2) + '\n')
print(f"Read {len(report['candidates'])} DBC candidates from {len(archives)} local Octo archives; patch precedence remains unverified.")
return report
if __name__ == '__main__':
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--client', type=Path, default=Path.home() / 'Games/octo/drive_c/Octowow')
p.add_argument('--output', type=Path, default=ROOT / 'runtime/octo-client-data')
p.add_argument('--comparison', type=Path, default=Path('/mnt/Games/Games/TurtleWoW/dbc'))
p.add_argument('--libmpq-source', type=Path, default=Path.home() / 'Servers/tortoise-wow/dep/libmpq/libmpq')
modes=p.add_mutually_exclusive_group()
modes.add_argument('--resolve-manifest',type=Path,help='Dry-run existing candidate manifest only; no scan, reader build or client writes')
modes.add_argument('--inventory-manifest',type=Path,help='Inventory all existing extracted candidates independently; never select effective data')
modes.add_argument('--validate-loaded-content',type=Path,help='Validate an existing declared natural-read trace and captured public DBC bytes; never launch or inspect a client')
modes.add_argument('--inventory-loaded-content',type=Path,help='Build a partial typed dependency inventory from validated captured bytes only; unresolved tables remain blockers')
p.add_argument('--selection-evidence',type=Path,help='Optional explicitly verified, hash-pinned selection or archive-order evidence')
p.add_argument('--extracted-root',type=Path,help='Existing per-archive extracted DBC root, required by --inventory-manifest')
p.add_argument('--spell-dbd',type=Path,help='Reviewed Spell DBD input to hash-pin with candidate inventory')
p.add_argument('--scan-manifest',type=Path,help='Pinned existing source scan for loaded-content validation or inventory')
p.add_argument('--captured-root',type=Path,help='Existing runtime directory containing observed DBC byte captures')
p.add_argument('--loader-analysis',type=Path,help='Reviewed PE32 static loader anchor for loaded-content validation or inventory')
p.add_argument('--block-analysis',type=Path,help='Separate reviewed MPQ fill anchor, only for explicit block capture mode')
p.add_argument('--transmog-analysis',type=Path,help='Reviewed ordinary transmog read/close hook anchor, only for explicit per-read variant')
a = p.parse_args()
if a.validate_loaded_content or a.inventory_loaded_content:
if not a.scan_manifest or not a.captured_root or a.selection_evidence or a.extracted_root or a.spell_dbd:p.error('Loaded-content validation requires --scan-manifest and --captured-root, without selection/inventory options')
try:report=validate_loaded_manifest(a.scan_manifest,a.validate_loaded_content or a.inventory_loaded_content,a.captured_root,a.output,loader_analysis_path=a.loader_analysis,expected_client=str(a.client.resolve()),include_inventory=bool(a.inventory_loaded_content),block_analysis_path=a.block_analysis,transmog_analysis_path=a.transmog_analysis)
except (ValueError,TypeError,KeyError,OSError) as error:p.error(str(error))
if a.inventory_loaded_content:print('Observed partial dependency inventory:',report['table_count'],'tables;',report['record_count'],'records;',report['reference_count'],'declared links;',len(report['blockers']),'blocker groups; no unresolved candidate imports or conversion/gameplay claim.')
else:print('Declared natural content trace:',report['table_count'],'tables;',report['read_count'],'outer reads;',report.get('block_count',0),'MPQ fills; exact candidate content matches; no inferred backing archive, independent runtime proof, conversion or gameplay claim.')
elif a.scan_manifest or a.captured_root or a.loader_analysis or a.block_analysis or a.transmog_analysis:p.error('Loaded-content analysis options require a loaded-content mode')
elif a.inventory_manifest:
if not a.extracted_root or a.selection_evidence:p.error('Inventory requires --extracted-root and does not accept --selection-evidence')
try:report=inventory_manifest(a.inventory_manifest,a.extracted_root,a.output,expected_client=str(a.client.resolve()),spell_dbd=a.spell_dbd)
except (ValueError,TypeError,KeyError,OSError) as error:p.error(str(error))
print('Independent extracted-candidate inventory:',report['source_candidates'],'candidates;',report['record_count'],'repeated-source records;',report['reference_count'],'declared links;',json.dumps(report['schema_status_counts'],sort_keys=True),'; archives/effective selection/conversion/engine loading not verified.')
elif a.extracted_root or a.spell_dbd:p.error('--extracted-root and --spell-dbd require --inventory-manifest')
elif a.resolve_manifest:
output=a.output.resolve()
if not output.is_relative_to(ROOT/'runtime') or output.suffix!='.json' or output.exists() or a.output.is_symlink() or not output.parent.is_dir():p.error('Resolution requires a new runtime JSON output with an existing parent')
try:report=resolve_candidates(_public_json(a.resolve_manifest),_public_json(a.selection_evidence) if a.selection_evidence else None,str(a.client.resolve()))
except (ValueError,TypeError,KeyError) as error:p.error(str(error))
output.write_text(json.dumps(report,ensure_ascii=False,sort_keys=True,indent=2)+'\n');output.chmod(0o600)
counts={status:sum(row['status']==status for row in report['tables']) for status in sorted({row['status'] for row in report['tables']})}
print('Manifest-only source resolution:',json.dumps(counts,sort_keys=True),'; files not rehashed; staging verification required.')
elif a.selection_evidence:p.error('--selection-evidence requires --resolve-manifest')
else:scan(a.client, a.output, a.comparison, a.libmpq_source)