"""Offline checks for the retained claim graph: python analyse_snapshot.py DIR.

Does not authenticate RPC or independently audit validators. Uses saved integer
ABI words, original call arguments and the documented bounded claim graph.
"""
import json,sys
from pathlib import Path
p=Path(sys.argv[1]);r=json.loads((p/'snapshot_raw.json').read_text());a=json.loads((p/'snapshot_analysis.json').read_text());b=r['block']['response']['result'];pin=b['number']
assert b['hash']==r['block_recheck']['response']['result']['hash']
assert int(r['chain']['response']['result'],16)==1
for label,call in r['calls'].items():
 assert call['http_status']==200 and call['request']['params'][1]==pin
 assert int(call['response']['result'],16)==int(call['decoded_integer'])
v=lambda k:int(r['calls'][k]['decoded_integer']);wad=10**18
def text(n):
 q,f=divmod(n,wad);return str(q)+('.'+str(f).zfill(18).rstrip('0') if f else '')
R=v('steth_total_supply');B=v('all_wsteth_claim_steth');C=v('aave_physical_claim_steth')
assert R==v('lido_reported_pooled_eth') and 0<=C<=B<=R
assert v('wrapper_steth_balance')>=B
assert v('wrapper_underlying')==int(r['addresses']['steth'],16)
assert v('aave_underlying')==int(r['addresses']['wsteth'],16)
assert v('aave_physical_wsteth')<=v('wsteth_total_supply')
for name,quantity in [('all_wsteth_claim_steth',v('wsteth_total_supply')),('aave_physical_claim_steth',v('aave_physical_wsteth'))]:
 encoded=r['calls'][name]['request']['params'][0]['data'];assert encoded[:10]=='0xbb2952fc' and int(encoded[10:],16)==quantity
# Current Lido conversion uses internal ether / internal shares. Using the
# already-rounded total pooled ether / total shares can lose one raw unit.
internal=R-v('steth_external_ether');shares=v('steth_total_shares')-v('steth_external_shares')
assert v('wsteth_total_supply')*internal//shares==B
assert v('aave_physical_wsteth')*internal//shares==C
expected={'R_reported_root_supply':R,'B_all_wrapped_claims':B,'C_aave_physical_custody_lookthrough':C,'candidate_gross_layer_sum':R+B+C,'nested_overlap_subtraction':B+C,'conditional_distinct_root_exposure':R}
for k,value in expected.items():assert text(value)==a[k],k
print(json.dumps({'passed':True,'block_number':int(pin,16),'block_hash':b['hash'],'exact_results':{k:text(value) for k,value in expected.items()},'scope':a['assumptions']},indent=2))
