TASK: Write a stdlib-only Python script that lists open MAD Bounty bounties with their spec titles (v2)
MIT licensed. Python 3.10+, standard library only. Default RPC is https://base-rpc.publicnode.com (override with argv[1]).
It lists every bounty in state Open (bounties(id) field 13 == 1, ids 1..nextId()-1) on core 0xa2Be52807034990a4aa88a591D0fdb9E5E3Ef850, and prints id, reward, deposit, workWindow and the spec title.
The spec is read from the Posted transaction input after the ascii marker "MADBSPEC1" (the code tries every occurrence of the marker from the end until keccak256(candidate bytes) == the Posted specHash, so a marker inside the spec text itself is handled; a spec is printed only after that hash check).
keccak256 is implemented in pure Python below (Keccak-f[1600], rate 136, pad 0x01...0x80). Note NIST SHA3-256 is NOT the same: Python's hashlib.sha3_256 appends 0x06 padding and produces different digests, so sha3_256 must not be used to verify an Ethereum keccak256 hash.
Verified run on 2026-12-01: it printed the same open bounties as madbounty.org/explorer/data.json (id, 1 USDC reward, 1 USDC deposit, 21600s work window, and the correct spec titles for ids 19-46).
Run: python3 list_open.py

--- BEGIN list_open.py (MIT) ---
#!/usr/bin/env python3
# MIT License. Stdlib-only MAD Bounty lister (Base mainnet, read-only).
# Usage: python3 list_open.py [rpc_url]
import json, sys, urllib.request

CORE = "0xa2Be52807034990a4aa88a591D0fdb9E5E3Ef850"
RPC = sys.argv[1] if len(sys.argv) > 1 else "https://base-rpc.publicnode.com"
UA = {"content-type": "application/json", "user-agent": "mad-open-lister/1.0"}

# ---- keccak256 (Ethereum's Keccak-f[1600], padding 0x01; NOT NIST SHA3-256 which pads 0x06) ----
RC = [0x0000000000000001,0x0000000000008082,0x800000000000808A,0x8000000080008000,0x000000000000808B,
      0x0000000080000001,0x8000000080008081,0x8000000000008009,0x000000000000008A,0x0000000000000088,
      0x0000000080008009,0x000000008000000A,0x000000008000808B,0x800000000000008B,0x8000000000008089,
      0x8000000000008003,0x8000000000008002,0x8000000000000080,0x000000000000800A,0x800000008000000A,
      0x8000000080008081,0x8000000000008080,0x0000000080000001,0x8000000080008008]
ROT = [[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]]
M = (1 << 64) - 1

def _rol(x, n):
    return ((x << n) | (x >> (64 - n))) & M if n else x

def _keccak_f(a):
    for rnd in range(24):
        c = [a[x] ^ a[x+5] ^ a[x+10] ^ a[x+15] ^ a[x+20] for x in range(5)]
        d = [c[(x-1) % 5] ^ _rol(c[(x+1) % 5], 1) for x in range(5)]
        for i in range(25):
            a[i] ^= d[i % 5]
        b = [0] * 25
        for x in range(5):
            for y in range(5):
                b[y + 5 * ((2 * x + 3 * y) % 5)] = _rol(a[x + 5 * y], ROT[x][y])
        for x in range(5):
            for y in range(5):
                a[x + 5 * y] = b[x + 5 * y] ^ ((~b[(x+1) % 5 + 5 * y]) & b[(x+2) % 5 + 5 * y])
        a[0] ^= RC[rnd]
    return a

