"""Offline structure and known-key checks (354–356). Input: evidence directory, output: results JSON. Stdlib."""
import base64,hashlib,json,itertools,sys,string
from collections import Counter
from pathlib import Path
def hx(x):return hashlib.sha256(x).hexdigest()
def u(x):return int.from_bytes(x,'big')
def payload_header(b):
 t=b[0]
 if t<128:raise ValueError('not a packet')
 if t&64:
  n=b[1]
  if n<192:return (t&63,2,n,'full')
  if n<224:return (t&63,3,(n-192)*256+b[2]+192,'full')
  if n<255:return (t&63,2,1<<(n&31),'partial')
  return t&63,6,u(b[2:6]),'full'
 l=t&3; tag=t>>2&15
 if l==3:return tag,1,len(b)-1,'to_eof'
 k=1<<l
 return tag,1+k,u(b[1:1+k]),'full'
def packets(b):
 while b:
  tag,h,l,mode=payload_header(b);assert mode=='full' and len(b)>=h+l
  yield tag,b[h:h+l];b=b[h+l:]
def mpi(b,i):
 size=u(b[i:i+2]);end=i+2+(size+7)//8;n=u(b[i+2:end]);assert end<=len(b) and n.bit_length()==size;return n,end
def strip_armor(a):
 return base64.b64decode(b''.join(s for s in a.split(b'\n\n',1)[1].splitlines() if s and not s.startswith((b'=',b'-'))),validate=True)
def padded_digest(b):
 # Minimum necessary DER-independent prefix & PS requirements from EMSA-PKCS1-v1_5.
 pos=b.find(b'\0',2)
 return b[:2]==b'\0\1' and pos>=10 and b[2:pos]==b'\xff'*(pos-2) and pos<len(b)-1
def initial(b):
 tag,h,n,mode=payload_header(b)
 problems=[]
 if mode=='partial':
  if n<512:problems.append('first partial chunk is shorter than 512')
  if tag not in (8,9,11,18):problems.append('partial length forbidden on this packet type')
 if h+n>len(b):problems.append('declared body exceeds object')
 return dict(tag=tag,length_mode=mode,length=n,prefix=b[:3].hex(),problems=problems)
