"""python signed_341.py EVIDENCE_DIR CACHE_DIR OUTPUT.json.gz (after 339; Pillow, GnuPG and ffprobe)"""
from pathlib import Path
import collections,io,itertools,json,re,subprocess,sys,tempfile
from PIL import Image
from signed_339 import FP,H,em,load,rawbody
def main(d,c,out):
 rs=load(d/'signed_339_results.json.gz')['records'];bs=json.loads((c/'verified_bodies.json').read_bytes())
 def body(n):
  r=next(x for x in rs if x['id']==n and x['state']=='valid');b=bs[n];assert H(b.encode())==r['body_sha256'];return b
 selectors=[f'assets/2014/stage03/onion{i}.outguess#1' for i in (1,2,3)]+['assets/2014/stage04/index.1.outguess#1','2014-01-onion5-liber-primus.asc#1']
 spans={};streams=[]
 for n in selectors:
  spans[n]=[];s=body(n).split('\n')
  for k,g in itertools.groupby(enumerate(s,1),key=lambda t:bool(re.fullmatch(r'(?:[0-9a-fA-F]{2})+',t[1].strip(' \t')))):
   a=list(g)
   if not k:continue
   ls=[l.strip(' \t') for _,l in a]
   if max(map(len,ls))<32:continue
   b=bytes.fromhex(''.join(ls));rec={'start':a[0][0],'end':a[-1][0],'rows':len(ls),'width_histogram':dict(collections.Counter(map(len,ls))),'bytes':len(b),'sha256':H(b)}
   if b.startswith(b'\xff\xd8'):
    im=Image.open(io.BytesIO(b));im.load();assert im.format=='JPEG' and b.endswith(b'\xff\xd9');rec.update(codec='JPEG',dimensions=list(im.size),pixel_sha256=H(im.tobytes()))
   if b.startswith(b'\xff\xf3'):
    cmd=['ffprobe','-loglevel','error','-show_entries','stream=codec_name,sample_rate,channels','-of','json','pipe:0']
    probe=json.loads(subprocess.run(cmd,input=b,capture_output=True,check=True).stdout)['streams'];assert len(probe)==1 and probe[0]['codec_name']=='mp3';rec.update(codec='MPEG audio',stream=probe[0])
   spans[n].append(rec)
   if n in selectors[:3]:streams.append(b)
 assert len(streams)==3 and len(set(map(len,streams)))==1
 nested=bytes(i^j^k for i,j,k in zip(*streams))
 assert nested.startswith(b'-----BEGIN PGP SIGNED MESSAGE-----\n') and rawbody(nested).decode()==body('2014-3')
 def verify(tmp,dat):
  p=subprocess.run(['gpg','--homedir',tmp,'--batch','--no-auto-key-retrieve','--no-default-keyring','--keyring',str((d/'public_key_119.gpg').resolve()),'--allow-weak-digest-algos','--status-fd','1','--verify'],input=dat,capture_output=True)
  return p.returncode==0 and b'[GNUPG:] VALIDSIG '+FP.encode()+b' ' in p.stdout
 # Single- and two-source controls compare the complete PGP prefix, not an incidental byte.
 controls={}
 for m in range(1,7):
  outb=bytes((p if m&1 else 0)^(q if m&2 else 0)^(r if m&4 else 0) for p,q,r in zip(*streams))
  controls[str(m)]=outb.startswith(b'-----BEGIN PGP SIGNED MESSAGE-----')
 with tempfile.TemporaryDirectory() as t:
  valid=verify(t,nested);mod=nested.replace(b'IDGTK',b'JDGTK',1);assert mod!=nested
  damaged=verify(t,mod);assert valid and not damaged and not any(controls.values())
 em({'spans':spans,'nested':{'xa_sha256':H(nested),'bytes':len(nested),'matches_body':'2014-3','valid_signature':valid,'one_visible_letter_changed_valid':damaged,'proper_subset_clear_signed_prefix':controls},'fingerprint':FP},out)
if __name__=='__main__':main(*map(Path,sys.argv[1:]))
