"""Offline arithmetic check of a reader-exported receipt;no network or writes.""" import json,sys,re,math from pathlib import Path from fractions import Fraction def require(condition,message): if not condition:raise ValueError(message) def strict(path): def reject(token):raise ValueError('Nonstandard JSON constant: '+token) return json.loads(Path(path).read_text(encoding='utf-8'),parse_constant=reject) FIELDS=['owner_balance_raw','recipient_balance_raw','allowance_raw'] def format_amount(raw,places): n=int(raw);sign='-'if n<0 else'';whole,fraction=divmod(abs(n),10**places) tail=str(fraction).zfill(places).rstrip('0')if places else'' return sign+str(whole)+('.'+tail if tail else'') def verify(data,source): require(type(data.get('schema_version'))is int and data.get('schema_version')==1 and data.get('tool')=='CoinPunch saved observation comparison','Wrong receipt schema/tool') require(data['source_observation_sha256']==source['source_sha256']and data['decimals']==source['decimals'],'Source hash/unit mismatch') require(type(data['selection']['a_record'])is int and type(data['selection']['b_record'])is int,'Integer selection required') a=data['selection']['a_record']-1;b=data['selection']['b_record']-1;cases=source['cases'] require(type(a)is int and type(b)is int and 0<=aa else'earlier'),'Selection order mismatch') require([r['field']for r in data['rows']]==FIELDS,'State fields mismatch') for r in data['rows']: field=r['field'];av=cases[a]['after'][field];bv=cases[b]['after'][field];delta=str(int(bv)-int(av)) require((r['a_raw'],r['b_raw'],r['b_minus_a_raw'])==(av,bv,delta),'Exact integer difference mismatch') require((r['a_lab'],r['b_lab'],r['b_minus_a_lab'])==tuple(format_amount(x,source['decimals'])for x in [av,bv,delta]),'LAB conversion mismatch') return {'passed':True,'checked':'Selected saved records,source label,exact raw-integer differences and LAB conversion only','not_checked':'Authenticity of an arbitrary changed source,real wallet/RPC/mainnet,one-call causation or security'} if __name__=='__main__': try:print(json.dumps(verify(strict(sys.argv[1]),strict(sys.argv[2])),ensure_ascii=False)) except (KeyError,ValueError,TypeError,IndexError,ZeroDivisionError,OSError)as error:raise SystemExit('Receipt check failed: '+str(error))