Files
WoW-Hybrid-gateway/ops/item_icon_preflight.py
2026-11-23 03:28:32 +02:00

381 lines
29 KiB
Python

#!/usr/bin/env python3
"""Compare observed Octo item-icon references with local target listfile names.
Pure dependency component: no archive extraction, source-winner selection,
installation, client calls, SQL or network. Filename agreement is not asset proof.
"""
import argparse,hashlib,json,re
from collections import Counter
from pathlib import Path
from item_package_preflight import ROOT,read_public_json,bounded_digest
from turtle_data import DBC,ITEM_DISPLAY_FIELDS
from octo_client_data import canonical_sha256,observed_analysis_context
MAX_LISTFILE_BYTES=268435456
MAX_LISTFILE_LINES=5000000
MAX_PATHS_PER_ID=16
MAX_ICON_REFERENCE_MATCHES=65536
# The existing observed IR retains contextual assets as well as <=100,000 DBC
# rows. Its bound is separate from the unchanged candidate/DBC input limits.
MAX_OBSERVED_INVENTORY_BYTES=134217728
def sha(raw):return hashlib.sha256(raw).hexdigest()
def hash_value(value):return isinstance(value,str) and re.fullmatch('[0-9a-f]{64}',value) is not None
def read_observed_inventory(path):return read_public_json(path,MAX_OBSERVED_INVENTORY_BYTES)
def reviewed_icon_column(text):
marker='BUILD 1.0.0.3980-1.12.3.6141\n'
if text.count(marker)!=1:raise ValueError('Missing/ambiguous reviewed legacy ItemDisplayInfo DBD block')
block=text.split(marker,1)[1].split('\n\n',1)[0];parsed=[]
for line in block.splitlines():
if not line or line.startswith(('BUILD','COMMENT')):continue
line=re.sub(r'^\$[^$]+\$','',line)
match=re.fullmatch(r'(\w+)(?:<32>)?(?:\[(\d+)\])?',line)
if not match:raise ValueError('Unreviewed legacy ItemDisplayInfo DBD syntax')
parsed.append((match[1],int(match[2] or 1)))
expected=[('ID',1),('ModelName',2),('ModelTexture',2),('InventoryIcon',1),('GeosetGroup',3),('Flags',1),('SpellVisualID',1),('GroupSoundIndex',1),('HelmetGeosetVisID',2),('Texture',8),('ItemVisual',1)]
if parsed!=expected:raise ValueError('Legacy ItemDisplayInfo column semantics changed')
column=ITEM_DISPLAY_FIELDS['InventoryIcon'][0]
if column!=5:raise ValueError('Shared InventoryIcon column differs from reviewed disk layout')
return column
def normalize_icon(value,*,source=False):
"""ASCII case/slashes only; bare source InventoryIcon uses its icon namespace.
Do not invent texture extensions, basename aliases or alternate resources.
"""
if not isinstance(value,str) or not 0<len(value)<=512 or not re.fullmatch(r'[A-Za-z0-9_./\\-]+',value):raise ValueError('Unsupported icon path characters/length')
value=value.replace('\\','/').lower();parts=value.split('/')
if any(part in ('','.','..') for part in parts):raise ValueError('Unsafe icon path')
if source and len(parts)==1:value='interface/icons/'+value
if not value.startswith('interface/icons/'):raise ValueError('Icon path outside reviewed interface/icons namespace')
filename=value.rsplit('/',1)[1];extension=None;stem=value
if '.' in filename:
stem,extension=value.rsplit('.',1)
if extension not in ('blp','tga'):raise ValueError('Unreviewed texture extension')
return dict(path=value,stem=stem,extension=extension)
SOURCE_EMPTY_ICON = 'source-empty-inventory-icon'
def empty_icon_reference(entry, display_id):
return dict(entry=entry, source_display_id=display_id, source_icon='',
policy=SOURCE_EMPTY_ICON, native_icon_file_data_id=0)
def listfile_index(stream,wanted,source_icons=None,*,max_wanted=4096):
"""One bounded pass for target IDs and exact source-icon naming references.
Source stems can match explicit .blp/.tga paths, but no extension is selected.
These naming references do not establish installed assets or safe overrides.
"""
# The bulk appearance preflight shares this reader with a separately bounded
# larger request set. Existing icon callers keep their4096-ID default.
if type(max_wanted) is not int or not 1<=max_wanted<=65536:raise ValueError('Target FileDataID budget bound')
if not isinstance(wanted,set) or len(wanted)>max_wanted or any(type(i) is not int or not 0<i<=0xffffffff for i in wanted):raise ValueError('Target FileDataID bound')
if source_icons is not None:
if not isinstance(source_icons,set) or len(source_icons)>4096:raise ValueError('Source icon-key bound')
for icon in source_icons:
if not isinstance(icon,str) or normalize_icon(icon)['path']!=icon:raise ValueError('Noncanonical source icon key')
references={};matches=0;found={};digest=hashlib.sha256();total=0;lines=0
while True:
raw=stream.readline(4097)
if not raw:break
total+=len(raw);lines+=1
if len(raw)>4096 or total>MAX_LISTFILE_BYTES or lines>MAX_LISTFILE_LINES:raise ValueError('Listfile byte/line bound')
digest.update(raw);line=raw.rstrip(b'\r\n')
if lines==1:line=line.removeprefix(b'\xef\xbb\xbf')
key,separator,path=line.partition(b';')
if not separator or not re.fullmatch(rb'[0-9]{1,10}',key) or int(key)>0xffffffff:raise ValueError('Malformed local listfile row')
ident=int(key)
if not 0<len(path)<=512:
if ident in wanted:raise ValueError('Selected target filename bound')
continue
try:name=path.decode('utf-8')
except UnicodeDecodeError:
if ident in wanted:raise ValueError('Selected target filename encoding') from None
continue
if ident in wanted:
found.setdefault(ident,set()).add(name)
if len(found[ident])>MAX_PATHS_PER_ID:raise ValueError('Ambiguous target alias count bound')
if not source_icons or not ident:continue
try:normalized=normalize_icon(name)
except ValueError:continue
if not normalized['extension']:continue
for icon in {normalized['path'],normalized['stem']} & source_icons:
ids=references.setdefault(icon,{});paths=ids.setdefault(ident,set())
if name in paths:continue
paths.add(name);matches+=1
if len(ids)>MAX_PATHS_PER_ID or len(paths)>MAX_PATHS_PER_ID or matches>MAX_ICON_REFERENCE_MATCHES:raise ValueError('Exact source-icon reference bound')
meta=dict(sha256=digest.hexdigest(),bytes=total,lines=lines)
if source_icons is not None:
meta['source_icon_references']={icon:[dict(file_data_id=ident,listfile_names=sorted(paths)) for ident,paths in sorted(ids.items())] for icon,ids in sorted(references.items())}
return {key:sorted(value) for key,value in sorted(found.items())},meta
def source_icon_keys(items,dbc,icon_column=ITEM_DISPLAY_FIELDS['InventoryIcon'][0]):
if icon_column!=5:raise ValueError('Unreviewed InventoryIcon column')
keys=set()
for item in items:
row=dbc.by_id.get(item['source_display_id'])
if row is None:continue
try:keys.add(normalize_icon(dbc.string(row[icon_column]),source=True)['path'])
except (ValueError,UnicodeDecodeError):continue
return keys
def observed_item_display(observed,raw):
"""Consume existing validated observed context; never resolve archive priority."""
if not isinstance(observed,dict) or observed.get('kind')!='octo-observed-partial-dependency-inventory':raise ValueError('Require existing observed-content inventory')
validation=observed.get('validation',{})
if (validation.get('kind')!='octo-loaded-content-validation' or validation.get('trace_contracts_validated') is not True or
validation.get('captured_content_rehashed') is not True):raise ValueError('Observed trace/content validation missing')
rows=[row for row in validation.get('tables',[]) if row.get('table')=='ItemDisplayInfo']
inventories=[row for row in observed.get('inventories',[]) if row.get('table')=='ItemDisplayInfo']
if len(rows)!=1 or len(inventories)!=1:raise ValueError('ItemDisplayInfo was not unambiguously observed')
table=rows[0];inventory=inventories[0];source=inventory.get('source_identity',{})
if (table.get('content_status')!='matched-observed-bytes' or source.get('provenance')!='selected-by-pinned-evidence' or
source.get('selection_scope')!='observed-file-content-only' or inventory.get('observed_content',{}).get('status')!='matched-observed-bytes'):
raise ValueError('Candidate archive data cannot replace observed ItemDisplayInfo')
if (not isinstance(source.get('source_installation'),str) or not source['source_installation'] or not hash_value(source.get('scan_sha256')) or
not isinstance(source.get('client_identity'),dict) or not hash_value(source['client_identity'].get('client_sha256')) or
source.get('dataset')!=observed.get('analysis_dataset')):raise ValueError('Observed source identity is incomplete')
if inventory.get('schema')!={'format':'WDBC','fields':23,'expected_reviewed_fields':23,'status':'reviewed-disk-shape'}:raise ValueError('Unreviewed observed ItemDisplayInfo schema')
for key in ('source_installation','scan_sha256','client_identity'):
if source.get(key)!=validation.get(key) or observed.get(key)!=validation.get(key):raise ValueError('Observed item-data context mismatch')
observed_analysis_context(observed,validation,source)
for key in ('observation_sha256','loader_analysis_sha256'):
if not hash_value(source.get(key)) or source[key]!=validation.get(key):raise ValueError('Observed item-data evidence hash mismatch')
if not isinstance(raw,bytes) or len(raw)>67108864 or sha(raw)!=table.get('sha256') or source.get('content_sha256')!=sha(raw) or inventory.get('candidate_sha256')!=sha(raw):raise ValueError('Captured ItemDisplayInfo bytes differ from validated observation')
class Captured:
name='ItemDisplayInfo.dbc'
def read_bytes(self):return raw
dbc=DBC(Captured(),23)
if table.get('fields')!=23 or table.get('rows')!=dbc.count or table.get('bytes')!=len(raw):raise ValueError('Observed ItemDisplayInfo disk shape differs')
records=inventory.get('records')
if not isinstance(records,list) or len(records)!=dbc.count:raise ValueError('Observed inventory record count differs')
seen=set()
for record in records:
identity=record.get('identity') if isinstance(record,dict) else None
if not isinstance(identity,list) or len(identity)!=2 or identity[0]!='ItemDisplayInfo' or type(identity[1]) is not int or identity[1] in seen:raise ValueError('Observed inventory identity differs')
ident=identity[1];seen.add(ident)
if ident not in dbc.by_id or record.get('raw_fields')!=list(dbc.by_id[ident]):raise ValueError('Observed inventory row differs from captured bytes')
return dbc,source
def selected_items(candidate):
if (not isinstance(candidate,dict) or candidate.get('kind')not in('blocked-scalar-item-metadata-candidate','blocked-owned-equipment-icon-candidate') or candidate.get('status')!='BLOCKED_NOT_INSTALLABLE' or
candidate.get('installable') is not False or candidate.get('contains_installable_record_payloads') is not False):raise ValueError('Require blocked scalar candidate, not an install package')
rows=candidate.get('selected_items')
if not isinstance(rows,list) or not 1<=len(rows)<=4096 or candidate.get('selected_count')!=len(rows):raise ValueError('Candidate selected-item bound')
seen=set()
for row in rows:
if not isinstance(row,dict) or type(row.get('entry')) is not int or not 0<row['entry']<=0x7fffffff or row['entry'] in seen:raise ValueError('Candidate source identity ambiguity')
seen.add(row['entry'])
for key in ('source_display_id','native_icon_file_data_id'):
if type(row.get(key)) is not int or not 0<=row[key]<=0xffffffff:raise ValueError('Candidate icon/display identity bound')
return sorted(rows,key=lambda row:row['entry'])
def ordinary_container_candidates(inventory,native):
"""Use the same blocked-candidate contract for a complete source bag scope.
Missing native icons stay0, never a placeholder icon or an invented item ID.
This selects naming references only; actual bag semantics/assets are still
checked by item_batch_stage before any installable records are generated.
"""
from item_package_preflight import target_index
if (inventory.get('snapshot_verification',{}).get('content_and_schema_and_ids_verified') is not True or
not isinstance(inventory.get('source_identity'),dict)):
raise ValueError('Require verified source inventory for ordinary bag scope')
basics=target_index(native,'Item');rows=inventory.get('records')
if not isinstance(rows,list) or not 1<=len(rows)<=100000:raise ValueError('Source bag inventory bound')
selected=[];seen=set()
for record in rows:
item=record.get('raw_fields') if isinstance(record,dict) else None
if not isinstance(item,dict) or record.get('identity')!=['Item',item.get('entry')]:raise ValueError('Source bag record identity differs')
entry=item.get('entry')
if type(entry)is not int or not 0<=entry<=0x7fffffff or entry in seen:raise ValueError('Ambiguous source bag identity')
seen.add(entry)
if not entry or (item.get('class'),item.get('subclass'),item.get('inventory_type'))!=(1,0,18):continue
selected.append(dict(entry=entry,source_display_id=item.get('display_id'),native_icon_file_data_id=basics.get(entry,{}).get('IconFileDataID',0)))
candidate=dict(kind='blocked-scalar-item-metadata-candidate',status='BLOCKED_NOT_INSTALLABLE',installable=False,
contains_installable_record_payloads=False,scope='ordinary-container-icon-references',source_snapshot_identity=inventory['source_identity'],
selected_items=sorted(selected,key=lambda row:row['entry']),selected_count=len(selected))
selected_items(candidate)
return candidate
def owned_equipment_candidates(components,inventory,native):
"""Join already-blocked owned equipment to the verified source snapshot.
This only selects exact source icon references for the existing preflight
and MPQ reader. It creates no item rows, assets, aliases or FileDataIDs.
"""
from item_package_preflight import target_index
if (components.get('kind')!='owned-equipment-identity-components' or components.get('build')!='1.60.1.70334'
or inventory.get('snapshot_verification',{}).get('content_and_schema_and_ids_verified')is not True
or not isinstance(inventory.get('source_identity'),dict)
or components.get('source_identity')!=inventory['source_identity']):
raise ValueError('Verified matching owned-equipment/source snapshot required')
ownership=components.get('ownership');blocked=components.get('blocked');records=inventory.get('records')
if (not isinstance(ownership,list)or not 1<=len(ownership)<=4096
or not isinstance(blocked,list)or len(blocked)>4096
or not isinstance(records,list)or not 1<=len(records)<=100000):
raise ValueError('Owned icon source scope bound')
if any(not isinstance(r,dict)or type(r.get('entry'))is not int or not 0<r['entry']<=0x7fffffff for r in ownership):raise ValueError('Owned icon identity bound')
owned={r['entry']for r in ownership};wanted=[]
if len(owned)!=len(ownership):raise ValueError('Duplicate owned icon identity')
for row in blocked:
if row.get('reason')!='ambiguous-or-missing-target-icon-reference':continue
entry=row.get('entry')
if type(entry)is not int or not 0<entry<=0x7fffffff or entry not in owned or entry in wanted:
raise ValueError('Ambiguous or unowned icon candidate')
wanted.append(entry)
source={}
for row in records:
item=row.get('raw_fields')if isinstance(row,dict)else None
if not isinstance(item,dict)or row.get('identity')!=['Item',item.get('entry')]:raise ValueError('Owned icon source record identity differs')
if item['entry']in source:raise ValueError('Duplicate owned icon source identity')
source[item['entry']]=item
basics=target_index(native,'Item');selected=[]
for entry in sorted(wanted):
item=source.get(entry)
if item is None or item.get('class')not in(2,4):raise ValueError('Owned equipment icon source missing or wrong category')
selected.append(dict(entry=entry,source_display_id=item.get('display_id'),native_icon_file_data_id=basics.get(entry,{}).get('IconFileDataID',0)))
result=dict(kind='blocked-owned-equipment-icon-candidate',status='BLOCKED_NOT_INSTALLABLE',installable=False,
contains_installable_record_payloads=False,scope='owned-equipment-missing-icon-references',
source_snapshot_identity=inventory['source_identity'],selected_items=selected,selected_count=len(selected))
selected_items(result);return result
def compare_icons(candidate,observed,raw,target_paths,icon_column=ITEM_DISPLAY_FIELDS['InventoryIcon'][0],source_references=None):
if icon_column!=5 or icon_column!=ITEM_DISPLAY_FIELDS['InventoryIcon'][0]:raise ValueError('Unreviewed InventoryIcon column')
if not isinstance(target_paths,dict) or len(target_paths)>4096:raise ValueError('Target path index bound')
for key,paths in target_paths.items():
if type(key) is not int or not 0<key<=0xffffffff or not isinstance(paths,list) or not 1<=len(paths)<=MAX_PATHS_PER_ID or any(not isinstance(path,str) or not 0<len(path)<=512 for path in paths):raise ValueError('Malformed target path index')
if source_references is not None:
if not isinstance(source_references,dict) or len(source_references)>4096:raise ValueError('Source-icon reference index bound')
references=0
for icon,values in source_references.items():
if normalize_icon(icon)['path']!=icon or not isinstance(values,list) or not 1<=len(values)<=MAX_PATHS_PER_ID:raise ValueError('Malformed source-icon reference index')
ids=set()
for value in values:
if not isinstance(value,dict) or type(value.get('file_data_id')) is not int or not 0<value['file_data_id']<=0xffffffff or value['file_data_id'] in ids:raise ValueError('Ambiguous source-icon reference identity')
ids.add(value['file_data_id']);paths=value.get('listfile_names')
if not isinstance(paths,list) or not 1<=len(paths)<=MAX_PATHS_PER_ID or any(not isinstance(path,str) or not 0<len(path)<=512 for path in paths) or len(set(paths))!=len(paths):raise ValueError('Malformed source-icon reference paths')
for path in paths:
target=normalize_icon(path)
if not target['extension'] or icon not in (target['path'],target['stem']):raise ValueError('Source-icon reference is not an exact path/stem match')
references+=len(paths)
if references>MAX_ICON_REFERENCE_MATCHES:raise ValueError('Exact source-icon reference bound')
items=selected_items(candidate);dbc,source=observed_item_display(observed,raw);rows=[]
for item in items:
row={key:item[key] for key in ('entry','source_display_id','native_icon_file_data_id')};row.update(filename_equivalent=False,logical_stem_equivalent=False,replacement_candidates=[])
display=dbc.by_id.get(item['source_display_id']);paths=target_paths.get(item['native_icon_file_data_id'],[])
if display is None:row['status']='blocked-source-display-missing'
else:
try:
icon=dbc.string(display[icon_column])
if icon == '':
row.update(status=SOURCE_EMPTY_ICON, source_icon=icon,
target_reference=empty_icon_reference(item['entry'], item['source_display_id']))
rows.append(row)
continue
old=normalize_icon(icon,source=True);row.update(source_icon=icon,normalized_source=old)
candidates=(source_references or {}).get(old['path'],[])
row['replacement_candidates']=[dict(file_data_id=value['file_data_id'],listfile_names=sorted(value['listfile_names']),
match='exact-path' if old['extension'] else 'exact-stem-extension-unverified',
status='UNVERIFIED_LISTFILE_REFERENCE',full_file_data_id_alias_inventory_verified=False,
asset_bytes_verified=False,semantic_review_verified=False,engine_acceptance_verified=False)
for value in sorted(candidates,key=lambda value:value['file_data_id'])]
row['replacement_candidate_selection']='none'
alternatives={(value['file_data_id'],normalize_icon(path)['path']) for value in candidates for path in value['listfile_names']}
row['replacement_candidate_resolution']=('ambiguous-matching-references' if len(alternatives)>1 else 'unverified-matching-reference') if candidates else 'no-exact-listfile-reference'
except (ValueError,UnicodeDecodeError):row['status']='blocked-source-icon-unsupported'
if 'status' not in row:
if not paths:row['status']='blocked-target-listfile-missing'
else:
normalized={};invalid=[]
for path in paths:
try:info=normalize_icon(path);normalized[info['path']]=info
except ValueError:invalid.append(path)
row['target_listfile_names']=sorted(set(paths))
if invalid:row['status']='blocked-target-path-unsupported'
elif len(normalized)!=1:row['status']='blocked-target-listfile-ambiguous'
else:
new=next(iter(normalized.values()));row['normalized_target']=new
if not new['extension']:row['status']='blocked-target-extension-missing'
elif old['extension'] and old['path']==new['path']:row.update(status='filename-equivalent',filename_equivalent=True,logical_stem_equivalent=True)
elif not old['extension'] and old['stem']==new['stem']:row.update(status='stem-equivalent-extension-unverified',logical_stem_equivalent=True)
else:row['status']='blocked-filename-mismatch'
rows.append(row)
return dict(kind='blocked-item-icon-reference-preflight',schema_version=1,build='1.60.1.70334',source_count=len(rows),rows=rows,
status_counts=dict(sorted(Counter(row['status'] for row in rows).items())),observed_source_context=source,item_relationship_source=candidate.get('source_snapshot_identity'),
source_item_display_sha256=sha(raw),source_observed_context_validated=True,patch_precedence_verified=False,postload_semantics_verified=False,
launcher_environment_equivalence_verified=False,addon_effects_verified=False,
asset_bytes_compared=False,engine_rendering_verified=False,dependency_complete=False,installable=False,installed=False,
limits=['Only supplied observed-content context and captured bytes are checked; observation execution is not independently reproduced.',
'Reviewed hook-profile contexts retain their distinct dataset identity; legacy, different read contracts and different loader profiles are not silently joined.',
'ASCII case/slash/icon-namespace normalization only. No fuzzy aliases, guessed archive winner or texture extension substitution.',
'Extensionless source names matching a target stem remain extension-unverified. Filename agreement does not establish equal assets or engine usability.',
'Target listfile is a local naming index, not proof of installed CASC accessibility or byte equality. Local item/public Octo database equality is not established.',
'Replacement candidates retain all exact path/stem references within bounds, not a complete alias inventory for each FileDataID. They select no winner and require strict CASC asset reads, semantic review and engine validation.',
'Launcher-environment equivalence, addon effects and post-load behavior are unverified; this comparison is not installation proof.',
'No conversion, installable record payload, generated header, client action, SQL, archive extraction or network.'])
def main():
parser=argparse.ArgumentParser(description=__doc__)
for key in ('observed-inventory','dbc','output'):parser.add_argument('--'+key,type=Path,required=True)
parser.add_argument('--candidate',type=Path)
parser.add_argument('--ordinary-container-snapshot',type=Path)
parser.add_argument('--owned-equipment-snapshot',type=Path)
parser.add_argument('--owned-equipment-components',type=Path)
parser.add_argument('--native-basic',type=Path)
parser.add_argument('--listfile',type=Path,default=Path.home()/'Projects/WoW-Hybrid/listfiles/community-listfile.csv')
parser.add_argument('--dbd',type=Path,default=Path.home()/'Projects/WoW-Hybrid/tools/WoWDBDefs/definitions/ItemDisplayInfo.dbd');args=parser.parse_args()
if not args.output.resolve().is_relative_to(ROOT/'runtime') or args.output.exists():parser.error('Require a new runtime report')
if sum(bool(v)for v in(args.candidate,args.ordinary_container_snapshot,args.owned_equipment_snapshot))!=1:parser.error('Select candidate, ordinary-container-snapshot or owned-equipment-snapshot')
if args.owned_equipment_components and not args.owned_equipment_snapshot:parser.error('Owned components require owned-equipment-snapshot')
extra_inputs=[]
if args.owned_equipment_snapshot:
if args.native_basic is None or args.owned_equipment_components is None:parser.error('Owned icon scope requires native-basic and owned-equipment-components')
from turtle_data import inventory_item_snapshot
inventory=inventory_item_snapshot(args.owned_equipment_snapshot)
native,nh=read_public_json(args.native_basic,67108864);components,coh=read_public_json(args.owned_equipment_components,67108864)
candidate=owned_equipment_candidates(components,inventory,native);ch=canonical_sha256(candidate)
extra_inputs=[(args.native_basic,nh,67108864),(args.owned_equipment_components,coh,67108864),
(args.owned_equipment_snapshot/'manifest.json',inventory['source_identity']['manifest_sha256'],4194304)]
elif args.ordinary_container_snapshot:
if args.native_basic is None:parser.error('Ordinary bag scope requires native-basic')
from turtle_data import inventory_item_snapshot
inventory=inventory_item_snapshot(args.ordinary_container_snapshot)
native,nh=read_public_json(args.native_basic,67108864)
candidate=ordinary_container_candidates(inventory,native);ch=canonical_sha256(candidate)
extra_inputs=[(args.native_basic,nh,67108864),(args.ordinary_container_snapshot/'manifest.json',inventory['source_identity']['manifest_sha256'],4194304)]
else:candidate,ch=read_public_json(args.candidate)
observed,oh=read_observed_inventory(args.observed_inventory);items=selected_items(candidate)
if args.dbc.is_symlink() or not args.dbc.is_file() or not 20<=args.dbc.stat().st_size<=67108864:raise ValueError('Captured DBC file bound')
with args.dbc.open('rb') as stream:raw=stream.read(67108865)
if len(raw)>67108864:raise ValueError('Captured DBC grew beyond bound')
dbc,source=observed_item_display(observed,raw)
if args.dbd.is_symlink() or not args.dbd.is_file() or not 0<args.dbd.stat().st_size<=1048576:raise ValueError('Source DBD file bound')
with args.dbd.open('rb') as stream:dbd=stream.read(1048577)
if len(dbd)>1048576:raise ValueError('Source DBD grew beyond bound')
column=reviewed_icon_column(dbd.decode())
if args.listfile.is_symlink() or not args.listfile.is_file() or args.listfile.stat().st_size>MAX_LISTFILE_BYTES:raise ValueError('Local listfile file bound')
with args.listfile.open('rb') as stream:paths,index=listfile_index(stream,{item['native_icon_file_data_id'] for item in items if item['native_icon_file_data_id']},source_icon_keys(items,dbc,column))
result=compare_icons(candidate,observed,raw,paths,column,index['source_icon_references'])
result['input_sha256']=dict(candidate=ch,observed_inventory=oh,source_dbc=sha(raw),target_listfile=index['sha256'],source_dbd=sha(dbd))
result['listfile_scan']=index
for path,digest in ((args.dbc,sha(raw)),)+(((args.candidate,ch),) if args.candidate else ()):
if bounded_digest(path)!=digest:raise ValueError('Icon preflight input changed during comparison')
if bounded_digest(args.observed_inventory,MAX_OBSERVED_INVENTORY_BYTES)!=oh:raise ValueError('Observed inventory changed during comparison')
if bounded_digest(args.listfile,MAX_LISTFILE_BYTES)!=index['sha256']:raise ValueError('Local listfile changed during comparison')
if bounded_digest(args.dbd,1048576)!=sha(dbd):raise ValueError('Source DBD changed during comparison')
for path,digest,bound in extra_inputs:
if bounded_digest(path,bound)!=digest:raise ValueError('Selected icon scope input changed')
if extra_inputs:
result['scope']=candidate['scope']
result['scope_input_sha256']={str(path):digest for path,digest,_ in extra_inputs}
result['candidate']=candidate
with args.output.open('x') as stream:json.dump(result,stream,sort_keys=True,indent=2,allow_nan=False);stream.write('\n')
print('Blocked icon-reference preflight:',len(result['rows']),'items;',json.dumps(result['status_counts'],sort_keys=True),'; no asset/engine/install claim.')
if __name__=='__main__':main()