#!/usr/bin/env python3 """Verify a pinned AhaSignals company packet and select facts known at a UTC cutoff.""" import argparse import datetime as dt import hashlib import json import math from pathlib import Path import re FACT_KEYS={'cik','concept','label','unit','value','start','end','filedDate','accession','form','id','firstObservedAt','firstSourceSha256','sourceUrl'} PACKET_KEYS={'cik','name','tickers','exchanges','sic','sicDescription','sector','screen','factsSource','submissionSource','version','publisher','facts','currentIds','comparisons','comparativeChanges','guidanceStatus','scope','reviewStatus','previousSha256','recordedAt','contentSignature'} CONCEPTS={'Revenues','RevenueFromContractWithCustomerExcludingAssessedTax','SalesRevenueNet','NetIncomeLoss','NetCashProvidedByUsedInOperatingActivities','PaymentsToAcquirePropertyPlantAndEquipment','Assets','CashAndCashEquivalentsAtCarryingValue'} def instant(v): if not isinstance(v,str) or not re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z',v):raise ValueError('UTC instant required') return dt.datetime.fromisoformat(v.replace('Z','+00:00')) def check(condition,why): if not condition:raise ValueError(why) def sha(v):return isinstance(v,str) and bool(re.fullmatch('[a-f0-9]{64}',v)) def verify(data,expected): check(sha(expected) and hashlib.sha256(data).hexdigest()==expected,'packet SHA-256 mismatch') p=json.loads(data) check(set(p)==PACKET_KEYS and p['publisher']=='AhaSignals' and p['version']=='1.0.0','unknown packet fields/version') check(bool(re.fullmatch(r'\d{10}',p['cik'])),'invalid CIK') check(p['previousSha256'] is None or sha(p['previousSha256']),'invalid parent hash') instant(p['recordedAt']) for field,route in [('factsSource','api/xbrl/companyfacts'),('submissionSource','submissions')]: s=p[field];check(set(s)=={'url','sha256','observedAt'} and sha(s['sha256']),'unknown source fields') check(s['url']==f'https://data.sec.gov/{route}/CIK{p["cik"]}.json','source issuer mismatch') check(instant(s['observedAt'])<=instant(p['recordedAt']),'source observed after packet') check(set(p['screen'])=={'status','measurement'},'screen fields') m=p['screen']['measurement'] if m: check(set(m)=={'val','end','filed','accn','unit','concept','sourceUrl'},'measurement fields') check(m['unit']=='USD' and m['concept']=='dei:EntityPublicFloat','wrong float unit/concept') check(m['end']<=p['submissionSource']['observedAt'][:10] and m['filed']<=p['submissionSource']['observedAt'][:10],'future float') ids=set() for r in p['facts']: check(set(r)==FACT_KEYS,'unknown fact fields') check(r['cik']==p['cik'] and r['unit']=='USD' and r['concept'] in {'us-gaap:'+c for c in CONCEPTS},'unsupported fact') check(isinstance(r['value'],(int,float)) and not isinstance(r['value'],bool) and math.isfinite(r['value']),'invalid value') check(sha(r['id']) and sha(r['firstSourceSha256']) and r['id'] not in ids,'invalid/duplicate fact ID');ids.add(r['id']) check(bool(re.fullmatch(r'\d{10}-\d{2}-\d{6}',r['accession'])),'invalid accession') check(r['sourceUrl']==f'https://www.sec.gov/Archives/edgar/data/{int(p["cik"])}/{r["accession"].replace("-", "")}/{r["accession"]}-index.htm','unexpected filing URL') check(r['filedDate']<=r['firstObservedAt'][:10] and r['end']<=r['firstObservedAt'][:10],'future fact') check(instant(r['firstObservedAt'])<=instant(p['recordedAt']),'future observation') if r['start']:check(r['start']<=r['end'],'negative period') check(len(set(p['currentIds']))==len(p['currentIds']) and set(p['currentIds'])<=ids,'unknown current fact') for c in p['comparisons']: check(set(c)=={'concept','currentId','priorId','growthPercent','reason'},'comparison fields') check(c['currentId'] in ids and (c['priorId'] is None or c['priorId'] in ids),'unknown comparison input') for c in p['comparativeChanges']: check(set(c)=={'concept','start','end','factIds','status','reason'} and set(c['factIds'])<=ids,'change fields') return p def replay(p,as_of): cutoff=instant(as_of) # Applying today's currentIds to an older date would leak removals and eligibility changes. check(instant(p['recordedAt'])<=cutoff,'Use a retained packet recorded no later than as-of; this observation packet did not exist yet') current_ids=set(p['currentIds']) rows=[r for r in p['facts'] if r['id'] in current_ids and instant(r['firstObservedAt'])<=cutoff] return {'publisher':'AhaSignals','asOf':as_of,'cik':p['cik'],'packetRecordedAt':p['recordedAt'], 'scope':'Observed facts, not proof of historical market-wide availability. Original durations remain unchanged.', 'facts':rows,'comparisons':p['comparisons'],'guidanceStatus':p['guidanceStatus']} if __name__=='__main__': a=argparse.ArgumentParser();a.add_argument('packet',type=Path);a.add_argument('--sha256',required=True);a.add_argument('--as-of',required=True);v=a.parse_args() print(json.dumps(replay(verify(v.packet.read_bytes(),v.sha256),v.as_of),ensure_ascii=False,indent=2))