def work(d):
 dat=(d/'base60_verified.bin').read_bytes();assert hx(dat)=='3b9b07d9a26e6d55c432d94d2661fdff3c2b348daed06821f2bdb23184a4b290'
 key=(d/'public_key_119.gpg').read_bytes();raw=base64.b64decode((d/'handoff_119.b64').read_bytes());body,arm=raw.split(b'-----BEGIN PGP SIGNATURE-----');sig=strip_armor(arm)
 keyp=list(packets(key));sp=list(packets(sig));assert [t for t,b in keyp]==[6,13,2,14,2] and len(sp)==1 and sp[0][0]==2
 kb=keyp[0][1];fp=hashlib.sha1(b'\x99'+len(kb).to_bytes(2,'big')+kb).hexdigest();assert fp=='6d854cd7933322a601c3286d181f01e57a35090f'
 n,i=mpi(kb,6);e,end=mpi(kb,i);k=(n.bit_length()+7)//8;assert end==len(kb)
 sn,ii=mpi(keyp[3][1],6)
 s=sp[0][1];assert s[:4]==bytes([4,1,1,2]);end=6+u(s[4:6]);pre=s[:end];z=end+2+u(s[end:end+2]);sval,last=mpi(s,z+2);assert last==len(s)
 text=body.split(b'\n\n',1)[1];assert text.endswith(b'\n');canonical=b'\r\n'.join(t.removeprefix(b'- ').rstrip(b' \t') for t in text[:-1].split(b'\n'))
 digest=hashlib.sha1(canonical+pre+b'\x04\xff'+len(pre).to_bytes(4,'big')).digest();assert digest[:2]==s[z:z+2]
 sha1_der=bytes.fromhex('3021300906052b0e03021a05000414')+digest
 recovered=pow(sval,e,n).to_bytes(k,'big');expected=b'\x00\x01'+b'\xff'*(k-len(sha1_der)-3)+b'\0'+sha1_der
 assert padded_digest(recovered) and recovered==expected and not padded_digest(pow(sval^1,e,n).to_bytes(k,'big'))
 # A fixed length literal fixture and entire legal 512-byte first partial, terminated by a definite empty chunk.
 literal=b'b\x00'+bytes(4)+b'known';fixture=bytes((0xcb,len(literal)))+literal
 part=bytes((0xcb,233))+literal.ljust(512,b'X')+b'\x00'
 assert list(packets(fixture))==[(11,literal)] and initial(part)['problems']==[] and part[514:]==b'\0'
 assert initial(bytes([0xcb,231])+b'a'*128+b'\x00')['problems']==['first partial chunk is shorter than 512']
 cells=json.loads((d/'grid_cells_254.json').read_bytes())['cells'];ts=[c['b'] for c in cells];flags=[(j,c['altsB'][0]) for j,c in enumerate(cells) if c['altsB']];assert len(flags)==10 and all(len(c['altsB'])<=1 for c in cells)
 b=(string.digits+string.ascii_uppercase+string.ascii_lowercase[:24]).replace('f','')
 models=[('compact59',b,59)]+[(f'ins{i}',b[:i]+'f'+b[i:],60) for i in range(16,60)]
 header=Counter();lens=Counter();count=passes=0;var=set();first3=set();unique_header=Counter()
 for name,alpha,rad in models:
  def enc(t):return rad*alpha.index(t[0])+alpha.index(t[1])
  base=bytes(map(enc,ts))
  if name=='ins41':assert base==dat
  for bits in itertools.product((False,True),repeat=len(flags)):
   tape=bytearray(base)
   for (idx,other),use in zip(flags,bits):
    if use:tape[idx]=enc(other)
   ident=hx(tape)
   a=initial(tape);assert a['length_mode']=='partial' and a['length']<512
   header[a['tag'],a['length']]+=1;first3.add(tape[:3].hex())
   count+=1
   if ident in var:continue
   var.add(ident);unique_header[a['tag'],a['length']]+=1
   signature=u(tape);assert signature<n
   candidate=pow(signature,e,n).to_bytes(k,'big')
   passes+=padded_digest(candidate);lens[candidate[:2].hex()]+=1
 assert count==45*1024 and not passes
 return {'inputs_sha256':{'grid':hx(dat),'handoff_armor':hx(raw),'public_key':hx(key)},'354':{'grid':initial(dat),'public_key_packets':[[t,len(b)] for t,b in keyp],'signed_handoff_signature_packet_body':len(s),'control_literal':initial(fixture),'control_partial':initial(part),'control_partial_termination':'zero-length definite new-format chunk','damaged_128_byte_partial_control_rejected':True},'355':{'alphabet_models':len(models),'ambiguities_per_alphabet':len(flags),'distinct_streams':len(var),'header_counts_distinct_streams':{f'{t}/{sz}':v for (t,sz),v in sorted(unique_header.items())},'header_tag_and_first_chunk_bytes':{f'{t}/{sz}':v for (t,sz),v in sorted(header.items())},'initial_three_byte_hex':sorted(first3),'valid_first_lengths':0},'356':{'primary_fingerprint':fp,'primary_rsa_bits':n.bit_length(),'subkey_rsa_bits':sn.bit_length(),'exponent':e,'known_signature_mpi_bits':sval.bit_length(),'modulus_octets':k,'known_sig_mpi_octets':(sval.bit_length()+7)//8,'signed_handoff_sha1':digest.hex(),'known_signature_matches_complete_encoded_digest':True,'flipped_signature_fails_prefix':True,'grid_candidate_settings':count,'distinct_grid_candidates':len(var),'candidates_recovering_0001_prefix':lens['0001'],'candidates_with_required_padding':passes,'preferred_first_eight_public_operation_bytes':pow(u(dat),e,n).to_bytes(k,'big')[:8].hex()}}
if __name__=='__main__':
 Path(sys.argv[2]).write_text(json.dumps(work(Path(sys.argv[1])),sort_keys=True,indent=2)+'\n')