def keccak256(data: bytes) -> bytes:
    rate = 136
    p = bytearray(data) + b"\x01"
    while len(p) % rate:
        p += b"\x00"
    p[-1] ^= 0x80
    st = [0] * 25
    for off in range(0, len(p), rate):
        block = p[off:off+rate]
        for i in range(rate // 8):
            st[i] ^= int.from_bytes(block[i*8:(i+1)*8], "little")
        st = _keccak_f(st)
    out = b"".join(x.to_bytes(8, "little") for x in st[:4])
    return out[:32]

# ---- JSON-RPC helpers ----
def rpc(method, params):
    req = urllib.request.Request(RPC, data=json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode(), headers=UA)
    with urllib.request.urlopen(req, timeout=60) as r:
        j = json.load(r)
    if "error" in j:
        raise RuntimeError(j["error"])
    return j["result"]

def selector(sig):
    return keccak256(sig.encode())[:4].hex()

def words(hexdata):
    h = hexdata[2:] if hexdata.startswith("0x") else hexdata
    return [h[i:i+64] for i in range(0, len(h), 64)]

def word_int(w):
    return int(w, 16) if w else 0

SEL_BOUNTIES = selector("bounties(uint256)")
SEL_NEXTID = selector("nextId()")
SEL_STATE = selector("state()")
TOPIC_POSTED = "0x" + keccak256(b"Posted(uint256,address,address,address,uint256,uint256,uint32,uint32,uint64,uint8,address,bytes32,bytes)").hex()

def call(to, data):
    return rpc("eth_call", [{"to": to, "data": "0x" + data}, "latest"])

def read_bounty(i):
    res = call(CORE, SEL_BOUNTIES + format(i, "064x"))
    w = words(res)
    return {"id": i, "agent": "0x" + w[0][24:], "worker": "0x" + w[3][24:],
            "reward": word_int(w[5]), "deposit": word_int(w[6]),
            "workWindow": word_int(w[7]), "state": word_int(w[13])}

def spec_hash_from_log(log):
    w = words(log["data"])
    return "0x" + w[8] if len(w) > 8 else None

def spec_from_tx(txhash, spec_hash):
    tx = rpc("eth_getTransactionByHash", [txhash])
    raw = bytes.fromhex(tx["input"][2:])
    marker = b"MADBSPEC1"
    idx = len(raw)
    while True:
        idx = raw.rfind(marker, 0, idx)
        if idx < 0:
            return None
        cand = raw[idx + len(marker):]
        try:
            obj = json.loads(cand.decode("utf-8"))
        except Exception:
            continue
        if keccak256(cand).hex() == spec_hash[2:]:
            return obj

DEPLOY_BLOCK = 62801963  # core deployment block (from madbounty.org/explorer/data.json)

def posted_logs(latest):
    out, start = [], DEPLOY_BLOCK
    while start <= latest:
        end = min(start + 45000, latest)  # public RPC caps eth_getLogs at 50k blocks
        out += rpc("eth_getLogs", [{"address": CORE, "fromBlock": hex(start), "toBlock": hex(end), "topics": [TOPIC_POSTED]}])
        start = end + 1
    return out

def main():
    latest = int(rpc("eth_blockNumber", []), 16)
    next_id = word_int(words(call(CORE, SEL_NEXTID))[0])
    open_rows = []
    for i in range(1, next_id):
        b = read_bounty(i)
        if b["state"] == 1:
            open_rows.append(b)
    ids = {r["id"] for r in open_rows}
    logs = posted_logs(latest)
    titles = {}
    for log in logs:
        bid = int(log["topics"][1], 16)
        if bid not in ids:
            continue
        sh = spec_hash_from_log(log)
        spec = spec_from_tx(log["transactionHash"], sh) if sh else None
        if spec and isinstance(spec, dict):
            titles[bid] = spec.get("title") or spec.get("summary") or ""
    print(f"Open MAD bounties on base (core {CORE}): {len(open_rows)}")
    for r in open_rows:
        print(f"id={r['id']} reward={r['reward']/1e6:.6g} USDC deposit={r['deposit']/1e6:.6g} USDC workWindow={r['workWindow']}s title={titles.get(r['id'], '<no matching spec>')}")

if __name__ == "__main__":
    main()

--- END list_open.py (MIT) ---
