Files
webworthit/chain/pack.py
T

157 lines
12 KiB
Python

"""Evidence pack + deterministic facts from evidence.json (any contract, any supported chain).
Generalised from D:/tmp/wwi-cost/pack.py (which was hard-wired to the 3xSusu raw files).
build(E) -> markdown the model reads. facts(E) -> [{tag, text, source}] used when a model report fails the fact check,
and shown beside every report. Every number here is computed in code, never by the model."""
import json
def f2(x):
return '%.2f' % x if isinstance(x, (int, float)) else str(x)
def short(a): return a[:6] + '...' + a[-4:] if a and len(a) == 42 else a
def build(E):
o = []; w = o.append
ex = E['explorer']
w('# Evidence pack: %s contract %s' % (E['chain_name'], E['address']))
w('Read at block %s (%s). All reads are public and read-only.\n' % (E['read_at']['block'], E['read_at']['time_ct']))
if not E.get('is_contract'):
w('## Not a contract\nThe address has no contract code. It is: %s. Native balance %s %s, nonce %s.' % (E.get('kind'), f2(E.get('native_balance')), E['native'], E.get('nonce')))
return '\n'.join(o)
px = E['proxy']
w('## Proxy and control (VERIFIED: storage slots and eth_call)')
w('- Type: %s' % px['type'])
w('- Upgradeable: %s' % ('yes' if px['upgradeable'] else 'no proxy slot set'))
if px.get('impl') or px.get('eip1822'): w('- Implementation now: %s' % (px.get('impl') or px.get('eip1822')))
if px.get('admin'): w('- ERC1967 admin slot: %s' % px['admin'])
if px.get('beacon'): w('- Beacon: %s' % px['beacon'])
w('- Code size: %s bytes (implementation %s bytes)' % (E.get('code_bytes'), E.get('impl_code_bytes')))
w('- Role getters read with eth_call: ' + (json.dumps(E.get('roles')) if E.get('roles') else 'none answered'))
if E.get('values'): w('- Other zero-argument values: ' + json.dumps(E['values']))
if 'paused' in E: w('- paused() now: %s' % E['paused'])
w('- Controller wallets:')
for a, k in (E.get('controllers') or {}).items(): w(' - %s: %s' % (a, k.get('desc')))
if E.get('upgrade_test'):
u = E['upgrade_test']
w('- Upgrade test (%s):' % u['method'])
for a, t in u['results'].items(): w(' - from %s%s: %s' % (a, ' (random address)' if a == u['random_address'] else '', t))
w('- Addresses that can upgrade in one transaction: %s' % (', '.join(E.get('can_upgrade') or []) or 'none found'))
w('')
w('## Source verification (Sourcify)')
for k, v in (E.get('verification') or {}).items(): w('- %s: %s%s' % (k, v.get('match') or 'not verified on Sourcify', (' (' + v['name'] + ')') if v.get('name') else ''))
w('- Note: %s\n' % E.get('verification_source'))
s = E.get('selectors') or {}
w('## Functions in the code (%s selectors, %s named; names from %s)' % (s.get('count'), s.get('named'), s.get('names_source')))
w(', '.join('%s %s' % (k, v or '?') for k, v in (s.get('map') or {}).items()))
w('- Control or custody related functions present: ' + (', '.join(E.get('risky_functions') or []) or 'none matched'))
if E.get('abi_functions'): w('- Verified ABI functions: ' + ', '.join(E['abi_functions'][:120]))
w('')
c = E.get('creation') or {}; win = E.get('window') or {}
w('## Deployment and history read')
w('- Creation block: %s (%s) source: %s; time %s; tx %s; deployer %s' % (c.get('block'), c.get('block') is not None and 'known' or 'unknown', c.get('source'), c.get('time_ct'), c.get('tx'), c.get('from')))
if E.get('age_days') is not None: w('- Contract age: %s days' % E['age_days'])
if c.get('addresses_in_input'): w('- Addresses passed in the deployment transaction input: ' + ', '.join(c['addresses_in_input']))
w('- Blocks read: %s to %s (%s blocks, from %s). Complete history: %s' % (win.get('from'), win.get('to'), win.get('blocks'), win.get('from_time_ct'), win.get('complete_history')))
for g in E.get('gaps') or []: w('- NOT READ (provider failure or time limit): %s, block ranges %s' % (g['what'], g['ranges'][:6]))
w('')
ev = E.get('events') or {}
w('## Events emitted by the contract (%s logs in the window)' % ev.get('total'))
for t in ev.get('by_topic', []): w('- %s %s: %d' % (t['topic'][:10], t['name'] or '', t['count']))
for nm, d in (E.get('decoded_events') or {}).items():
# also print big sums already divided by 10^18 (2 decimals) so the model never has to convert and the fact gate can match
as18 = {k: round(int(v) / 1e18, 2) for k, v in (d['uint_field_sums_raw'] or {}).items() if isinstance(v, (int, str)) and str(v).isdigit() and int(v) >= 10 ** 12}
w('- Decoded %s: %d events; sums of number fields (raw integer units): %s; the same sums as 18-decimal amounts (%s or an 18-decimal token, 2 decimals): %s; top addresses per field: %s; first samples: %s' % (
nm, d['count'], json.dumps(d['uint_field_sums_raw']), E['native'], json.dumps(as18), json.dumps(d['top_addresses']), json.dumps(d['first_samples'])))
cn = E.get('counts') or {}
w('\n## Precomputed counts (use these, do not recount)')
w('- Upgraded events total: %s' % cn.get('upgrade_events_total'))
w('- Upgrades AFTER deployment: %s (%s)' % (cn.get('upgrades_after_deployment'), cn.get('upgrades_note')))
w('- Paused events: %s; ownership transfers: %s' % (cn.get('pause_events'), cn.get('ownership_transfers')))
w('\n## Admin event timeline')
for x in E.get('admin_events') or []:
w('- %s block %s tx %s %s %s%s%s' % (x.get('time_ct'), x['block'], x['tx'], x['event'], x.get('arg') or '', ' [in the deployment tx]' if x.get('in_creation_tx') else '',
(' sent by ' + x['from'] + ' selector ' + x.get('selector', '')) if x.get('from') else ''))
w('\n## Money held and moved (token Transfer logs, VERIFIED)')
w('- Native %s balance of the contract now: %s' % (E['native'], f2(E.get('native_balance'))))
tx = E.get('txs')
if tx:
w('- Transactions behind the events: %d (read %d, %s). Direct calls to the contract among them: %d; native %s sent in with them: %s (%d calls carried a value).' % (
tx['event_txs_total'], tx['read'], tx['read_note'], tx['direct_calls'], E['native'], f2(tx['native_sent_in']), tx['calls_with_native']))
w('- Direct calls by function: ' + ', '.join('%s x%d' % (a, n) for a, n in tx['by_function']))
w('- Top direct callers: ' + ', '.join('%s x%d' % (a, n) for a, n in tx['top_senders']))
w('- Native coin paid OUT by the contract (internal transfers) is not visible in logs and was not traced (UNKNOWN).')
if not E.get('money'): w('- No transfers of the stable tokens checked (%s) in the window, and no balance.' % ', '.join(E.get('tokens_checked', [])))
for sy, m in (E.get('money') or {}).items():
w('### %s (%s, %s decimals)' % (sy, m['token'], m['decimals']))
w('- Balance now (balanceOf): %s' % f2(m['balance_now']))
w('- In: %d transfers, %s total, from %d wallets' % (m['in_count'], f2(m['in_total']), m['payers']))
w('- Out: %d transfers, %s total, to %d wallets' % (m['out_count'], f2(m['out_total']), m['recipients']))
w('- In minus out over the window: %s' % f2(m['net_in_minus_out']))
w('- Top recipients (address, total, transfers): ' + '; '.join('%s %s x%d' % (a, f2(v), n) for a, v, n in m['top_recipients']))
w('- Top payers: ' + '; '.join('%s %s x%d' % (a, f2(v), n) for a, v, n in m['top_payers']))
w('- Most common outgoing sizes (size x count): ' + ', '.join('%s x%d' % (a, n) for a, n in m['out_sizes']))
if m['daily_in_counts']: w('- Incoming transfers per day (CT): ' + ', '.join('%s:%d' % (d, n) for d, n in m['daily_in_counts']))
w('\n## Wallet approvals to this contract (Approval logs + live allowance, VERIFIED)')
if not E.get('approvals'): w('- None found in the window.')
for sy, a in (E.get('approvals') or {}).items():
w('- %s: %d approval events, %d approving wallets (%d read), %d with a live allowance, %d unlimited, total that could be pulled from wallets right now %s' % (
sy, a['approval_events'], a['approving_wallets'], a['read'], a['live_allowances'], a['unlimited'], f2(a['pullable_now'])))
p = E.get('positions')
if p:
w('\n## Positions stored in the contract (%s)' % p['method'])
w('- %s = %s; owners read %s; distinct owners %s' % (p['count_function'], p['count'], p['read'], p['owners']))
w('- Top owners (address, positions): ' + '; '.join('%s %d' % (a, n) for a, n in p['top_owners']))
w('\n## Wallet profiles (role holders, deployer, deployment-input addresses, top recipients)')
for a, k in (E.get('wallets') or {}).items():
w('- %s [%s] %s, nonce %s, native %s, received from contract %s%s' % (a, ', '.join(k.get('labels') or []) or 'top recipient', k.get('desc'), k.get('nonce'), f2(k.get('native_balance')),
json.dumps(k.get('received_from_contract') or {}), (', positions owned %s' % k['positions_owned']) if 'positions_owned' in k else ''))
w('\n## Notes')
for n in E.get('notes') or []: w('- ' + n)
return '\n'.join(o)
def facts(E):
F = []; ex = E['explorer']
add = lambda tag, text, src=None: F.append({'tag': tag, 'text': text, 'source': src})
A = E['address']
if not E.get('is_contract'):
add('VERIFIED', 'This address has no contract code: it is %s.' % E.get('kind'), ex + '/address/' + A)
return F
px = E['proxy']
if px['upgradeable']:
add('VERIFIED', 'The contract is an upgradeable proxy (%s). Its code can be replaced.' % px['type'], ex + '/address/' + A)
else:
add('VERIFIED', 'No upgradeable-proxy slot is set: %s.' % px['type'], ex + '/address/' + A)
for a in E.get('can_upgrade') or []:
k = (E.get('controllers') or {}).get(a) or {}
add('VERIFIED', 'Address %s can upgrade the code in one transaction (simulated with eth_call). It is a %s.' % (a, k.get('desc', 'wallet')), ex + '/address/' + a)
cn = E.get('counts') or {}
if cn.get('upgrades_after_deployment') is not None and px['upgradeable']:
add('VERIFIED', 'Upgrades after deployment: %s.' % cn['upgrades_after_deployment'], None)
for x in [y for y in E.get('admin_events') or [] if y['event'] == 'Upgraded(address)' and not y.get('in_creation_tx')][:6]:
add('VERIFIED', 'Upgrade on %s to implementation %s.' % (x.get('time_ct'), x.get('arg')), ex + '/tx/' + x['tx'])
for k, v in (E.get('verification') or {}).items():
add('VERIFIED' if v.get('match') else 'UNKNOWN', '%s source: %s on Sourcify.' % (k.capitalize(), 'verified (' + v['match'] + ')' if v.get('match') else 'not verified'), None)
for fn, a in (E.get('roles') or {}).items():
k = (E.get('controllers') or {}).get(a) or {}
add('VERIFIED', '%s returns %s (%s).' % (fn, a, k.get('desc', '')), ex + '/address/' + a)
if 'paused' in E: add('VERIFIED', 'paused() is %s now.' % E['paused'], None)
if E.get('risky_functions'): add('INFERRED', 'Functions related to control or custody found in the code: %s.' % ', '.join(E['risky_functions'][:20]), None)
add('VERIFIED', 'Native %s balance now: %s.' % (E['native'], f2(E.get('native_balance'))), ex + '/address/' + A)
for sy, m in (E.get('money') or {}).items():
add('VERIFIED', '%s balance now: %s. Received %s in %d transfers; sent out %s in %d transfers (blocks %s to %s).' % (
sy, f2(m['balance_now']), f2(m['in_total']), m['in_count'], f2(m['out_total']), m['out_count'], E['window']['from'], E['window']['to']), ex + '/address/' + A)
for sy, a in (E.get('approvals') or {}).items():
add('VERIFIED', '%s approvals: %d wallets approved this contract; %d unlimited; %s could be pulled from wallets right now.' % (sy, a['approving_wallets'], a['unlimited'], f2(a['pullable_now'])), None)
p = E.get('positions')
if p and p['top_owners']:
a, n = p['top_owners'][0]
lab = ', '.join(((E.get('wallets') or {}).get(a) or {}).get('labels') or [])
add('INFERRED', 'Top position owner %s%s holds %d of %d positions.' % (a, (' (' + lab + ')') if lab else '', n, p['count']), ex + '/address/' + a)
win = E.get('window') or {}
add('VERIFIED', 'History read: blocks %s to %s%s.' % (win.get('from'), win.get('to'), ' (complete since deployment)' if win.get('complete_history') else ' (partial window)'), None)
for g in E.get('gaps') or []: add('UNKNOWN', 'Not read: %s in %d block ranges (provider limit or time cap).' % (g['what'], len(g['ranges'])), None)
return F