Files
WoW-Hybrid-gateway/ops/casc_asset_package.py

1165 lines
80 KiB
Python

#!/usr/bin/env python3
"""Offline additive CASC asset-package primitives for pinned Forever70334 data.
Staging only: no client launch, storage mutation, downloads or schema changes.
The v2 ROOT group layout is pinned to CascLib CaptureRootGroup(58221+).
"""
from collections import defaultdict
import bisect
import hashlib
import re
import struct
import zlib
NO_NAME_HASH=0x10000000
MAX_ROOT_BYTES=134217728
MAX_ROOT_RECORDS=5000000
MAX_GROUPS=65536
# Match the existing 65,536-slot registry ceiling; native4096-byte encoding
# pages and the smaller per-index-bucket write bound remain unchanged.
MAX_ASSET_BATCH=65536
def reviewed_encoding_spec(spec):
# Exact original70334 ROOT790857/TEX0790860 CFT controls. Their repeated
# 256KiB Z blocks use the existing standard BLTE encoder; this does not
# admit other units, modes, sizes, or generalized ESpec grammar.
if isinstance(spec, str) and spec == 'b:{256K*=z}':
return spec.encode('ascii')
if not isinstance(spec,str)or len(spec)>16384 or not(spec=='n'or re.fullmatch(r'b:\{(?:[1-9][0-9]{0,9}=[nz],){0,1023}\*=[nz]\}',spec)):
raise ValueError('Reviewed plaintext encoding spec required')
return spec.encode('ascii')
def allocate_asset_ids(native_root,paths,registry=None):
"""Extend a pinned content registry without renumbering existing assets.
Removed paths remain reserved for future packages. Sorting is used only for
newly seen paths, never to recompute old IDs. This allocates FileDataIDs,
not item IDs, display IDs or native resource-group identifiers.
"""
import copy
root=root_groups(native_root)
if not isinstance(paths,list)or not 1<=len(paths)<=MAX_ASSET_BATCH:
raise ValueError('Bounded distinct asset paths required')
def valid_path(path):
return (isinstance(path,str)and 1<=len(path)<=254 and
re.fullmatch(r'[a-z0-9_./-]+',path)and
all(p not in('','.','..')for p in path.split('/')))
if any(not valid_path(p)for p in paths):raise ValueError('Canonical relative asset path required')
if len(set(paths))!=len(paths):raise ValueError('Distinct asset paths required')
result=copy.deepcopy(registry)if registry is not None else dict(
native_root_md5=root['root_md5'],max_native_file_data_id=root['max_file_data_id'],slots={})
if(not isinstance(result,dict)or set(result)!={'native_root_md5','max_native_file_data_id','slots'}or
result['native_root_md5']!=root['root_md5']or
type(result['max_native_file_data_id'])is not int or
result['max_native_file_data_id']!=root['max_file_data_id']or not isinstance(result['slots'],dict)):
raise ValueError('Pinned native asset registry required')
slots=result['slots'];values=list(slots.values());base=root['max_file_data_id']
if(len(slots)>65536 or any(not valid_path(p)for p in slots)or
any(type(v)is not int or not base<v<=0xffffffff for v in values)or
len(set(values))!=len(values)):
raise ValueError('Asset registry collision or bound')
next_id=max([base,*values])
for path in sorted(set(paths)-slots.keys()):
next_id+=1
if next_id>0xffffffff:raise ValueError('FileDataID allocation overflow')
slots[path]=next_id
if len(slots)>65536:raise ValueError('Asset registry count bound')
return result
def download_layout(raw):
"""Strict observed70334 DLv1:16-byte EKeys, no entry checksums.
Local CascLib CaptureDownloadHeader/Entry/Tag and TACT.Net BoolArray
establish the11-byte header,22-byte records and MSB-first tag bitmaps.
Other versions/checksum algorithms require separate witnessed contracts.
"""
if not isinstance(raw,bytes)or not 11<=len(raw)<=134217728:
raise ValueError('Bounded native DOWNLOAD bytes required')
if raw[:5]!=b'DL\x01\x10\x00':
raise ValueError('Pinned native DOWNLOADv1/no-checksum layout required')
count=int.from_bytes(raw[5:9],'big');tag_count=int.from_bytes(raw[9:11],'big')
if not 0<count<=MAX_ROOT_RECORDS or not 0<tag_count<=512:
raise ValueError('DOWNLOAD record/tag bounds')
end=11+22*count
if end>len(raw):raise ValueError('Truncated DOWNLOAD records')
priorities=raw[32:end:22]
if any(v>2 for v in priorities)or any(a>b for a,b in zip(priorities,priorities[1:])):
raise ValueError('Unreviewed DOWNLOAD priority/order')
size=(count+7)//8;pos=end;tags=[];seen=set()
for _ in range(tag_count):
zero=raw.find(b'\0',pos,min(pos+257,len(raw)))
if zero<=pos or any(c<32 or c>126 for c in raw[pos:zero]):
raise ValueError('Bounded ASCII DOWNLOAD tag required')
name=raw[pos:zero].decode('ascii');identity=(name,int.from_bytes(raw[zero+1:zero+3],'big'))
begin=zero+3
if begin+size>len(raw):raise ValueError('Truncated DOWNLOAD tag bitmap')
if identity in seen:raise ValueError('Duplicate DOWNLOAD tag')
bitmap=raw[begin:begin+size]
if count%8 and bitmap[-1]&((1<<(8-count%8))-1):
raise ValueError('Nonzero DOWNLOAD bitmap padding')
seen.add(identity);tags.append(dict(name=name,type=identity[1],bitmap=bitmap));pos=begin+size
if pos!=len(raw):raise ValueError('Unreviewed DOWNLOAD trailing bytes')
return dict(count=count,entries_end=end,tags=tags,md5=hashlib.md5(raw).hexdigest())
def download_controls(raw,layout,keys):
"""Resolve explicit EKeys only; do not infer tags from similar paths."""
if not isinstance(keys,set)or not 1<=len(keys)<=2*MAX_ASSET_BATCH or any(
not isinstance(k,bytes)or len(k)!=16 for k in keys):
raise ValueError('Explicit bounded DOWNLOAD control keys required')
found={}
for index,at in enumerate(range(11,layout['entries_end'],22)):
key=raw[at:at+16]
if key not in keys:continue
if key in found:raise ValueError('Ambiguous DOWNLOAD control key')
found[key]=dict(index=index,encoded_size=int.from_bytes(raw[at+16:at+21],'big'),
priority=raw[at+21],tags=[bool(t['bitmap'][index//8]&(128>>(index%8)))for t in layout['tags']])
return found
def _insert_download_bits(bitmap,count,insertions):
"""Insert MSB-first bits; retain all original bits including byte crossings."""
value=int.from_bytes(bitmap,'big')>>(len(bitmap)*8-count)
for position,bit in insertions:
if type(position)is not int or not 0<=position<=count or type(bit)is not bool:
raise ValueError('Invalid DOWNLOAD bitmap insertion')
tail=count-position;mask=(1<<tail)-1
value=((value>>tail)<<(tail+1))|(int(bit)<<tail)|(value&mask);count+=1
pad=(-count)%8
return(value<<pad).to_bytes((count+7)//8,'big')
def extend_download(raw,additions,*,expected_download_md5):
"""Stage new asset availability with actual native resource tags/priority.
Preserve every old entry and tag bit. Inherit only from an explicit native
EKey control, never fabricated platform/locale metadata. No client install.
This is not proof that missing DOWNLOAD entries caused a native failure.
"""
layout=download_layout(raw)
if not isinstance(expected_download_md5,str)or not re.fullmatch('[0-9a-f]{32}',expected_download_md5)or layout['md5']!=expected_download_md5:
raise ValueError('Native DOWNLOAD content pin differs')
if not isinstance(additions,list)or not 1<=len(additions)<=MAX_ASSET_BATCH:
raise ValueError('Bounded DOWNLOAD asset additions required')
wanted=set();new_keys=set();jobs=[]
for row in additions:
if not isinstance(row,dict)or set(row)!={'encoding_key','encoded_size','native_control_ekey'}:
raise ValueError('Complete DOWNLOAD addition/control required')
for name in('encoding_key','native_control_ekey'):
if not isinstance(row[name],str)or not re.fullmatch('[0-9a-f]{32}',row[name])or row[name]=='0'*32:
raise ValueError('Positive DOWNLOAD EKey required')
key=bytes.fromhex(row['encoding_key']);control=bytes.fromhex(row['native_control_ekey'])
if key in new_keys:raise ValueError('Duplicate DOWNLOAD addition')
if type(row['encoded_size'])is not int or not 0<row['encoded_size']<1<<40:
raise ValueError('DOWNLOAD encoded size bound')
wanted.add(control);new_keys.add(key);jobs.append((key,control,row['encoded_size']))
found=download_controls(raw,layout,wanted|new_keys)
if not wanted<=found.keys():raise ValueError('Native DOWNLOAD control is absent')
if new_keys&found.keys():raise ValueError('DOWNLOAD addition already exists')
if layout['count']+len(jobs)>MAX_ROOT_RECORDS:raise ValueError('Extended DOWNLOAD count bound')
# Existing priorities are nondecreasing; stable insertion retains old order.
priorities=raw[32:layout['entries_end']:22];jobs.sort(key=lambda r:(found[r[1]]['priority'],r[0]))
blocks=[];cursor=11;insertions=[];records=[]
for offset,(key,control,size)in enumerate(jobs):
native=found[control];position=bisect.bisect_right(priorities,native['priority'])
at=11+position*22;blocks.extend((raw[cursor:at],key+size.to_bytes(5,'big')+bytes([native['priority']])));cursor=at
insertions.append((position+offset,native['tags']))
records.append(dict(encoding_key=key.hex(),native_control_ekey=control.hex(),priority=native['priority'],
tags=[dict(name=t['name'],type=t['type'])for t,bit in zip(layout['tags'],native['tags'])if bit]))
blocks.append(raw[cursor:layout['entries_end']]);count=layout['count']+len(jobs)
header=raw[:5]+count.to_bytes(4,'big')+raw[9:11];tag_bytes=[]
for i,tag in enumerate(layout['tags']):
bitmap=_insert_download_bits(tag['bitmap'],layout['count'],[(p,bits[i])for p,bits in insertions])
tag_bytes.append(tag['name'].encode()+b'\0'+tag['type'].to_bytes(2,'big')+bitmap)
output=header+b''.join(blocks)+b''.join(tag_bytes);checked=download_layout(output)
return output,dict(kind='additive-native-download-stage',original_download_md5=layout['md5'],
staged_download_md5=checked['md5'],original_entries=layout['count'],new_entries=len(jobs),
original_entry_bytes_preserved=True,original_tag_bits_preserved=True,records=records,
installed=False,engine_loaded=False,native_failure_cause_established=False)
def encoding_layout(raw):
"""Pinned ENv1/16-byte-key pages; verify every original page digest."""
if not isinstance(raw,bytes)or not 22<=len(raw)<=536870912:raise ValueError('Bounded ENCODING bytes required')
magic,version,ck,ek,cp,ep,cn,en,reserved,es=struct.unpack_from('>2s3B2H2IBI',raw)
if magic!=b'EN'or version!=1 or ck!=16 or ek!=16 or cp!=4 or ep!=4 or reserved or not 0<cn<=100000 or not 0<en<=100000 or not 0<es<=16777216:
raise ValueError('Pinned native ENCODING layout required')
pos=22
if pos+es>len(raw):raise ValueError('Truncated encoding specs')
specs=raw[pos:pos+es];pos+=es
if not specs.endswith(b'\0'):raise ValueError('Encoding spec terminator')
sections={}
for label,count in(('content',cn),('encoded',en)):
headers_at=pos;pages_at=pos+count*32;end=pages_at+count*4096
if end>len(raw):raise ValueError('Truncated encoding pages')
pages=[];previous=None
for i in range(count):
first=raw[headers_at+i*32:headers_at+i*32+16]
digest=raw[headers_at+i*32+16:headers_at+(i+1)*32]
page=raw[pages_at+i*4096:pages_at+(i+1)*4096]
if previous is not None and first<=previous:raise ValueError('Encoding page-key ordering')
if hashlib.md5(page).digest()!=digest:raise ValueError('Encoding page checksum mismatch')
pages.append((first,page));previous=first
sections[label]=pages;pos=end
tail=raw[pos:]
if not 0<len(tail)<=4096 or any(v<32 or v>126 for v in tail):raise ValueError('Encoding self-spec tail')
return dict(specs=specs,sections=sections,tail=tail,md5=hashlib.md5(raw).hexdigest())
_ENCODED_PAGE_TERMINATOR=bytes(16)+b'\xff'*4+bytes(5)
def _encoding_entries(page,kind):
entries=[];pos=0
while pos<len(page):
if kind=='content':
count=page[pos]
if not count:break
length=22+count*16;key_at=6
else:
if page[pos:pos+16]==bytes(16):break
length=25;key_at=0
if pos+length>len(page):raise ValueError('Encoding entry crosses page')
row=page[pos:pos+length];key=row[key_at:key_at+16]
if entries and key<=entries[-1][0]:raise ValueError('Encoding entry-key ordering')
entries.append((key,row));pos+=length
# Original70334 EKey pages can end with a zero key, UINT32_MAX ESpec
# index and zero size. This is an end marker, not an encoded-file entry.
tail=page[pos:]
if kind=='encoded' and tail.startswith(_ENCODED_PAGE_TERMINATOR):
tail=tail[len(_ENCODED_PAGE_TERMINATOR):]
if any(tail):raise ValueError('Nonzero encoding page padding')
if not entries:raise ValueError('Empty encoding page')
return entries
def _extend_encoding_pages(pages,additions,kind,*,content_replacements=None):
keys=[p[0]for p in pages];selected=defaultdict(list)
for key,row in additions:
selected[max(0,bisect.bisect_right(keys,key)-1)].append((key,row))
output=[];changed=0;new_count=0;terminal_pages=0
for i,(first,page)in enumerate(pages):
if i not in selected:output.append((first,page));continue
old=_encoding_entries(page,kind)
end=sum(len(row)for _,row in old)
terminal=(_ENCODED_PAGE_TERMINATOR if kind=='encoded' and
page[end:end+len(_ENCODED_PAGE_TERMINATOR)]==_ENCODED_PAGE_TERMINATOR else b'')
if old[0][0]!=first:raise ValueError('Encoding page first-key differs')
merged=dict(old)
for key,row in selected[i]:
if key in merged:
if merged[key]!=row:
expected=(content_replacements or {}).get(key)
before=merged[key]
if kind!='content' or expected!=(before,row):raise ValueError('Conflicting encoding identity')
old_keys=[before[n:n+16]for n in range(22,len(before),16)]
new_keys=[row[n:n+16]for n in range(22,len(row),16)]
if (row[1:22]!=before[1:22] or row[0]!=len(new_keys) or len(set(new_keys))!=len(new_keys) or
not set(old_keys)<=set(new_keys) or not 1<=len(new_keys)<=255):
raise ValueError('External local preference lost native content identity/bindings')
merged[key]=row
else:merged[key]=row;new_count+=1
if list(sorted(merged.items()))==old:output.append((first,page));continue
changed+=1;payload=bytearray();page_first=None
for key,row in sorted(merged.items()):
if len(row)>4096:raise ValueError('Encoding entry size bound')
if len(payload)+len(row)>4096:
output.append((page_first,bytes(payload)+bytes(4096-len(payload))));payload=bytearray();page_first=None
if page_first is None:page_first=key
payload.extend(row)
if payload:
if terminal and len(payload)+len(terminal)>4096:
# Encoded rows are fixed25bytes. Carry the last real row to
# another page so the original end marker follows all rows.
last_key,last_row=sorted(merged.items())[-1]
assert kind=='encoded' and len(last_row)==25 and len(payload)>25
prefix=payload[:-25]
output.append((page_first,bytes(prefix)+bytes(4096-len(prefix))))
page_first=last_key;payload=bytearray(last_row)
output.append((page_first,bytes(payload)+terminal+bytes(4096-len(payload)-len(terminal))))
terminal_pages+=bool(terminal)
if any(a[0]>=b[0]for a,b in zip(output,output[1:])):raise ValueError('Extended encoding page ordering')
audit=dict(original_pages=len(pages),staged_pages=len(output),changed_original_pages=changed,new_entries=new_count,original_entries_preserved=True)
if terminal_pages:audit['original_encoded_end_markers_preserved']=terminal_pages
return output,audit
def extend_encoding(raw,additions,*,expected_encoding_md5,reused_native_payloads=None,external_content_payloads=None,retained_native_content_entries=None):
"""Add generated plaintext BLTE identities; preserve original keys/records.
TACT EncodingContentEntry: count8,size40,CKey128,EKeys128[];
EncodingEncodedEntry: EKey128,specIndex32,size40, all multibyte values BE.
Only touched pages are repacked/split; original key bindings survive.
Explicit external content receipts may prefer a newly local framing while
retaining all original EKeys in that content-address entry.
No encrypted object or spec is decoded/re-encoded by this operation.
"""
if not isinstance(expected_encoding_md5,str)or not re.fullmatch('[0-9a-f]{32}',expected_encoding_md5):raise ValueError('Encoding content pin required')
layout=encoding_layout(raw)
if layout['md5']!=expected_encoding_md5:raise ValueError('Native encoding content pin differs')
if not isinstance(additions,list)or not 1<=len(additions)<=MAX_ASSET_BATCH:raise ValueError('Encoding addition bound')
# Explicit byte-for-byte native readback receipts allow a second framing of
# identical content without replacing its original CKey -> EKey selection.
# The new EKey still gets an encoded entry for TVFS direct references.
if reused_native_payloads is not None and not isinstance(reused_native_payloads,dict):
raise ValueError('Bounded native content reuse receipts required')
receipts={} if reused_native_payloads is None else dict(reused_native_payloads)
# External source bytes may repair unavailable local native content when
# their full MD5 content address and decoded size match original ENCODING.
# This is distinct from claiming an available-native payload readback.
external={} if external_content_payloads is None else external_content_payloads
if not isinstance(external,dict) or len(external)>MAX_ASSET_BATCH:
raise ValueError('Bounded external content-address receipts required')
for key,receipt in external.items():
if (not isinstance(receipt,dict) or set(receipt)!={'authority','payload'} or
receipt['authority']!='original-encoding-full-MD5-and-decoded-size' or
not isinstance(receipt['payload'],bytes) or key in receipts):
raise ValueError('Explicit disjoint external content-address authority required')
receipts[key]=receipt['payload']
if not isinstance(receipts,dict) or len(receipts)>MAX_ASSET_BATCH:
raise ValueError('Bounded native content reuse receipts required')
originals={}
if receipts:
originals={key:row for _,page in layout['sections']['content']for key,row in _encoding_entries(page,'content') if key.hex()in receipts}
for key,receipt in receipts.items():
if (not isinstance(key,str) or not re.fullmatch('[0-9a-f]{32}',key)
or not isinstance(receipt,bytes) or hashlib.md5(receipt).hexdigest()!=key
or bytes.fromhex(key)not in originals
or int.from_bytes(originals[bytes.fromhex(key)][1:6],'big')!=len(receipt)):
raise ValueError('Native content reuse bytes/key/size differ')
specs=layout['specs'];strings=specs[:-1].split(b'\0')
spec_indices={s:i for i,s in enumerate(strings)}
ckeys=set();ekeys=set();content=[];encoded=[];content_replacements={};local_preferences=[]
for row in additions:
fields={'content_key','encoding_key','decoded_size','encoded_size'}
if not isinstance(row,dict)or set(row)not in(fields,fields|{'encoding_spec'}):raise ValueError('Complete new asset encoding identity required')
spec=row.get('encoding_spec','n')
spec_bytes=reviewed_encoding_spec(spec)
if spec_bytes not in spec_indices:
spec_indices[spec_bytes]=len(strings);strings.append(spec_bytes);specs+=spec_bytes+b'\0'
spec_index=spec_indices[spec_bytes]
for key in('content_key','encoding_key'):
if not isinstance(row[key],str)or not re.fullmatch('[0-9a-f]{32}',row[key])or row[key]=='0'*32:raise ValueError('Positive encoding key required')
ck=bytes.fromhex(row['content_key']);ek=bytes.fromhex(row['encoding_key'])
if ck in ckeys or ek in ekeys:raise ValueError('Duplicate new encoding identity')
ckeys.add(ck);ekeys.add(ek)
for field in('decoded_size','encoded_size'):
if type(row[field])is not int or not 0<row[field]<=0x7fffffff:raise ValueError('Bounded encoded asset size required')
if spec=='n'and row['encoded_size']!=row['decoded_size']+9:raise ValueError('N-frame BLTE size contract differs')
if row['content_key'] in receipts:
if len(receipts[row['content_key']])!=row['decoded_size']:
raise ValueError('Native content reuse decoded size differs')
original=originals[ck]
if row['content_key'] in external:
old_keys=[original[n:n+16]for n in range(22,len(original),16)]
preferred=[ek]+[key for key in old_keys if key!=ek]
if len(preferred)>255:raise ValueError('Native EKey alternative count bound')
replacement=bytes([len(preferred)])+original[1:22]+b''.join(preferred)
if replacement!=original:
content_replacements[ck]=(original,replacement)
local_preferences.append(dict(content_key=ck.hex(),preferred_local_encoding_key=ek.hex(),
original_encoding_keys=[key.hex()for key in old_keys],all_original_bindings_preserved=True))
content.append((ck,replacement))
else:content.append((ck,original))
else:
content.append((ck,b'\x01'+row['decoded_size'].to_bytes(5,'big')+ck+ek))
encoded.append((ek,struct.pack('>16sI',ek,spec_index)+row['encoded_size'].to_bytes(5,'big')))
# A fresh store may reuse the current, already accepted original-content
# selection without rereading its decoded assets. These are actual EN rows,
# not a newly inferred preferred framing. Every original alternative must
# remain, and every retained EKey must exist in the native table/additions.
retained={} if retained_native_content_entries is None else retained_native_content_entries
if not isinstance(retained,dict)or len(retained)>MAX_ASSET_BATCH:
raise ValueError('Bounded retained native content entries required')
if retained:
baseline={key:row for _,page in layout['sections']['content']for key,row in _encoding_entries(page,'content')if key.hex()in retained}
known_encoded={key for _,page in layout['sections']['encoded']for key,row in _encoding_entries(page,'encoded')}|ekeys
selected=dict(content)
for key,row in retained.items():
if not isinstance(key,str)or not re.fullmatch('[0-9a-f]{32}',key):raise ValueError('Retained native content key')
ck=bytes.fromhex(key);original=baseline.get(ck)
if (original is None or not isinstance(row,bytes)or len(row)<38 or not row[0]
or len(row)!=22+16*row[0]or row[6:22]!=ck or row[1:6]!=original[1:6]):
raise ValueError('Retained native content entry identity/size differs')
old_keys={original[n:n+16]for n in range(22,len(original),16)}
keys=[row[n:n+16]for n in range(22,len(row),16)]
if len(set(keys))!=len(keys)or not old_keys.issubset(keys)or not(set(keys)-old_keys).issubset(known_encoded):
raise ValueError('Retained native entry drops original or has unavailable encoding')
selected[ck]=row
if row!=original:content_replacements[ck]=(original,row)
content=list(selected.items())
cp,ca=_extend_encoding_pages(layout['sections']['content'],content,'content',content_replacements=content_replacements)
ep,ea=_extend_encoding_pages(layout['sections']['encoded'],encoded,'encoded')
if ca['new_entries']==0 and ea['new_entries']==0 and ca['changed_original_pages']==0 and ea['changed_original_pages']==0:return raw,dict(installed=False,new_entries=0,original_entries_preserved=True)
def block(pages):
return b''.join(first+hashlib.md5(page).digest()for first,page in pages)+b''.join(page for _,page in pages)
header=struct.pack('>2s3B2H2IBI',b'EN',1,16,16,4,4,len(cp),len(ep),0,len(specs))
# This staged encoding object itself is published as a single N-frame BLTE.
result=header+specs+block(cp)+block(ep)+b'n'
checked=encoding_layout(result)
return result,dict(kind='additive-native-encoding-stage',original_encoding_md5=expected_encoding_md5,
staged_encoding_md5=checked['md5'],content_pages=ca,encoded_pages=ea,
original_entries_preserved=True,reused_native_content_keys=sorted(reused_native_payloads or {}),
external_content_keys=sorted(external),external_local_encoding_preferences=local_preferences,
original_content_entry_bytes_preserved=not bool(content_replacements),all_original_content_key_encoding_bindings_preserved=True,retained_native_content_entries=sorted(retained),external_content_authority='original-encoding-full-MD5-and-decoded-size' if external else None,new_entries=len(additions),installed=False,engine_loaded=False)
def blte_uncompressed(raw):
if not isinstance(raw,bytes)or not 0<len(raw)<=536870912:raise ValueError('Bounded asset bytes required')
encoded=b'BLTE'+bytes(4)+b'N'+raw
return encoded,dict(content_key=hashlib.md5(raw).hexdigest(),encoding_key=hashlib.md5(encoded).hexdigest(),decoded_size=len(raw),encoded_size=len(encoded))
def blte_encoding_key(encoded):
"""Validate generated N/Z frames; framed EKey hashes the HEADER only.
CascLib ParseBlteHeader/LoadSpanFrames and TACT.Net Finalise agree on
explicit compressed/decoded sizes and per-frame MD5s. This does not grant
access to encrypted data and deliberately accepts no encryption frames.
"""
if not isinstance(encoded,bytes)or not 9<=len(encoded)<=536936448 or encoded[:4]!=b'BLTE':
raise ValueError('Bounded generated BLTE required')
size=int.from_bytes(encoded[4:8],'big')
if size==0:
if encoded[8:9]!=b'N' or len(encoded)==9:raise ValueError('Generated headerless N-frame required')
return hashlib.md5(encoded).digest()
if len(encoded)<12 or encoded[8]!=15:raise ValueError('Explicit BLTE frame header required')
count=int.from_bytes(encoded[9:12],'big')
if not 1<=count<=1024 or size!=12+24*count or size>=len(encoded):
raise ValueError('BLTE frame table extent')
pos=size;decoded=0
for i in range(count):
es,ds=struct.unpack_from('>II',encoded,12+i*24)
if es<2 or ds<1 or es>len(encoded)-pos:raise ValueError('BLTE frame extent')
frame=encoded[pos:pos+es];decoded+=ds
if frame[:1]not in(b'N',b'Z')or decoded>536870912:
raise ValueError('Unreviewed BLTE frame mode/size')
if frame[:1]==b'N'and len(frame)!=ds+1:raise ValueError('N-frame decoded size differs')
if hashlib.md5(frame).digest()!=encoded[20+i*24:36+i*24]:raise ValueError('BLTE frame checksum differs')
pos+=es
if pos!=len(encoded):raise ValueError('Trailing BLTE frame bytes')
return hashlib.md5(encoded[:size]).digest()
def decode_blte(encoded,*,encoding_key,content_key,max_decoded=16777216):
"""Decode checked plaintext asset frames; no networking or key bypass.
Both keys come from independently pinned game metadata. Explicit per-frame
sizes, checksums, bounded zlib output and the final content hash are required.
Encrypted/unknown modes remain rejected by the existing framing validator.
"""
if any(not isinstance(k,str)or not re.fullmatch('[0-9a-f]{32}',k)for k in(encoding_key,content_key)):
raise ValueError('Pinned BLTE encoding/content keys required')
if type(max_decoded)is not int or not 0<max_decoded<=536870912:raise ValueError('Decoded BLTE bound required')
if blte_encoding_key(encoded).hex()!=encoding_key:raise ValueError('BLTE encoding key differs')
header=int.from_bytes(encoded[4:8],'big');decoded=[];total=0
if header==0:
if len(encoded)-9>max_decoded:raise ValueError('Decoded BLTE byte bound')
decoded=[encoded[9:]]
else:
pos=header
for i in range(int.from_bytes(encoded[9:12],'big')):
es,ds=struct.unpack_from('>II',encoded,12+24*i);total+=ds
if total>max_decoded:raise ValueError('Decoded BLTE byte bound')
frame=encoded[pos:pos+es];pos+=es
if frame[:1]==b'N':raw=frame[1:]
else:
decoder=zlib.decompressobj()
try:raw=decoder.decompress(frame[1:],ds+1)
except zlib.error as error:raise ValueError('Invalid BLTE zlib frame')from error
if not decoder.eof or decoder.unused_data or decoder.unconsumed_tail:raise ValueError('Incomplete/trailing BLTE zlib frame')
if len(raw)!=ds:raise ValueError('BLTE decoded frame size differs')
decoded.append(raw)
result=b''.join(decoded)
if hashlib.md5(result).hexdigest()!=content_key:raise ValueError('BLTE content key differs')
return result
def blte_framed(chunks):
"""Generate bounded, explicitly sized native-style plaintext N/Z frames."""
if not isinstance(chunks,list)or not 1<=len(chunks)<=1024:raise ValueError('Bounded BLTE chunks required')
frames=[];table=[];digest=hashlib.md5();total=0
for raw,mode in chunks:
if not isinstance(raw,bytes)or not raw or mode not in('N','Z'):raise ValueError('Explicit N/Z chunk required')
total+=len(raw)
if total>536870912:raise ValueError('Decoded BLTE byte bound')
digest.update(raw);frame=b'N'+raw if mode=='N'else b'Z'+zlib.compress(raw,9)
frames.append(frame);table.append(struct.pack('>II',len(frame),len(raw))+hashlib.md5(frame).digest())
header=b'BLTE'+struct.pack('>I',12+24*len(frames))+b'\x0f'+len(frames).to_bytes(3,'big')+b''.join(table)
result=header+b''.join(frames);key=blte_encoding_key(result)
return result,dict(content_key=digest.hexdigest(),encoding_key=key.hex(),decoded_size=total,encoded_size=len(result))
def blte_frame_spec(chunks):
"""Exact generated plaintext block recipe; final block consumes remainder."""
if not isinstance(chunks,list)or not 1<=len(chunks)<=1024:raise ValueError('Bounded BLTE chunks required')
if any(not isinstance(raw,bytes)or not raw or mode not in('N','Z')for raw,mode in chunks):raise ValueError('Explicit N/Z chunk required')
return 'b:{'+','.join([str(len(raw))+'='+mode.lower()for raw,mode in chunks[:-1]]+['*='+chunks[-1][1].lower()])+'}'
def frame_encoding(raw):
"""Use the actual70334 seven-section EN framing, including its self-spec.
Actual native control: N,Z,N,N,N,N,Z for header/spec strings/content
index/content pages/encoded index/encoded pages/self-spec. Explicit decoded
sizes avoid relying on headerless metadata size adoption. Native acceptance
remains an integration test, not an inference from CascLib readback.
"""
layout=encoding_layout(raw);cp=layout['sections']['content'];ep=layout['sections']['encoded']
sizes=[22,len(layout['specs']),32*len(cp),4096*len(cp),32*len(ep),4096*len(ep)]
modes=['N','Z','N','N','N','N','Z'];end=sum(sizes)
if end+len(layout['tail'])!=len(raw):raise ValueError('ENCODING section extents differ')
tail=('b:{'+','.join(str(n)+'='+m.lower()for n,m in zip(sizes,modes))+',*=z}').encode()
rebuilt=raw[:end]+tail;chunks=[];pos=0
for size,mode in zip(sizes,modes):chunks.append((rebuilt[pos:pos+size],mode));pos+=size
chunks.append((tail,'Z'));encoded,identity=blte_framed(chunks)
return rebuilt,encoded,dict(identity,frame_count=7,self_encoding_spec=tail.decode(),zlib_version=zlib.ZLIB_VERSION)
def model_container(body,skin_ids,texture_ids):
"""Bind staged native body to explicit package IDs, never loose handles.
The destination engine's actual paired model uses MD21/SFID/TXID chunks.
Zero texture IDs are retained for replaceable slots. This function does
not allocate IDs, infer texture identity, publish storage or load a model.
"""
from item_appearance_preflight import model_vertex_stream,model_dependency_chunks
if not isinstance(body,bytes)or body[:4]!=b'MD20':raise ValueError('Native MD20 body required')
# #88: the 70334 animation lookup probes header 0x24 as a hash until -1; a copied 1.12 table ([0], direct)
# loops forever for an absent ID (ERROR #109). Every packaged body gets the native terminated hash.
from m2_sequence_hash import native_sequence_hash
if struct.unpack_from('<I',body,0x1C)[0]:body=native_sequence_hash(body)[0]
parsed=model_vertex_stream(body)
if parsed['md20_version']not in(272,274):raise ValueError('Converted native model version required')
views=struct.unpack_from('<I',body,68)[0]
if not isinstance(skin_ids,list)or len(skin_ids)!=views or not 1<=views<=32 or any(type(i)is not int or not 0<i<=0xffffffff for i in skin_ids):
raise ValueError('Explicit skin ID for every native view required')
if not isinstance(texture_ids,list)or len(texture_ids)!=len(parsed['declared_textures'])or any(type(i)is not int or not 0<=i<=0xffffffff for i in texture_ids):
raise ValueError('Explicit native texture slot IDs required')
for slot,ident in zip(parsed['declared_textures'],texture_ids):
if (slot['type']==0 and not ident)or(slot['type']!=0 and ident):
raise ValueError('External texture needs registered ID; replaceable slot remains zero')
# Native MD21 controls retain texture type/flags, but filename lengths are
# zero: explicit resources come from TXID, replaceable slots from item
# materials. A legacy name here can select the old path instead of the
# registered FileDataID. Retain source provenance outside the engine body.
native_body=bytearray(body);count,offset=struct.unpack_from('<II',body,80)
if count!=len(texture_ids):raise ValueError('Native texture array differs')
for index in range(count):struct.pack_into('<II',native_body,offset+index*16+8,0,0)
def chunk(tag,data):return struct.pack('<4sI',tag,len(data))+data
result=chunk(b'MD21',native_body)+chunk(b'SFID',struct.pack('<'+'I'*len(skin_ids),*skin_ids))+chunk(b'TXID',struct.pack('<'+'I'*len(texture_ids),*texture_ids))
checked=model_dependency_chunks(result)
if checked['skin_file_ids']!=skin_ids or checked['texture_file_ids']!=texture_ids:
raise ValueError('Native model binding roundtrip differs')
return result
def _model_txid_layout(raw):
"""Locate the witnessed explicit TXID array without rebuilding any chunks."""
from item_appearance_preflight import model_dependency_chunks
deps=model_dependency_chunks(raw)
if deps['md20_version'] not in (272,274):raise ValueError('Reviewed native model version required')
pos=0;body=None;txid=None
while pos<len(raw):
tag,size=struct.unpack_from('<4sI',raw,pos)
if tag==b'MD21':
if body is not None:raise ValueError('Duplicate native body')
body=raw[pos+8:pos+8+size]
if tag==b'TXID':
if txid is not None:raise ValueError('Duplicate native TXID')
txid=(pos+8,size)
pos+=8+size
if body is None or txid is None:raise ValueError('Complete native body/TXID required')
count,offset=struct.unpack_from('<II',body,80)
if count!=len(deps['texture_file_ids']) or txid[1]!=count*4 or offset+count*16>len(body):raise ValueError('Complete declared native texture slots required')
types=[struct.unpack_from('<I',body,offset+i*16)[0]for i in range(count)]
return deps,txid,types
def rebind_model_texture_file_ids(raw,replacements):
"""Create an owned explicit-texture variant; preserve all other native bytes."""
if not isinstance(raw,bytes)or not isinstance(replacements,dict)or not replacements or any(type(a)is not int or type(b)is not int or not 0<a<=0xffffffff or not 0<b<=0xffffffff or a==b for a,b in replacements.items()):raise ValueError('Explicit changed texture IDs required')
deps,(offset,size),types=_model_txid_layout(raw);old=deps['texture_file_ids'];used={i for i in old if i in replacements}
if used!=set(replacements):raise ValueError('Unrelated texture replacement')
result=bytearray(raw);changed=[]
for i,ident in enumerate(old):
if ident in replacements:
if types[i]!=0:raise ValueError('Only original explicit texture slots can be rebound')
struct.pack_into('<I',result,offset+i*4,replacements[ident]);changed.append(i)
result=bytes(result);new=_model_txid_layout(result)[0]
masked=raw[:offset]+bytes(size)+raw[offset+size:]
if result[:offset]+bytes(size)+result[offset+size:]!=masked:raise ValueError('Model variant changed non-TXID bytes')
return result,dict(kind='owned-explicit-TXID-rebind-v1',old_texture_ids=old,new_texture_ids=new['texture_file_ids'],skin_file_ids=deps['skin_file_ids'],animation_files=deps['animation_files'],changed_slots=changed,non_TXID_sha256=hashlib.sha256(masked).hexdigest(),all_non_TXID_bytes_preserved=True,geometry_SKIN_metadata_and_all_opaque_chunks_preserved=True)
def specialize_model_material(raw,material_file_id):
"""Compile a constant source-appearance material into a native M2 variant.
Only captured equipment selectors0(explicit) and2(item diffuse) qualify.
The caller resolves the genuine ItemDisplayInfo material and deduplicates
returned bytes by content; no item IDs or runtime texture handles enter M2.
Existing explicit TXIDs, skin references and all geometry remain unchanged.
"""
from m2_format_compare import model
if type(material_file_id)is not int or not 0<material_file_id<=0xffffffff:
raise ValueError('Positive registered source material FileDataID required')
parsed=model(raw);textures=parsed['summary']['declared_textures'];deps=parsed['dependencies']
if parsed['old']or any(t['type']not in(0,2)for t in textures):raise ValueError('Reviewed native equipment texture selectors required')
ids=list(deps['texture_file_ids'])
if len(ids)!=len(textures):raise ValueError('Complete native texture FileDataID bindings required')
replaced=[i for i,t in enumerate(textures)if t['type']==2]
if not replaced:return raw,dict(specialized=False,geometry_preserved=True,source_sha256=hashlib.sha256(raw).hexdigest())
body=bytearray(parsed['body']);count,offset=struct.unpack_from('<II',body,80)
if count!=len(ids)or not 1<=count<=32768:raise ValueError('Native texture array bound')
for i in replaced:struct.pack_into('<I',body,offset+16*i,0);ids[i]=material_file_id
# Every remaining slot is explicit. Match the witnessed native type-index
# table's last type0 index, avoiding a stale type2 override after baking.
body.extend(bytes((-len(body))%16));at=len(body);body.extend(struct.pack('<h',count-1));struct.pack_into('<II',body,104,1,at)
# Existing native SFID may include extra LOD skins beyond the body view
# count. Preserve that complete chunk instead of passing it through the
# converted-legacy builder's stricter one-skin-per-view contract.
for i in range(count):struct.pack_into('<II',body,offset+16*i+8,0,0)
def replacement_chunk(tag,data):return struct.pack('<4sI',tag,len(data))+data
generated=(replacement_chunk(b'MD21',bytes(body))+
replacement_chunk(b'TXID',struct.pack('<'+'I'*len(ids),*ids)))
# Native families can carry TXAC/LDV1 and other original chunks. Retain
# their bytes and order; rebuilding only the three basic chunks would
# silently discard native model metadata while keeping the same mesh.
def chunks(data):
offset=0
while offset<len(data):
if offset+8>len(data):raise ValueError('Truncated material variant chunk')
tag,size=struct.unpack_from('<4sI',data,offset);end=offset+8+size
if end>len(data):raise ValueError('Material variant chunk outside input')
yield tag,data[offset:end]
offset=end
replacements=dict(chunks(generated));seen=set();parts=[]
for tag,chunk in chunks(raw):
if tag in replacements:
if tag in seen:raise ValueError('Duplicate native material-binding chunk')
seen.add(tag);parts.append(replacements[tag])
else:parts.append(chunk)
if seen!=set(replacements):raise ValueError('Original native material-binding chunks required')
result=b''.join(parts);checked=model(result)
if checked['vertices']!=parsed['vertices']or checked['dependencies']['skin_file_ids']!=deps['skin_file_ids']:
raise ValueError('Material specialization changed geometry or skins')
return result,dict(kind='source-appearance-constant-material-variant',specialized=True,
source_sha256=hashlib.sha256(raw).hexdigest(),variant_sha256=hashlib.sha256(result).hexdigest(),
material_file_data_id=material_file_id,replaced_texture_slots=replaced,geometry_preserved=True,
skin_file_data_ids=deps['skin_file_ids'],source_item_ids_changed=False,engine_rendering_verified=False)
def root_groups(raw):
if not isinstance(raw,bytes)or not 24<=len(raw)<=MAX_ROOT_BYTES:raise ValueError('Bounded native ROOT bytes required')
magic,header,version,total,named,padding=struct.unpack_from('<6I',raw)
if magic!=0x4d465354 or header!=24 or version!=2 or padding or not 0<=named<=total<=MAX_ROOT_RECORDS:raise ValueError('Pinned70334 ROOT header required')
pos=header;groups=[];actual=0;actual_named=0;maximum=0
while pos<len(raw):
start=pos
if len(groups)>=MAX_GROUPS or pos+17>len(raw):raise ValueError('ROOT group count/header bound')
count,locale,flags1,flags2,flags3=struct.unpack_from('<4IB',raw,pos);pos+=17
if not 1<=count<=MAX_ROOT_RECORDS-actual:raise ValueError('ROOT record count bound')
flags=flags1|flags2|(flags3<<17);ids=pos;ckeys=pos+4*count;hashes=ckeys+16*count;has_names=not(flags&NO_NAME_HASH)
pos=hashes+(8*count if has_names else 0)
if pos>len(raw):raise ValueError('Truncated ROOT arrays')
ident=0
for(delta,)in struct.iter_unpack('<I',raw[ids:ckeys]):
ident+=delta
if not 0<ident<=0xffffffff:raise ValueError('Invalid/overflowing ROOT FileDataID delta')
maximum=max(maximum,ident);ident+=1
groups.append(dict(start=start,end=pos,count=count,locale=locale,flags1=flags1,flags2=flags2,flags3=flags3,ids_offset=ids,ckeys_offset=ckeys,name_hashes_offset=hashes if has_names else None))
actual+=count;actual_named+=count if has_names else 0
if(actual,actual_named)!=(total,named):raise ValueError('ROOT aggregate counts differ')
return dict(header_bytes=header,total_records=total,named_records=named,max_file_data_id=maximum,groups=groups,root_md5=hashlib.md5(raw).hexdigest(),root_sha256=hashlib.sha256(raw).hexdigest())
def reuse_existing_root_variant(raw, replacements, *, expected_root_md5):
"""Select an existing same-FileDataID content variant for local fallback.
Preserve every ID, group header, locale, ordering and name hash. Replacement
keys must already belong to that exact native ID (not just a similar path).
Caller establishes unavailable bytes and supplies the matching real payload.
No schema identifiers or engine validation are changed.
"""
if hashlib.md5(raw).hexdigest()!=expected_root_md5 or not isinstance(replacements,dict) or not 1<=len(replacements)<=32:
raise ValueError('Pinned bounded native variant replacement required')
layout=root_groups(raw);found=root_controls(raw,layout,set(replacements))
output=bytearray(raw);changed=[]
for ident,key in sorted(replacements.items()):
if not isinstance(key,str)or not re.fullmatch('[0-9a-f]{32}',key)or key not in {r['content_key']for r in found[ident]}:
raise ValueError('Replacement is not an existing same-ID native variant')
for group in layout['groups']:
ident=0
for index,(delta,)in enumerate(struct.iter_unpack('<I',raw[group['ids_offset']:group['ckeys_offset']])):
ident+=delta
if ident in replacements:
at=group['ckeys_offset']+16*index;old=raw[at:at+16].hex();new=replacements[ident]
if old!=new:
output[at:at+16]=bytes.fromhex(new)
changed.append(dict(file_data_id=ident,old_content_key=old,new_content_key=new,offset=at))
ident+=1
result=bytes(output);root_groups(result)
return result,dict(kind='existing-same-file-id-content-variant-fallback',changes=changed,
original_root_md5=expected_root_md5,staged_root_md5=hashlib.md5(result).hexdigest(),
ids_groups_names_preserved=True,installed=False,engine_loaded=False)
def registered_variant_replacements(audit):
"""Read explicit same-ID fallback provenance without accepting new variants."""
fallback=audit.get('selected_same_id_variant_fallback')
if fallback is None:return {}
if (fallback.get('kind')!='existing-same-file-id-content-variant-fallback' or
fallback.get('ids_groups_names_preserved')is not True or
fallback.get('staged_root_md5')!=audit.get('staged_root_md5')):
raise ValueError('Pinned registered ROOT variant provenance required')
changes=fallback.get('changes')
if not isinstance(changes,list)or not 1<=len(changes)<=32:
raise ValueError('Bounded registered ROOT variant changes required')
replacements={}
for row in changes:
ident=row.get('file_data_id');key=row.get('new_content_key')
if (type(ident)is not int or not 0<ident<=0xffffffff or
not isinstance(key,str)or not re.fullmatch('[0-9a-f]{32}',key)or
ident in replacements and replacements[ident]!=key):
raise ValueError('Conflicting or invalid registered ROOT variant')
replacements[ident]=key
return replacements
def extend_registered_root(native,additions,baseline,baseline_root):
"""Reconstruct the pinned baseline before extending its IDs and fallbacks.
This rejects unrepresented baseline edits rather than silently losing them
when building a new package from the pristine native metadata.
"""
audit=baseline['root'];pin=baseline['registry']['native_root_md5']
if hashlib.md5(baseline_root).hexdigest()!=audit['staged_root_md5']:
raise ValueError('Registered baseline ROOT bytes changed')
fields=('path','file_data_id','content_key','native_group_control')
prior=[{k:r[k]for k in fields}for r in baseline['assets']]
current={r['path']:r for r in additions}
if len(current)!=len(additions)or any(current.get(r['path'])!=r for r in prior):
raise ValueError('Registered baseline asset identity changed')
replacements=registered_variant_replacements(audit)
if prior:
before,_=extend_existing_root_groups(native,prior,expected_root_md5=pin)
else:
# A private additive stage may start at a fully pinned, already-built
# ROOT without claiming its pre-existing records as newly registered.
# No variants or reserved slots may be silently dropped in this mode.
if (baseline.get('kind')!='source-equipment-empty-pinned-root-base-v1'
or baseline['registry'].get('slots') or replacements
or hashlib.md5(native).hexdigest()!=pin or pin!=audit['staged_root_md5']):
raise ValueError('Explicit empty pinned ROOT base required')
before=native
if replacements:
before,_=reuse_existing_root_variant(before,replacements,expected_root_md5=hashlib.md5(before).hexdigest())
if before!=baseline_root:raise ValueError('Registered baseline ROOT edits are not reproducible')
strategy=baseline.get('root_extension_strategy')
if strategy is None:
updated,result=extend_existing_root_groups(native,additions,expected_root_md5=pin)
elif strategy=='prepend-additive-neutral-groups' and not prior:
# Some pinned parents already contain additive groups sharing an
# original group header. Preserve every parent group verbatim instead
# of guessing which matching group should be extended in place.
updated,result=extend_root(native,additions,expected_root_md5=pin)
else:
raise ValueError('Explicit empty-parent ROOT strategy required')
if replacements:
updated,fallback= reuse_existing_root_variant(updated,replacements,expected_root_md5=result['staged_root_md5'])
result.update(staged_root_md5=fallback['staged_root_md5'],
original_id_and_content_key_prefixes_bit_identical=False,
selected_same_id_variant_fallback=fallback)
result.update(baseline_root_md5=audit['staged_root_md5'],baseline_asset_identities_preserved=True)
return updated,result
def _root_controls_bounded(raw,layout,control_ids,maximum,*,allow_missing=False):
if not isinstance(control_ids,set)or not 1<=len(control_ids)<=maximum or any(type(i)is not int or not 0<i<=0xffffffff for i in control_ids):raise ValueError('Bounded actual native control FileDataIDs required')
found=defaultdict(list)
for group in layout['groups']:
ident=0
for index,(delta,)in enumerate(struct.iter_unpack('<I',raw[group['ids_offset']:group['ckeys_offset']])):
ident+=delta
if ident in control_ids:found[ident].append(dict(group=group,content_key=raw[group['ckeys_offset']+16*index:group['ckeys_offset']+16*(index+1)].hex()))
ident+=1
if not allow_missing and set(found)!=control_ids:raise ValueError('Control FileDataID absent from actual native ROOT')
return dict(found)
def root_controls(raw,layout,control_ids):
return _root_controls_bounded(raw,layout,control_ids,32)
def root_controls_batch(raw,layout,control_ids,*,allow_missing=False):
"""Resolve a bounded registered family in one pass over the original ROOT."""
if type(allow_missing)is not bool:raise ValueError('Explicit missing-control policy required')
return _root_controls_bounded(raw,layout,control_ids,MAX_ASSET_BATCH,allow_missing=allow_missing)
def root_content_controls_batch(raw,layout,content_keys,control_id):
"""Find existing content keys in the native control's groups in one pass.
CKey matches identify possible existing CASC content; callers must retain
any additional source/native byte-equality requirements as a separate hold.
"""
if (not isinstance(content_keys,set) or not 1<=len(content_keys)<=MAX_ASSET_BATCH or
any(not isinstance(k,str) or not re.fullmatch('[0-9a-f]{32}',k) for k in content_keys) or
type(control_id)is not int or not 0<control_id<=0xffffffff):
raise ValueError('Bounded content keys and native group control required')
wanted={bytes.fromhex(k):k for k in content_keys};found=defaultdict(list);allowed=set()
for group in layout['groups']:
identity=tuple(group[k] for k in ('locale','flags1','flags2','flags3'));ident=0
for index,(delta,) in enumerate(struct.iter_unpack('<I',raw[group['ids_offset']:group['ckeys_offset']])):
ident+=delta
if ident==control_id:allowed.add(identity)
offset=group['ckeys_offset']+16*index;key=raw[offset:offset+16]
if key in wanted:
matches=found[wanted[key]]
if len(matches)>=4096:raise ValueError('Existing content-key association is too ambiguous')
matches.append({'file_data_id':ident,'group_identity':identity})
ident+=1
if not allowed:raise ValueError('Native group control absent from actual ROOT')
return {key:[r for r in values if r['group_identity'] in allowed] for key,values in found.items()
if any(r['group_identity'] in allowed for r in values)}
def extend_root(raw,additions,*,expected_root_md5,reserved_gap_ids=None):
"""Append named-package IDs using witnessed native resource group headers.
All old group bytes remain bit-identical. New IDs must be strictly above
the actual native maximum unless an explicit, parent-absent reserved gap is supplied. Source item IDs are never interpreted as file IDs.
New nameless groups precede old groups to preserve hashless-first ordering.
"""
if not isinstance(expected_root_md5,str)or not re.fullmatch('[0-9a-f]{32}',expected_root_md5):raise ValueError('Explicit native ROOT content pin required')
layout=root_groups(raw)
if layout['root_md5']!=expected_root_md5:raise ValueError('Native ROOT content pin differs')
if not isinstance(additions,list)or not 1<=len(additions)<=MAX_ASSET_BATCH:raise ValueError('Bounded additive asset records required')
if reserved_gap_ids is not None and (not isinstance(reserved_gap_ids,set) or not reserved_gap_ids or any(type(i)is not int or not 0<i<=0xffffffff for i in reserved_gap_ids)):raise ValueError('Explicit bounded reserved gap IDs required')
ids=set();paths=set();wanted=set()
for row in additions:
if not isinstance(row,dict)or set(row)!={'file_data_id','path','content_key','native_group_control'}:raise ValueError('Complete additive asset identity required')
ident=row['file_data_id'];control=row['native_group_control'];path=row['path']
if type(ident)is not int or not 0<ident<=0xffffffff or (ident<=layout['max_file_data_id'] and (reserved_gap_ids is None or ident not in reserved_gap_ids)) or ident in ids:raise ValueError('Asset ID collision/outside additive namespace')
if type(control)is not int or not 0<control<=layout['max_file_data_id']:raise ValueError('Actual native resource type control required')
if not isinstance(path,str)or len(path)>256 or not re.fullmatch('[a-z0-9_./-]+',path)or any(p in('','.','..')for p in path.split('/'))or path in paths:raise ValueError('Unique safe compatibility asset path required')
if not isinstance(row['content_key'],str)or not re.fullmatch('[0-9a-f]{32}',row['content_key']):raise ValueError('Asset content MD5 required')
ids.add(ident);paths.add(path);wanted.add(control)
if reserved_gap_ids is not None:
if reserved_gap_ids!={i for i in ids if i<=layout['max_file_data_id']}:raise ValueError('Reserved gap IDs must exactly match additions below current maximum')
if root_controls_batch(raw,layout,reserved_gap_ids,allow_missing=True):raise ValueError('Reserved gap ID already exists in parent ROOT')
# Reuse the bounded metadata reader for disjoint control subsets.
# A cumulative registry can retain more than32 original role controls.
if len(wanted)<=32:
controls=root_controls(raw,layout,wanted)
else:
controls={}
ordered_controls=sorted(wanted)
for start in range(0,len(ordered_controls),32):
controls.update(root_controls(raw,layout,set(ordered_controls[start:start+32])))
batches=defaultdict(list)
for row in additions:
candidates=[r['group']for r in controls[row['native_group_control']]if r['group']['flags1']==0 and r['group']['name_hashes_offset']is None]
headers={(g['locale'],g['flags1'],g['flags2'],g['flags3'])for g in candidates}
if len(headers)!=1:raise ValueError('Resource control lacks one neutral nameless group header')
batches[next(iter(headers))].append(row)
new_groups=[]
for(locale,f1,f2,f3),rows in sorted(batches.items()):
rows=sorted(rows,key=lambda r:r['file_data_id']);deltas=[];previous=0
for row in rows:deltas.append(row['file_data_id']-previous);previous=row['file_data_id']+1
new_groups.append(struct.pack('<4IB',len(rows),locale,f1,f2,f3)+struct.pack('<'+str(len(rows))+'I',*deltas)+b''.join(bytes.fromhex(r['content_key'])for r in rows))
header=bytearray(raw[:24]);struct.pack_into('<I',header,12,layout['total_records']+len(additions));extra=b''.join(new_groups);result=bytes(header)+extra+raw[24:]
checked=root_groups(result)
if checked['total_records']!=layout['total_records']+len(additions)or checked['named_records']!=layout['named_records']or result[24+len(extra):]!=raw[24:]:raise ValueError('Original native ROOT preservation failed')
return result,dict(kind='additive-native-root-stage',original_root_md5=expected_root_md5,staged_root_md5=checked['root_md5'],original_records=layout['total_records'],new_records=len(additions),original_groups_bit_identical=True,resource_controls=sorted(wanted),file_data_id_min=min(ids),file_data_id_max=max(ids),installed=False,engine_loaded=False,encoding_and_storage_publication_required=True)
def extend_existing_root_groups(raw,additions,*,expected_root_md5):
"""Preserve native group order/count instead of prepending duplicate headers.
Reuse the strict resource-control and ID collision checks above. Only the
witnessed nameless native groups grow; existing delta/CKey prefixes remain
byte-identical. This is closer to the observed native ROOT organization,
not proof of the native client's cache/lifecycle acceptance.
"""
expanded,audit=extend_root(raw,additions,expected_root_md5=expected_root_md5)
old=root_groups(raw);temporary=root_groups(expanded)
new_group_count=len(temporary['groups'])-len(old['groups'])
key=lambda g:(g['locale'],g['flags1'],g['flags2'],g['flags3'])
pending={key(g):g for g in temporary['groups'][:new_group_count]}
for identity in pending:
if sum(key(g)==identity for g in old['groups'])!=1:
raise ValueError('Need one exact native group for in-place extension')
blocks=[];changed=0
for group in old['groups']:
addition=pending.get(key(group))
if addition is None:blocks.append(raw[group['start']:group['end']]);continue
if group['name_hashes_offset']is not None:raise ValueError('Only native nameless groups may grow')
old_deltas=raw[group['ids_offset']:group['ckeys_offset']]
added_deltas=bytearray(expanded[addition['ids_offset']:addition['ckeys_offset']])
last=-1
for(delta,)in struct.iter_unpack('<I',old_deltas):last+=delta+1
first=struct.unpack_from('<I',added_deltas)[0]
if first<=last:raise ValueError('New group IDs overlap native range')
struct.pack_into('<I',added_deltas,0,first-last-1)
count=group['count']+addition['count']
header=struct.pack('<4IB',count,group['locale'],group['flags1'],group['flags2'],group['flags3'])
old_ckeys=raw[group['ckeys_offset']:group['end']]
added_ckeys=expanded[addition['ckeys_offset']:addition['end']]
blocks.append(header+old_deltas+added_deltas+old_ckeys+added_ckeys);changed+=1
result=expanded[:24]+b''.join(blocks);checked=root_groups(result)
if len(checked['groups'])!=len(old['groups'])or checked['total_records']!=old['total_records']+len(additions):
raise ValueError('Native ROOT group/count preservation failed')
for before,after in zip(old['groups'],checked['groups']):
if key(before)!=key(after):raise ValueError('Native ROOT group order changed')
size=before['count']
if (raw[before['ids_offset']:before['ckeys_offset']]!=result[after['ids_offset']:after['ids_offset']+size*4]or
raw[before['ckeys_offset']:before['ckeys_offset']+size*16]!=result[after['ckeys_offset']:after['ckeys_offset']+size*16]):
raise ValueError('Native ROOT ID/CKey prefix changed')
audit=dict(audit,staged_root_md5=checked['root_md5'],strategy='extend-existing-witnessed-native-groups',
original_groups_bit_identical=False,original_group_count_preserved=True,
original_group_order_preserved=True,original_id_and_content_key_prefixes_bit_identical=True,
changed_groups=changed,native_engine_acceptance_verified=False)
return result,audit
def verify_native_asset_reuse(asset_manifest,native_encoding,client,output,exporter,*,batch_exporter=None):
"""Batch-prove exact public payload reuse using the existing local exporter.
This parameterizes the prior publication driver's readback step. It writes
proof files only; it never changes client storage, configs or a game session.
Content-key equality/size alone is insufficient: compare actual local bytes.
"""
import json
from pathlib import Path
import subprocess
from item_package_preflight import read_public_json,bounded_digest
asset_manifest,native_encoding,client,output,exporter=map(Path,(asset_manifest,native_encoding,client,output,exporter))
assets,manifest_pin=read_public_json(asset_manifest,33554432)
if not isinstance(assets.get('assets'),list)or not 1<=len(assets['assets'])<=8192:raise ValueError('Bounded registered asset stage required')
# Pinned70334 ENCODING is149293631bytes, larger than a single ROOT/DB2.
# This scoped bound does not relax their separate schema/input limits.
encoding_bound=268435456
encoding_pin=bounded_digest(native_encoding,encoding_bound);raw=native_encoding.read_bytes()
layout=encoding_layout(raw)
entries=dict(row for _,page in layout['sections']['content']for row in _encoding_entries(page,'content'))
exporter_pin=bounded_digest(exporter,67108864);identity=client/'.build.info';client_pin=bounded_digest(identity,1048576)
if output.exists()or output.is_symlink():raise ValueError('Fresh readback evidence directory required')
output.mkdir(parents=True);matches=[];skipped=0;pending=[];payloads={}
batch_pin=bounded_digest(Path(batch_exporter),67108864)if batch_exporter is not None else None
for asset in assets['assets']:
name=asset.get('file','');ckey=asset.get('content_key','');size=asset.get('bytes')
if (not isinstance(name,str)or not name or Path(name).name!=name or
not isinstance(ckey,str)or not re.fullmatch('[0-9a-f]{32}',ckey)or
type(size)is not int or not 0<size<=67108864):raise ValueError('Pinned public asset identity required')
entry=entries.get(bytes.fromhex(ckey))
if entry is None:skipped+=1;continue
if int.from_bytes(entry[1:6],'big')!=size:raise ValueError('Native content-key size differs')
source=asset_manifest.parent/name
if bounded_digest(source,67108864)!=asset.get('sha256'):raise ValueError('Staged asset bytes changed')
payload=source.read_bytes()
if len(payload)!=size or hashlib.md5(payload).hexdigest()!=ckey:raise ValueError('Staged asset content key differs')
pending.append((asset,entry));payloads[ckey]=payload
if batch_exporter is not None and pending:
request=output/'content-requests.txt'
request.write_text(''.join(key+' '+str(len(payloads[key]))+'\n'for key in sorted(payloads)))
subprocess.run([str(batch_exporter),'--export-ckeys',str(client),str(request),str(output)],check=True,timeout=120)
for asset,entry in pending:
ckey=asset['content_key'];size=asset['bytes'];payload=payloads[ckey]
destination=output/(ckey+'.bin')
if not destination.exists() and batch_exporter is None:
subprocess.run([str(exporter),str(client),ckey,str(size),str(destination)],check=True,stdout=subprocess.DEVNULL,timeout=30)
if destination.is_symlink()or destination.read_bytes()!=payload:raise ValueError('Native readback differs from staged bytes')
matches.append(dict(content_key=ckey,file_data_id=asset.get('file_data_id'),bytes=size,sha256=hashlib.sha256(payload).hexdigest(),original_encoding_keys=[entry[i:i+16].hex()for i in range(22,len(entry),16)],native_casc_readback_identical=True))
if (bounded_digest(asset_manifest,33554432)!=manifest_pin or bounded_digest(native_encoding,encoding_bound)!=encoding_pin or
bounded_digest(exporter,67108864)!=exporter_pin or bounded_digest(identity,1048576)!=client_pin):raise ValueError('Readback inputs changed during batch')
if batch_exporter is not None and bounded_digest(Path(batch_exporter),67108864)!=batch_pin:raise ValueError('Batch exporter changed during readback')
report=dict(kind='registered-assets-native-content-reuse-readback',batch_exporter_sha256=batch_pin,asset_manifest_sha256=manifest_pin,native_encoding_sha256=encoding_pin,
exporter_sha256=exporter_pin,client_build_info_sha256=client_pin,matches=matches,absent_from_original_encoding=skipped,
installed=False,engine_loaded=False,client_storage_modified=False)
(output/'report.json').write_text(json.dumps(report,indent=2)+'\n')
return report
def preserve_registered_tvfs_variants(raw,root_audit,assets,framed):
"""Rebind only existing same-ID native paths recorded by the ROOT stage."""
from casc_tvfs import replace_references
replacements=registered_variant_replacements(root_audit)
if not replacements:return raw,None
fields=('content_key','encoding_key','decoded_size','encoded_size','encoding_spec')
references={}
for ident,key in replacements.items():
candidates=[{k:framed[a['file']][k]for k in fields}for a in assets if a['content_key']==key]
if not candidates or any(row!=candidates[0]for row in candidates):
raise ValueError('Registered native variant lacks one preserved framed payload')
references[f'{ident:08X}'+key.upper()]=candidates[0]
return replace_references(raw,references,expected_md5=hashlib.md5(raw).hexdigest())
def stage_framed_native_assets(asset_manifest,native_context,reuse_directory,output,*,retained_asset_frames=None,retained_native_content_entries=None,retained_download_controls=None):
"""Compose one offline native70334 asset publication through tested primitives.
Retains original ENCODING selections, DOWNLOAD metadata and TVFS paths.
Byte-identical assets share storage while their distinct FileDataIDs survive.
This does not assemble/write client storage or change executable build data.
A fresh compaction recipe may supply previously accepted encoded frame rows
keyed by registered filename. It binds their registered SHA/CKey/size and
reuses their encoded files; only the new archive writer reads those bytes.
"""
import json
from pathlib import Path
from item_package_preflight import read_public_json,bounded_digest
from casc_tvfs import extend_files,layout as tvfs_layout,paths,spans,container_record,replace_references
source,context,proof_dir,out=map(Path,(asset_manifest,native_context,reuse_directory,output))
assets,asset_pin=read_public_json(source,33554432)
proof,proof_pin=read_public_json(proof_dir/'report.json',33554432)
if proof.get('asset_manifest_sha256')!=asset_pin:raise ValueError('Native reuse proof belongs to different asset stage')
if not isinstance(assets.get('assets'),list)or not 1<=len(assets['assets'])<=MAX_ASSET_BATCH-6:raise ValueError('Framed asset batch bound')
expected={'target-encoding.bin':'277d57a2b135f956642242b2422f85bf',
'target-download.bin':'a8fd4c417e540e4ba14b01b1912c55ad',
'native-tvfs-default.bin':'d210a383412ad7d7eabda4a9d9d21433',
'native-vfs-root.bin':'3928e0afa0bfba09e1e7a045eabd91be'}
inputs={};native={}
def read(path,bound=268435456):
pin=bounded_digest(path,bound);raw=path.read_bytes()
if hashlib.sha256(raw).hexdigest()!=pin:raise ValueError('Framing input changed while reading')
inputs[path]=(bound,pin);return raw
for name,digest in expected.items():
native[name]=read(context/name)
if hashlib.md5(native[name]).hexdigest()!=digest:raise ValueError('Pinned70334 native metadata differs: '+name)
if hashlib.sha256(native['target-encoding.bin']).hexdigest()!=proof.get('native_encoding_sha256'):raise ValueError('Native encoding differs from reuse proof')
controls=json.loads(read(context/'download-native-controls.json',1048576))
controls={r['file_data_id']:r['encoded_key']for r in controls}
if retained_download_controls is not None:
if not isinstance(retained_download_controls,dict)or len(retained_download_controls)>MAX_ASSET_BATCH:
raise ValueError('Bounded retained native DOWNLOAD controls required')
for group,key in retained_download_controls.items():
if (type(group)is not int or group<=0 or not isinstance(key,str)or
not re.fullmatch('[0-9a-f]{32}',key)or key=='0'*32 or
group in controls and controls[group]!=key):
raise ValueError('Retained native DOWNLOAD control conflicts')
controls[group]=key
identity=json.loads(read(context/'tvfs-default-identity.json',1048576))
if (identity.get('ckey'),identity.get('vfs_number'),identity.get('name'))!=('d210a383412ad7d7eabda4a9d9d21433',820,'0001F3F600000000'):raise ValueError('Pinned native TVFS identity differs')
if retained_asset_frames is not None and (not isinstance(retained_asset_frames,dict)or
set(retained_asset_frames)!={a['file']for a in assets['assets']}):
raise ValueError('Complete retained current asset framing map required')
retained_inputs={};reused={}
for row in proof.get('matches',[]):
if row.get('native_casc_readback_identical')is not True or not re.fullmatch('[0-9a-f]{32}',row.get('content_key','')):raise ValueError('Explicit native payload byte proof required')
if retained_asset_frames is not None:
if row['content_key']not in(retained_native_content_entries or {}):
raise ValueError('Retained native reuse needs its accepted current EN entry')
continue
raw=read(proof_dir/(row['content_key']+'.bin'),67108864)
if hashlib.sha256(raw).hexdigest()!=row['sha256']:raise ValueError('Readback evidence payload changed')
reused[row['content_key']]=raw
if out.exists()or out.is_symlink():raise ValueError('Fresh framed asset output required')
out.mkdir(parents=True);(out/'decoded').mkdir();rows=[];by_encoded={};by_source={};download_rows={}
def publish(raw,chunks,label):
if b''.join(body for body,method in chunks)!=raw:raise ValueError('Frame chunks differ from decoded bytes')
encoded,row=blte_framed(chunks);key=row['encoding_key']
if key in by_encoded:
old=by_encoded[key]
if (old['content_key']!=row['content_key']or old['encoded_size']!=len(encoded)or
old.get('file')is not None and(out/old['file']).read_bytes()!=encoded):raise ValueError('Framed payload identity collision')
old['source_files'].append(label);by_source[label]=old;return old
row.update(encoding_spec=blte_frame_spec(chunks),file=key+'.blte',decoded_file='decoded/'+label,source_file=label,source_files=[label])
(out/row['file']).write_bytes(encoded);(out/row['decoded_file']).write_bytes(raw)
rows.append(row);by_encoded[key]=row;by_source[label]=row;return row
for asset in assets['assets']:
name=asset['file']
if Path(name).name!=name:raise ValueError('Flat registered asset filename required')
if retained_asset_frames is None:
raw=read(source.parent/name,67108864)
if hashlib.sha256(raw).hexdigest()!=asset['sha256']or hashlib.md5(raw).hexdigest()!=asset['content_key']:raise ValueError('Registered payload differs')
row=publish(raw,[(raw,'N')],name)
else:
old=retained_asset_frames[name];baseline=old.get('baseline_IDX_relationship')
if (old.get('registered_sha256')!=asset['sha256']or old.get('content_key')!=asset['content_key']
or old.get('decoded_size')!=asset['bytes']):
raise ValueError('Retained registered framing identity differs')
if baseline is not None:
if (not isinstance(baseline,dict)or baseline.get('qualified_baseline_relationship')is not True
or baseline.get('all_original_IDX_rows_preserved_unchanged')is not True
or any(baseline.get(k)!=old.get(k)for k in('content_key','encoding_key','decoded_size','encoded_size'))
or not isinstance(baseline.get('matches'),list)or not 1<=len(baseline['matches'])<=2):
raise ValueError('Qualified original baseline framing relationship required')
for match in baseline['matches']:
rawrow=bytes.fromhex(match['index_row_18B_hex'])
if (len(rawrow)!=18 or rawrow[:9]!=bytes.fromhex(old['encoding_key'])[:9]
or match.get('within_original_local_B_base')is not True
or match.get('position_below_header_maximum')is not True):
raise ValueError('Retained native index binding differs')
# Both genuine header/nested entries remain in the immutable
# baseline. No new chooser, payload export, or physical copy.
path=None
else:
path=Path(old['file'])
if (not path.is_absolute()or path.is_symlink()or not path.is_file()
or path.stat().st_size!=old.get('encoded_size')):
raise ValueError('Retained encoded file identity differs')
st=path.stat();retained_inputs[path]=(st.st_dev,st.st_ino,st.st_size,st.st_mtime_ns)
key=old['encoding_key'];reviewed_encoding_spec(old['encoding_spec'])
if not re.fullmatch('[0-9a-f]{32}',key):raise ValueError('Retained complete EKey required')
if key in by_encoded:
row=by_encoded[key]
if any(row[k]!=old[k]for k in('content_key','decoded_size','encoded_size','encoding_spec')):
raise ValueError('Retained framing alias identity collision')
row['source_files'].append(name)
else:
row={k:old[k]for k in('content_key','encoding_key','decoded_size','encoded_size','encoding_spec')}
row.update(file=str(path)if path is not None else None,source_file=name,source_files=[name],retained_encoded_payload=True)
if baseline is not None:row['retained_baseline_binding']=baseline
rows.append(row);by_encoded[key]=row
by_source[name]=row
addition=dict(encoding_key=row['encoding_key'],encoded_size=row['encoded_size'],native_control_ekey=controls[asset['native_group_control']])
if row['encoding_key']in download_rows and download_rows[row['encoding_key']]!=addition:raise ValueError('Identical payload uses conflicting native DOWNLOAD control')
download_rows[row['encoding_key']]=addition
raw=read(source.parent/'root.bin')
if hashlib.md5(raw).hexdigest()!=assets['root']['staged_root_md5']:raise ValueError('Registered ROOT hash differs')
root=publish(raw,[(raw[i:i+262144],'Z')for i in range(0,len(raw),262144)],'root.bin')
download_rows[root['encoding_key']]=dict(encoding_key=root['encoding_key'],encoded_size=root['encoded_size'],native_control_ekey='bb32f86e4e8e83adf2be8751c2e958b8')
raw,download_audit=extend_download(native['target-download.bin'],list(download_rows.values()),expected_download_md5=expected['target-download.bin'])
dl=download_layout(raw);download=publish(raw,[(raw[:11],'N'),(raw[11:dl['entries_end']],'N'),(raw[dl['entries_end']:],'Z')],'download.bin')
additions=[dict(file_data_id=a['file_data_id'],**{k:by_source[a['file']][k]for k in('content_key','encoding_key','decoded_size','encoded_size','encoding_spec')})for a in assets['assets']]
raw,child_audit=extend_files(native['native-tvfs-default.bin'],additions,expected_md5=expected['native-tvfs-default.bin'])
raw,variant_audit=preserve_registered_tvfs_variants(raw,assets['root'],assets['assets'],by_source)
if variant_audit:
child_audit.update(staged_md5=hashlib.md5(raw).hexdigest(),native_texture_aliases=variant_audit)
child=publish(raw,[(raw[i:i+262144],'Z')for i in range(0,len(raw),262144)],'tvfs-default.bin')
raw=native['native-vfs-root.bin'];header=tvfs_layout(raw);index=paths(raw,header);refs={}
if [n for n,e in index.items()if spans(raw,e,header)[0]['encoding_key_prefix']==identity['ekey'][:18]]!=[identity['name']]:raise ValueError('Native TVFS child ownership differs')
for name,row in ((identity['name'],child),('.root',root)):
control=container_record(raw,spans(raw,index[name],header)[0],header)
refs[name]={k:row[k]for k in('content_key','encoding_key','decoded_size','encoded_size')};refs[name]['encoding_spec']=control['encoding_spec']
raw,parent_audit=replace_references(raw,refs,expected_md5=expected['native-vfs-root.bin'])
parent=publish(raw,[(raw[i:i+262144],'Z')for i in range(0,len(raw),262144)],'tvfs-root.bin')
fields=('content_key','encoding_key','decoded_size','encoded_size','encoding_spec')
updated,audit=extend_encoding(native['target-encoding.bin'],[{k:r[k]for k in fields}for r in rows],expected_encoding_md5=expected['target-encoding.bin'],reused_native_payloads=reused,retained_native_content_entries=retained_native_content_entries)
raw,encoded,encoding=frame_encoding(updated);encoding.update(file=encoding['encoding_key']+'.blte',decoded_file='encoding.bin')
(out/encoding['file']).write_bytes(encoded);(out/'encoding.bin').write_bytes(raw)
if any(bounded_digest(path,bound)!=pin for path,(bound,pin)in inputs.items())or bounded_digest(source,33554432)!=asset_pin or bounded_digest(proof_dir/'report.json',33554432)!=proof_pin:raise ValueError('Framing input changed before publication')
if any((path.stat().st_dev,path.stat().st_ino,path.stat().st_size,path.stat().st_mtime_ns)!=token for path,token in retained_inputs.items()):
raise ValueError('Retained encoded frame changed during metadata composition')
report=dict(kind='framed-native-asset-publication-stage',assets=rows,root=root,download=download,encoding=encoding,audit=audit,download_audit=download_audit,
tvfs=dict(root=parent,child=child,child_number=820,child_name=identity['name'],child_audit=child_audit,parent_audit=parent_audit,metadata_absent_from_original_download=True),
registered_asset_count=len(assets['assets']),shared_payload_aliases=sum(len(r['source_files'])-1 for r in rows),
asset_manifest_sha256=asset_pin,native_reuse_proof_sha256=proof_pin,input_sha256={str(p):pin for p,(_,pin)in inputs.items()},
all_objects_explicitly_framed=True,retained_registered_frames=len(retained_asset_frames or {}),decoded_registered_payloads_reread=retained_asset_frames is None,installed=False,engine_loaded=False)
(out/'manifest.json').write_text(json.dumps(report,indent=2)+'\n');return report
if __name__=='__main__':
import argparse,json
from pathlib import Path
from client_installation import COPY,inspect_installation
p=argparse.ArgumentParser(description='Read-only local byte proof for existing registered CASC assets; no installation')
modes=p.add_mutually_exclusive_group(required=True)
modes.add_argument('--verify-native-content',action='store_true');modes.add_argument('--stage-framed-assets',action='store_true')
p.add_argument('--source-manifest',type=Path,required=True);p.add_argument('--native-encoding',type=Path)
p.add_argument('--batch-exporter',type=Path,help='Optional strict one-storage-open content exporter for reuse proof')
p.add_argument('--native-context',type=Path);p.add_argument('--reuse-directory',type=Path)
p.add_argument('--output',type=Path,required=True)
a=p.parse_args();root=Path(__file__).resolve().parents[1]
if not a.output.absolute().is_relative_to(root/'runtime')or a.output.absolute().resolve()!=a.output.absolute():p.error('Owned runtime output required')
if a.stage_framed_assets:
if not a.native_context or not a.reuse_directory or a.native_encoding or a.batch_exporter:p.error('Framing requires native context/reuse directory only')
r=stage_framed_native_assets(a.source_manifest,a.native_context,a.reuse_directory,a.output)
print(json.dumps(dict(registered_assets=r['registered_asset_count'],unique_framed_payloads=len(r['assets']),shared_payload_aliases=r['shared_payload_aliases'],installed=False)))
else:
if not a.native_encoding or a.native_context or a.reuse_directory:p.error('Readback requires native encoding only')
if inspect_installation(COPY)['version']!='1.60.1.70334':p.error('Pinned target client version required')
r=verify_native_asset_reuse(a.source_manifest,a.native_encoding,COPY,a.output,root/'build/casc-manifest-export',batch_exporter=a.batch_exporter)
print(json.dumps(dict(exact_native_payload_matches=len(r['matches']),absent_from_original_encoding=r['absent_from_original_encoding'],installed=False)))