Files
webworthit/chain/scan.py
T
martbost 6aeb1b2146 Rubric red flag 4 sharpened (Marty 2026-11-16): forced High only when earlier buyers are paid from later buyers' payments; sponsor commissions on a delivered product are disclosed and scored, not auto-flagged
Deterministic payout read (chain/payouts.py): every payout matched to the buyer of the same tx and classed operator /
referral line / earlier buyer outside the line. Earlier-buyer payouts = VERIFIED red flag 4. A model red flag 4 is
INFERRED, must cite evidence, and is not applied when the chain shows only operator and referral-line payouts
(shown on the report as 'Considered and not applied'). Same test for every contract.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 12:26:07 -06:00

608 lines
33 KiB
Python

"""WebWorthIt chain scan: one read-only pass over a contract, producing evidence.json (structured facts with sources)
and pack.md (the evidence pack the model reads). Generalised from the 3xSusu review tools (D:/tmp/bsc-audit/tools).
Usage: python3 scan.py CHAIN ADDRESS OUTDIR [--budget SECONDS] [--hint-abi FILE]
Prints one JSON progress line per step on stdout ({"step": ...}) and a final {"done": true}.
READ-ONLY: every RPC used is a read (eth_call, eth_getLogs, eth_getCode, eth_getStorageAt, eth_getBalance, ...).
No key, no signing, no transaction is ever sent. eth_call simulations change nothing on chain.
Deterministic counts (the model never counts): upgrades after deployment, events per type, transfers in/out, totals,
balances, positions per owner, approvals. Every number in pack.md comes from here.
"""
import sys, os, json, time, re, collections, datetime, random
from concurrent.futures import ThreadPoolExecutor
import requests
from chainrpc import RPC, CHAINS, TRANSFER, APPROVAL, addr_topic, topic_addr, CallReverted
import keccak
try:
from zoneinfo import ZoneInfo
CT = ZoneInfo('America/Chicago')
except Exception:
CT = None
SLOTS = {'impl': '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc',
'admin': '0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103',
'beacon': '0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50',
'eip1822': '0xc5f16f0fcc639fa48a6947836d9850f504798523bf8c9a3a87d5876cf622bcf7'}
EVENTS = {
'0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b': 'Upgraded(address)',
'0x7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f': 'AdminChanged(address,address)',
'0x1cf3b03a6cf19fa2baba4df148e9dcabedea7f8a5c07840e207e5c089be95d3e': 'BeaconUpgraded(address)',
'0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0': 'OwnershipTransferred(address,address)',
'0x38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e22700': 'OwnershipTransferStarted(address,address)',
'0x62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258': 'Paused(address)',
'0x5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa': 'Unpaused(address)',
'0xc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2': 'Initialized(uint64)',
'0x7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498': 'Initialized(uint8)',
'0x2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d': 'RoleGranted(bytes32,address,address)',
'0xf6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b': 'RoleRevoked(bytes32,address,address)',
TRANSFER: 'Transfer(address,address,uint256)', APPROVAL: 'Approval(address,address,uint256)',
}
ADMIN_EVENTS = {k for k, v in EVENTS.items() if not v.startswith(('Transfer', 'Approval'))}
UPGRADED = '0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b'
# selectors whose presence matters for custody / control (names from public signature databases)
RISKY = re.compile(r'^(upgradeTo|upgradeToAndCall|withdraw|emergencyWithdraw|sweep|rescue|recover|drain|skim|setFee|setFees|setTax|setRouter|'
r'setToken|setTreasury|setWallet|setRecipient|setReceiver|setPlatform|setAdmin|setOwner|transferOwnership|renounceOwnership|'
r'pause|unpause|mint|burn|blacklist|addBlacklist|setBlacklist|execute|multicall|call|delegatecall|setImplementation|'
r'changeAdmin|grantRole|revokeRole|setOperator|setManager|setSplit|setPrice|setLimit|setMax|withdrawAll|withdrawTokens|'
r'adminWithdraw|ownerWithdraw|emergency|migrate|setContract|setVault|query)', re.I)
POSITION_PAIRS = [('totalEntries()', 'entries(uint256)'), ('totalPositions()', 'positions(uint256)'), ('positionCount()', 'positions(uint256)'),
('nextPositionId()', 'positions(uint256)'), ('totalSlots()', 'slots(uint256)'), ('totalNodes()', 'nodes(uint256)'),
('totalDeposits()', 'deposits(uint256)'), ('depositCount()', 'deposits(uint256)')]
KNOWN_SEL = {'owner()': '0x8da5cb5b', 'admin()': '0xf851a440', 'getOwner()': '0x893d20e8', 'paused()': '0x5c975abb',
'totalEntries()': '0x7fef036e', 'entries(uint256)': '0xb30906d4', 'proxiableUUID()': '0x52d1902d',
'upgradeToAndCall(address,bytes)': '0x4f1ef286', 'decimals()': '0x313ce567', 'balanceOf(address)': '0x70a08231',
'allowance(address,address)': '0xdd62ed3e', 'getThreshold()': '0xe75235b8', 'getOwners()': '0xa0e67e2b',
'pendingOwner()': '0xe30c3978', 'implementation()': '0x5c60da1b', 'symbol()': '0x95d89b41', 'name()': '0x06fdde03'}
T0 = time.time()
def step(name, **kw):
print(json.dumps(dict({'step': name, 't': round(time.time() - T0, 1)}, **kw)), flush=True)
def ct(ts):
d = datetime.datetime.fromtimestamp(ts, CT) if CT else datetime.datetime.utcfromtimestamp(ts)
return d.strftime('%Y-%m-%d %H:%M ') + (d.tzname() if CT else 'UTC')
def addr_of(w):
if not w or w == '0x' or len(w) < 42: return None
try:
v = int(w, 16)
except Exception:
return None
if v == 0 or v >= 2 ** 160: return None
return '0x' + w[-40:].lower()
def words(hexdata):
h = hexdata[2:] if hexdata.startswith('0x') else hexdata
return [h[i:i + 64] for i in range(0, len(h) - len(h) % 64, 64)]
def disasm_push(code):
b = bytes.fromhex(code[2:] if code.startswith('0x') else code); i = 0; out = []
while i < len(b):
op = b[i]
if 0x60 <= op <= 0x7f:
n = op - 0x5f; out.append((n, b[i + 1:i + 1 + n].hex(), b[i + 1 + n] if i + 1 + n < len(b) else None)); i += 1 + n
else:
i += 1
return out
def lookup_selectors(sels):
res = {}
try:
for c in range(0, len(sels), 40):
chunk = sels[c:c + 40]
j = requests.get('https://api.openchain.xyz/signature-database/v1/lookup', params={'function': ','.join(chunk), 'filter': 'true'}, timeout=25).json()
for h, v in (j.get('result', {}).get('function') or {}).items():
if v: res[h] = [x['name'] for x in v]
except Exception:
pass
missing = [s for s in sels if s not in res]
for s in missing[:40]:
try:
j = requests.get('https://www.4byte.directory/api/v1/signatures/', params={'hex_signature': s}, timeout=15).json()
if j.get('results'): res[s] = [x['text_signature'] for x in j['results']][:3]
except Exception:
pass
return res
def sourcify(chain_id, a):
try:
r = requests.get('https://sourcify.dev/server/v2/contract/%d/%s?fields=deployment,abi,compilation' % (chain_id, a), timeout=25)
if r.status_code == 200:
j = r.json(); comp = j.get('compilation') or {}
return {'match': j.get('match'), 'deployment': j.get('deployment'), 'abi': j.get('abi'), 'name': comp.get('name'), 'verifiedAt': j.get('verifiedAt')}
return {'match': None, 'status': r.status_code}
except Exception as e:
return {'match': None, 'error': str(e)[:120]}
def abi_sig(f):
def t(i):
if i.get('type', '').startswith('tuple'):
return '(' + ','.join(t(c) for c in i.get('components', [])) + ')' + i['type'][5:]
return i.get('type')
return '%s(%s)' % (f['name'], ','.join(t(i) for i in f.get('inputs', [])))
def main():
chain, A, OUT = sys.argv[1], sys.argv[2].lower(), sys.argv[3]
budget = 420
if '--budget' in sys.argv: budget = int(sys.argv[sys.argv.index('--budget') + 1])
hint_abi = []
if '--hint-abi' in sys.argv:
try: hint_abi = json.load(open(sys.argv[sys.argv.index('--hint-abi') + 1]))
except Exception: hint_abi = []
os.makedirs(OUT, exist_ok=True)
deadline = T0 + budget
r = RPC(chain); C = CHAINS[chain]
E = {'chain': chain, 'chain_name': C['name'], 'address': A, 'explorer': C['explorer'], 'native': C['native'], 'notes': [], 'gaps': []}
E['notes'].append('All data read with public JSON-RPC nodes and public signature/verification databases. Read-only: no transaction was sent.')
# ---- basics
step('basics')
latest = r.block(); latest_ts = r.block_ts(latest)
E['read_at'] = {'block': latest, 'time_ct': ct(latest_ts), 'ts': latest_ts}
code = r.code(A)
if len(code) <= 2 or code.startswith('0xef0100'):
E['is_contract'] = False
E['kind'] = 'EOA+7702-delegation' if code.startswith('0xef0100') else 'EOA (a personal wallet, no contract code)'
E['native_balance'] = int(r.call('eth_getBalance', [A, 'latest']), 16) / 1e18
E['nonce'] = int(r.call('eth_getTransactionCount', [A, 'latest']), 16)
finish(E, OUT); return
E['is_contract'] = True; E['code_bytes'] = (len(code) - 2) // 2
E['native_balance'] = int(r.call('eth_getBalance', [A, 'latest']), 16) / 1e18
# ---- proxy
step('proxy')
px = {k: addr_of(r.call('eth_getStorageAt', [A, s, 'latest'])) for k, s in SLOTS.items()}
impl = px['impl'] or px['eip1822']
if px['beacon']:
px['type'] = 'beacon proxy'
try: impl = addr_of(r.eth_call(px['beacon'], '0x5c60da1b'))
except Exception: pass
elif impl:
try:
r.eth_call(impl, '0x52d1902d'); uups = True
except Exception:
uups = False
px['type'] = 'UUPS proxy (the upgrade function lives in the implementation)' if uups else ('Transparent proxy (upgrades through the admin slot holder)' if px['admin'] else 'ERC1967 proxy')
else:
px['type'] = 'not a standard upgradeable proxy (no ERC1967 / EIP-1822 / beacon slot set)'
px['upgradeable'] = bool(impl)
E['proxy'] = px
code_target = impl or A
tcode = r.code(code_target) if impl else code
E['impl_code_bytes'] = (len(tcode) - 2) // 2
# ---- verification
step('verification')
ver = {'contract': sourcify(C['id'], A)}
if impl: ver['implementation'] = sourcify(C['id'], impl)
E['verification'] = {k: {kk: v.get(kk) for kk in ('match', 'name', 'verifiedAt')} for k, v in ver.items()}
E['verification_source'] = 'Sourcify (sourcify.dev). A contract verified only on a block explorer may show as not found here.'
abi = (ver.get('implementation') or {}).get('abi') or (ver['contract'] or {}).get('abi') or []
abi_src = 'verified source (Sourcify)' if abi else None
if not abi and hint_abi:
abi = hint_abi; abi_src = 'human-readable ABI found in the project website code (INFERRED)'
# ---- selectors
step('selectors')
P = disasm_push(tcode)
sels = sorted({'0x' + v for (n, v, nx) in P if n == 4 and nx == 0x14})
abi_fns = [f for f in abi if isinstance(f, dict) and f.get('type') == 'function' and f.get('name')]
abi_sigs = {abi_sig(f) for f in abi_fns}
abi_sel = {keccak.selector(abi_sig(f)): abi_sig(f) for f in abi_fns}
outs = {abi_sig(f): [o.get('type') for o in f.get('outputs') or []] for f in abi_fns}
for f in abi:
if isinstance(f, dict) and f.get('type') == 'event' and f.get('name'):
EVENTS.setdefault(keccak.topic(abi_sig(f)), abi_sig(f))
missing = [s for s in sels if s not in abi_sel]
looked = lookup_selectors(missing) if missing else {}
selmap = {s: abi_sel.get(s) or (looked.get(s) or [None])[0] for s in sels}
E['selectors'] = {'count': len(sels), 'named': sum(1 for v in selmap.values() if v), 'map': selmap, 'abi_source': abi_src,
'names_source': ('verified ABI' if abi_src and 'Sourcify' in abi_src else 'openchain.xyz / 4byte.directory signature databases (a name is a public guess from the selector, INFERRED)')}
risky = sorted({v for v in selmap.values() if v and RISKY.match(v)})
E['risky_functions'] = risky
if abi:
E['abi_functions'] = sorted(abi_sigs)[:200]
# ---- role getters: every zero-argument named function, read with eth_call (read-only)
step('roles')
zero = sorted({v for v in selmap.values() if v and v.endswith('()')} | {'owner()', 'admin()', 'getOwner()', 'paused()', 'pendingOwner()'})
sel_of = {v: s for s, v in selmap.items() if v}
sel_of.update({k: v for k, v in KNOWN_SEL.items() if k not in sel_of})
roles, values = {}, {}
skip = re.compile(r'^(renounceOwnership|pause|unpause|refund\(\)$|claim|withdraw|execute|buy|purchase|deposit|stake|unstake|harvest|compound|sync|skim|mint|burn)', re.I)
for fn in zero[:60]:
s = sel_of.get(fn)
if not s or skip.match(fn) and fn not in ('refund()',): continue
try:
v = r.eth_call(A, s)
except Exception:
continue
if not v or v == '0x': continue
if len(v) == 66:
a = addr_of(v)
typed = outs.get(fn)
is_addr = (typed == ['address']) if typed else (a is not None and int(v, 16) > 2 ** 120)
if a and is_addr:
roles[fn] = a
else:
iv = int(v, 16)
if fn == 'paused()': values[fn] = bool(iv)
elif iv < 10 ** 30: values[fn] = iv
E['roles'] = roles; E['values'] = values
if 'paused()' in values: E['paused'] = values['paused()']
# ---- controllers: EOA / contract / Safe
step('controllers')
ctl = {}
for a in sorted(set(list(roles.values()) + [x for x in [px['admin']] if x])):
ctl[a] = kind_of(r, a)
# transparent proxy: the admin slot holder is usually a ProxyAdmin contract; read its owner
if px['admin'] and ctl.get(px['admin'], {}).get('type') == 'contract':
try:
o = addr_of(r.eth_call(px['admin'], '0x8da5cb5b'))
if o: roles['proxy admin owner()'] = o; ctl[o] = kind_of(r, o)
except Exception:
pass
E['controllers'] = ctl
# ---- who can upgrade: read-only eth_call of upgradeToAndCall(current impl, "") from each role holder and a random address
if impl and E['proxy']['type'].startswith('UUPS'):
step('upgrade_test')
data = '0x4f1ef286' + addr_topic(impl)[2:] + '0' * 62 + '40' + '0' * 64
tests = {}
cands = list(dict.fromkeys(list(roles.values())))
rnd = '0x' + ''.join(random.choice('0123456789abcdef') for _ in range(40))
for who in cands[:8] + [rnd]:
try:
r.call('eth_call', [{'from': who, 'to': A, 'data': data}, 'latest'], tries=3)
tests[who] = 'succeeds (this address can upgrade)'
except CallReverted as e:
msg = e.args[0] if e.args else {}
tests[who] = 'reverts ' + str((msg.get('data') if isinstance(msg, dict) else '') or (msg.get('message') if isinstance(msg, dict) else msg))[:80]
except Exception as e:
tests[who] = 'no answer'
E['upgrade_test'] = {'method': 'eth_call (simulation, nothing sent) of upgradeToAndCall(current implementation, empty data)', 'random_address': rnd, 'results': tests}
E['can_upgrade'] = [w for w, t in tests.items() if t.startswith('succeeds') and w != rnd]
if tests.get(rnd, '').startswith('succeeds'): E['notes'].append('A random address could call upgradeToAndCall in simulation: the check is not conclusive for this contract.')
# ---- creation block
step('creation')
dep = (ver['contract'] or {}).get('deployment') or {}
created = None; creation_tx = None; creation_src = None
if dep.get('blockNumber'):
created = int(dep['blockNumber']); creation_tx = (dep.get('transactionHash') or '').lower() or None; creation_src = 'Sourcify deployment record'
else:
created = find_creation(r, A, latest)
if created is not None: creation_src = 'binary search of eth_getCode on an archive node'
E['creation'] = {'block': created, 'source': creation_src}
if created is not None:
try: E['creation']['time_ct'] = ct(r.block_ts(created))
except Exception: pass
E['age_days'] = round((latest_ts - r.block_ts(created)) / 86400, 1) if created else None
# ---- log window
span0 = C['log_providers'][0][1]
cap_chunks = 260 # per filter
frm = created if created is not None else max(0, latest - span0 * 40)
if latest - frm + 1 > span0 * cap_chunks:
E['notes'].append('History is longer than one scan covers: only the latest %d blocks were read.' % (span0 * cap_chunks))
frm = latest - span0 * cap_chunks + 1
E['window'] = {'from': frm, 'to': latest, 'blocks': latest - frm + 1, 'complete_history': created is not None and frm == created}
try: E['window']['from_time_ct'] = ct(r.block_ts(frm))
except Exception: pass
# ---- contract logs
step('logs', blocks=latest - frm + 1)
toks = C['tokens']; tlist = list(toks.values()); E['tokens_checked'] = list(toks.keys())
qin = [[TRANSFER, APPROVAL], None, addr_topic(A)]; qout = [TRANSFER, addr_topic(A)]
# the three filters run side by side and share the provider's pace, so a time cut leaves small gaps in each, not one lost filter
dl = T0 + budget * 0.8
with ThreadPoolExecutor(3) as ex3:
fL = ex3.submit(r.logs, A, frm, latest, None, 2, dl)
fI = ex3.submit(r.logs, tlist, frm, latest, qin, 2, dl)
fO = ex3.submit(r.logs, tlist, frm, latest, qout, 2, dl)
L, gaps = fL.result(); inn, g1 = fI.result(); out, g2 = fO.result()
# second pass over every range that failed (rate limits clear in seconds), with what is left of the budget
passes = 0
while (gaps or g1 or g2) and time.time() < T0 + budget * 0.9 and passes < 4:
passes += 1; step('retry_gaps', ranges=len(gaps) + len(g1) + len(g2))
dl = T0 + budget * 0.9
def refill(addr, topics, gs, have):
left = []
for a, b in gs:
more, g = r.logs(addr, a, b, topics, threads=1, deadline=dl); have += more; left += g
return left
gaps = refill(A, None, gaps, L); g1 = refill(tlist, qin, g1, inn); g2 = refill(tlist, qout, g2, out)
for lst in (L, inn, out):
seen = set(); uniq = []
for l in lst:
k = (l['transactionHash'], l['logIndex'])
if k not in seen: seen.add(k); uniq.append(l)
uniq.sort(key=lambda l: (int(l['blockNumber'], 16), int(l['logIndex'], 16))); lst[:] = uniq
if gaps: E['gaps'].append({'what': 'contract events', 'ranges': gaps})
if g1: E['gaps'].append({'what': 'token transfers in + approvals', 'ranges': g1})
if g2: E['gaps'].append({'what': 'token transfers out', 'ranges': g2})
tc = collections.Counter(l['topics'][0] if l['topics'] else 'anonymous' for l in L)
E['events'] = {'total': len(L), 'by_topic': [{'topic': t, 'name': EVENTS.get(t), 'count': n} for t, n in tc.most_common(30)]}
if not creation_tx and created is not None:
first = [l for l in L if int(l['blockNumber'], 16) == created]
if first: creation_tx = first[0]['transactionHash'].lower(); E['creation']['tx_source'] = 'transaction of the first event in the creation block'
else:
try:
recs = r.call('eth_getBlockReceipts', [hex(created)], tries=3)
for rc in recs or []:
if (rc.get('contractAddress') or '').lower() == A: creation_tx = rc['transactionHash'].lower(); E['creation']['tx_source'] = 'block receipts'; break
except Exception:
pass
E['creation']['tx'] = creation_tx
tsc = {}
def bts(n):
if n not in tsc:
try: tsc[n] = r.block_ts(n)
except Exception: tsc[n] = None
return tsc[n]
adm = []
for l in L:
if l['topics'] and l['topics'][0] in ADMIN_EVENTS:
b = int(l['blockNumber'], 16)
ts = int(l['blockTimestamp'], 16) if l.get('blockTimestamp') else bts(b)
arg = topic_addr(l['topics'][1]) if len(l['topics']) > 1 and l['topics'][1][2:26] == '0' * 24 else (topic_addr(l['data']) if l['topics'][0] == UPGRADED and l['data'] != '0x' else None)
if l['topics'][0] == '0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0' and len(l['topics']) > 2:
arg = '%s -> %s' % (topic_addr(l['topics'][1]), topic_addr(l['topics'][2]))
adm.append({'event': EVENTS[l['topics'][0]], 'block': b, 'time_ct': ct(ts) if ts else None, 'tx': l['transactionHash'].lower(), 'arg': arg,
'in_creation_tx': bool(creation_tx and l['transactionHash'].lower() == creation_tx)})
E['admin_events'] = adm[:80]
# decode the contract's own events with the verified ABI (static fields only): counts, sums of number fields, top addresses
dec_ev = {}; dec_rows = {}
abi_events = {keccak.topic(abi_sig(f)): f for f in abi if isinstance(f, dict) and f.get('type') == 'event' and f.get('name') and not f.get('anonymous')}
for t, f in abi_events.items():
if t in ADMIN_EVENTS or t in (TRANSFER, APPROVAL): continue
ls = [l for l in L if l['topics'] and l['topics'][0] == t]
if not ls: continue
sums = collections.Counter(); addrs = collections.defaultdict(collections.Counter); samples = []
for l in ls:
ti = 1; dw = words(l['data']); di = 0; row = {}
for inp in f.get('inputs', []):
typ = inp.get('type'); nm = inp.get('name') or typ
if inp.get('indexed'):
raw = l['topics'][ti] if ti < len(l['topics']) else None; ti += 1
else:
if typ in ('string', 'bytes') or typ.endswith(']') or typ.startswith('tuple'):
di += 1; continue
raw = '0x' + dw[di] if di < len(dw) else None; di += 1
if raw is None: continue
if typ == 'address': v = topic_addr(raw); addrs[nm][v] += 1
elif typ.startswith('uint'): v = int(raw, 16); sums[nm] += v
elif typ == 'bool': v = bool(int(raw, 16))
else: v = raw
row[nm] = v
if len(samples) < 5: samples.append({'block': int(l['blockNumber'], 16), 'tx': l['transactionHash'].lower(), 'fields': row})
dec_rows.setdefault(abi_sig(f), []).append((int(l['blockNumber'], 16), int(l['logIndex'], 16), l['transactionHash'].lower(), row))
dec_ev[abi_sig(f)] = {'count': len(ls), 'uint_field_sums_raw': dict(sums), 'top_addresses': {k: v.most_common(8) for k, v in addrs.items()}, 'first_samples': samples}
E['decoded_events'] = dec_ev
ups = [x for x in adm if x['event'] == 'Upgraded(address)']
E['counts'] = {'upgrade_events_total': len(ups), 'upgrades_after_deployment': sum(1 for x in ups if not x['in_creation_tx']) if creation_tx else None,
'upgrades_note': 'An Upgraded event inside the deployment transaction sets the first implementation and is not counted as an upgrade.',
'pause_events': sum(1 for x in adm if x['event'] == 'Paused(address)'), 'ownership_transfers': sum(1 for x in adm if x['event'].startswith('OwnershipTransferred'))}
if creation_tx is None and ups:
E['notes'].append('The deployment transaction is unknown, so upgrades after deployment could not be separated from the first implementation set at deployment.')
# ---- tokens: transfers in/out and approvals to the contract (stable tokens of this chain)
step('tokens')
dec = {}; sym = {v: k for k, v in toks.items()}
for t in tlist:
try: dec[t] = int(r.eth_call(t, '0x313ce567'), 16)
except Exception: dec[t] = 18 if chain == 'bsc' else 6
tin = [l for l in inn if l['topics'][0] == TRANSFER]; apps = [l for l in inn if l['topics'][0] == APPROVAL]
money = {}
for t in tlist:
d = 10 ** dec[t]
i_ = [l for l in tin if l['address'].lower() == t]; o_ = [l for l in out if l['address'].lower() == t]
try: bal = int(r.eth_call(t, '0x70a08231' + addr_topic(A)[2:]), 16) / d
except Exception: bal = None
if not i_ and not o_ and not bal: continue
fin = collections.Counter(); fout = collections.Counter(); cin = collections.Counter(); cout = collections.Counter()
for l in i_: a = topic_addr(l['topics'][1]); fin[a] += int(l['data'], 16) / d; cin[a] += 1
for l in o_: a = topic_addr(l['topics'][2]); fout[a] += int(l['data'], 16) / d; cout[a] += 1
sizes = collections.Counter(round(int(l['data'], 16) / d, 4) for l in o_)
days = collections.Counter()
for l in i_:
b = int(l['blockNumber'], 16); ts = int(l['blockTimestamp'], 16) if l.get('blockTimestamp') else None
if ts: days[ct(ts)[:10]] += 1
money[sym[t]] = {'token': t, 'decimals': dec[t], 'balance_now': bal, 'in_count': len(i_), 'in_total': round(sum(fin.values()), 6), 'payers': len(fin),
'out_count': len(o_), 'out_total': round(sum(fout.values()), 6), 'recipients': len(fout),
'net_in_minus_out': round(sum(fin.values()) - sum(fout.values()), 6),
'top_recipients': [[a, round(v, 4), cout[a]] for a, v in fout.most_common(15)],
'top_payers': [[a, round(v, 4), cin[a]] for a, v in fin.most_common(10)],
'out_sizes': [[k, v] for k, v in sizes.most_common(10)],
'daily_in_counts': sorted(days.items())}
E['money'] = money
# approvals: live allowance and balance per approving wallet
step('approvals')
appr = {}
for t in tlist:
al = [l for l in apps if l['address'].lower() == t]
if not al: continue
owners = sorted({topic_addr(l['topics'][1]) for l in al})[:1500]
d = 10 ** dec[t]
def one(o):
try:
a_ = int(r.eth_call(t, '0xdd62ed3e' + addr_topic(o)[2:] + addr_topic(A)[2:]), 16)
b_ = int(r.eth_call(t, '0x70a08231' + addr_topic(o)[2:]), 16)
return o, a_, b_
except Exception:
return o, None, None
with ThreadPoolExecutor(6) as ex: res = list(ex.map(one, owners))
ok = [x for x in res if x[1] is not None]
live = [x for x in ok if x[1] > 0]
appr[sym[t]] = {'approval_events': len(al), 'approving_wallets': len(owners), 'read': len(ok),
'live_allowances': len(live), 'unlimited': sum(1 for x in ok if x[1] >= 2 ** 255),
'pullable_now': round(sum(min(x[1], x[2]) for x in ok) / d, 6)}
E['approvals'] = appr
# ---- positions probe (contracts that store numbered positions with an owner in the first field)
step('positions')
pos = None
for cnt_fn, get_fn in POSITION_PAIRS:
if cnt_fn in sel_of and get_fn in sel_of and time.time() < T0 + budget * 0.93:
try:
n = int(r.eth_call(A, sel_of[cnt_fn]), 16)
except Exception:
continue
if not (0 < n <= 20000): continue
s = sel_of[get_fn]
def one(i):
try:
v = r.eth_call(A, s + hex(i)[2:].rjust(64, '0'))
return i, addr_of('0x' + words(v)[0]) if v and len(v) >= 66 else None
except Exception:
return i, None
ids = list(range(0, n + 1))
with ThreadPoolExecutor(8) as ex: res = list(ex.map(one, ids))
own = collections.Counter(a for i, a in res if a)
pos = {'count_function': cnt_fn, 'count': n, 'getter': get_fn, 'read': sum(1 for i, a in res if a),
'method': 'eth_call of %s for ids 0..%d; owner = the first returned field (INFERRED layout)' % (get_fn, n),
'owners': len(own), 'top_owners': [[a, c] for a, c in own.most_common(15)]}
break
E['positions'] = pos
# ---- deployment arguments (addresses passed in the creation transaction)
step('deployer')
labels = {}
for fn, a in roles.items(): labels.setdefault(a, []).append(fn)
if creation_tx:
try:
tx = r.call('eth_getTransactionByHash', [creation_tx])
E['creation']['from'] = tx['from'].lower(); labels.setdefault(tx['from'].lower(), []).append('deployer')
init_addrs = []
for w in words(tx['input'][-64 * 24:]):
a = addr_of('0x' + w)
if a and w[:24] == '0' * 24 and a not in init_addrs and a != A and int(a, 16) > 2 ** 100: init_addrs.append(a)
E['creation']['addresses_in_input'] = init_addrs[:12]
except Exception:
pass
# ---- who gets paid when someone buys (rubric red flag 4: earlier buyers paid from later buyers' payments)
step('payouts')
try:
import payouts
tl = lambda l, i: (int(l['blockNumber'], 16), int(l['logIndex'], 16), l['transactionHash'].lower(), topic_addr(l['topics'][i]), int(l['data'], 16) if l['data'] not in ('0x', '') else 0)
E['payout_relations'] = payouts.analyse(E, dec_rows, [tl(l, 1) for l in tin], [tl(l, 2) for l in out])
except Exception as e:
E['payout_relations'] = {'error': str(e)[:200]}
# ---- profiles of labelled wallets (roles + deployer + top recipients)
step('wallets')
recv = collections.Counter();
for sy, m in money.items():
for a, v, c in m['top_recipients']: recv[a] += v
cand = list(dict.fromkeys(list(labels.keys()) + [a for a in E.get('creation', {}).get('addresses_in_input', [])] + [a for a, _ in recv.most_common(6)]))
prof = {}
stable = toks.get('USDT') or tlist[0]
for a in cand[:16]:
try:
k = kind_of(r, a)
k['native_balance'] = int(r.call('eth_getBalance', [a, 'latest']), 16) / 1e18
k['nonce'] = int(r.call('eth_getTransactionCount', [a, 'latest']), 16)
k['labels'] = labels.get(a, []) + (['address in deployment input'] if a in E['creation'].get('addresses_in_input', []) else [])
got = {sy: round(sum(v for x, v, c in m['top_recipients'] if x == a), 4) for sy, m in money.items()}
k['received_from_contract'] = {s: v for s, v in got.items() if v}
if pos: k['positions_owned'] = dict(pos['top_owners']).get(a, 0)
prof[a] = k
except Exception:
continue
E['wallets'] = prof
# ---- native coin sent in with the calls that emitted events (msg.value of those transactions; internal transfers out are not traced)
step('native_in')
hs = list(dict.fromkeys(l['transactionHash'] for l in L))
cap = 400; hs_read = hs[-cap:]
def gtx(h):
try:
t = r.call('eth_getTransactionByHash', [h], tries=3)
return {'from': t['from'].lower(), 'to': (t.get('to') or '').lower(), 'value': int(t['value'], 16), 'sel': t['input'][:10]}
except Exception:
return None
if time.time() < T0 + budget * 0.95:
with ThreadPoolExecutor(8) as ex: txs = [x for x in ex.map(gtx, hs_read) if x]
direct = [t for t in txs if t['to'] == A]
selc = collections.Counter(t['sel'] for t in direct)
sndc = collections.Counter(t['from'] for t in direct)
E['txs'] = {'event_txs_total': len(hs), 'read': len(txs), 'read_note': ('the latest %d of them' % cap) if len(hs) > cap else 'all of them',
'direct_calls': len(direct), 'native_sent_in': round(sum(t['value'] for t in direct) / 1e18, 6),
'calls_with_native': sum(1 for t in direct if t['value']),
'by_function': [[selmap.get(k) or k, n] for k, n in selc.most_common(12)], 'top_senders': [[a, n] for a, n in sndc.most_common(10)]}
# ---- the transactions behind admin events (sender + selector)
step('admin_txs')
for x in E['admin_events'][:30]:
try:
t = r.call('eth_getTransactionByHash', [x['tx']], tries=3)
x['from'] = t['from'].lower(); x['selector'] = t['input'][:10]
except Exception:
pass
E['rpc_calls'] = r.calls
finish(E, OUT)
def kind_of(r, a):
code = r.code(a)
if len(code) <= 2: return {'type': 'EOA', 'desc': 'personal wallet (EOA), one key'}
if code.startswith('0xef0100'): return {'type': 'EOA+7702', 'desc': 'personal wallet with EIP-7702 delegated code', 'delegate': '0x' + code[8:48]}
try:
th = int(r.eth_call(a, '0xe75235b8'), 16)
return {'type': 'safe', 'desc': 'Safe multisig, threshold %d' % th, 'threshold': th}
except Exception:
return {'type': 'contract', 'desc': 'contract (%d bytes)' % ((len(code) - 2) // 2)}
def find_creation(r, A, latest):
urls = r.c.get('archive_rpcs') or []
for u in urls:
try:
def has(b):
c = r.call('eth_getCode', [A, hex(b)], tries=3, urls=[u]); return len(c) > 2
if not has(latest): continue
lo, hi = 0, latest
# quick probe: most contracts we see are young, search the recent part first
for back in (200000, 2000000, 20000000):
if latest - back > 0 and not has(latest - back): lo = latest - back; break
while hi - lo > 1:
mid = (lo + hi) // 2
if has(mid): hi = mid
else: lo = mid
return hi
except Exception:
continue
return None
def finish(E, OUT):
E['elapsed_s'] = round(time.time() - T0, 1)
json.dump(E, open(os.path.join(OUT, 'evidence.json'), 'w', encoding='utf8', newline='\n'), indent=1)
import pack
md = pack.build(E)
open(os.path.join(OUT, 'pack.md'), 'w', encoding='utf8', newline='\n').write(md)
json.dump(pack.facts(E), open(os.path.join(OUT, 'facts.json'), 'w', encoding='utf8', newline='\n'), indent=1)
print(json.dumps({'done': True, 'elapsed': E['elapsed_s'], 'pack_chars': len(md)}), flush=True)
if __name__ == '__main__':
main()