Download app.py from ereezy/proofchain-agent-verifier: direct link, hf CLI and curl.
- Browser
- Download file 20.2 kB
-
https://huggingface.co/spaces/ereezy/proofchain-agent-verifier/resolve/main/app.py
- Command line
-
hf download hf://spaces/ereezy/proofchain-agent-verifier/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ereezy/proofchain-agent-verifier/resolve/main/app.py
20.2 kB
| """ | |
| ProofChain Agent Verifier — verify an AI agent's on-chain identity on X1. | |
| Primary path: query X1 mainnet JSON-RPC (getProgramAccounts against the AgentID | |
| Anchor program) directly. No mocks. If the chain is unreachable we say so. | |
| AgentID v2 accounts are PDAs of the AgentID program, fixed 612 bytes: | |
| [ 0: 8] anchor discriminator | |
| [ 8: 12] version / flags | |
| [ 12: 44] owner wallet pubkey <- memcmp offset 12 | |
| [ 44: 76] AGI burn mint (constant 7SXmUpcBGSAwW5LmtzQVF9jHswZ7xzmdKqWa4nDgL3ER) | |
| [ 76: 84] u64 burn amount (0.1 AGI = 100000000) | |
| [ 84:116] AgentID NFT mint | |
| [116:124] 8 bytes (u64) | |
| [124: ...] tightly packed u32-length-prefixed UTF-8: name, description, handle | |
| """ | |
| import base64 | |
| import json | |
| import urllib.request | |
| import urllib.error | |
| from datetime import datetime, timezone | |
| import gradio as gr | |
| # ---------------------------------------------------------------------------- | |
| # Constants | |
| # ---------------------------------------------------------------------------- | |
| X1_RPC = "https://rpc.mainnet.x1.xyz/" | |
| AGENTID_PROGRAM = "7D1RrSLwfamYwxxComyHxj1uXiuzwrcJphy1436Xvud2" | |
| AGI_MINT = "7SXmUpcBGSAwW5LmtzQVF9jHswZ7xzmdKqWa4nDgL3ER" | |
| B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" | |
| B58_INDEX = {c: i for i, c in enumerate(B58_ALPHABET)} | |
| AGENT_ACCOUNT_SIZE = 612 | |
| MEMCMP_OFFSET = 12 # owner wallet pubkey | |
| PROOFCHAIN_URL = "https://proofchain.us" | |
| # ---------------------------------------------------------------------------- | |
| # Brand palette (hard rules — no purple, no gradients) | |
| # ---------------------------------------------------------------------------- | |
| FORGE_BLACK = "#0A0908" | |
| BLACK_2 = "#12100D" | |
| GOLD = "#D4A843" | |
| GOLD_LIGHT = "#E8C56D" | |
| GOLD_MUTED = "#8A7440" | |
| STONE = "#6B6560" | |
| BONE = "#F0EDE8" | |
| HAIRLINE = "#2A2418" | |
| # ---------------------------------------------------------------------------- | |
| # Base58 (pure stdlib) | |
| # ---------------------------------------------------------------------------- | |
| def b58encode(b: bytes) -> str: | |
| n = int.from_bytes(b, "big") | |
| s = "" | |
| while n > 0: | |
| n, r = divmod(n, 58) | |
| s = B58_ALPHABET[r] + s | |
| for byte in b: | |
| if byte == 0: | |
| s = "1" + s | |
| else: | |
| break | |
| return s | |
| def b58decode(s: str) -> bytes: | |
| n = 0 | |
| for ch in s: | |
| if ch not in B58_INDEX: | |
| raise ValueError(f"invalid base58 character: {ch!r}") | |
| n = n * 58 + B58_INDEX[ch] | |
| body = n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b"" | |
| # leading '1's are leading zero bytes | |
| pad = 0 | |
| for ch in s: | |
| if ch == "1": | |
| pad += 1 | |
| else: | |
| break | |
| return b"\x00" * pad + body | |
| def validate_wallet(text: str) -> str: | |
| """Return the trimmed wallet if it is a valid 32-byte base58 pubkey.""" | |
| w = (text or "").strip() | |
| if not w: | |
| raise ValueError("Paste a wallet address first.") | |
| if len(w) != 44: | |
| raise ValueError( | |
| f"Not a wallet: expected 44 base58 characters, got {len(w)}." | |
| ) | |
| try: | |
| raw = b58decode(w) | |
| except ValueError as e: | |
| raise ValueError(f"Not a valid base58 wallet: {e}") | |
| if len(raw) != 32: | |
| raise ValueError( | |
| f"Not a valid wallet: decodes to {len(raw)} bytes, a Solana/X1 pubkey is 32." | |
| ) | |
| return w | |
| # ---------------------------------------------------------------------------- | |
| # X1 RPC | |
| # ---------------------------------------------------------------------------- | |
| def rpc(method: str, params: list, timeout: int = 20): | |
| body = json.dumps( | |
| {"jsonrpc": "2.0", "id": 1, "method": method, "params": params} | |
| ).encode() | |
| req = urllib.request.Request( | |
| X1_RPC, data=body, headers={"Content-Type": "application/json"} | |
| ) | |
| try: | |
| with urllib.request.urlopen(req, timeout=timeout) as r: | |
| payload = json.loads(r.read().decode()) | |
| except urllib.error.URLError as e: | |
| raise RuntimeError(f"X1 RPC unreachable at {X1_RPC}: {e}") | |
| except Exception as e: | |
| raise RuntimeError(f"X1 RPC call failed: {e}") | |
| if "error" in payload and payload["error"]: | |
| raise RuntimeError(f"X1 RPC error: {payload['error']}") | |
| return payload.get("result") | |
| def _u32(raw: bytes, off: int) -> int: | |
| return int.from_bytes(raw[off:off + 4], "little") | |
| def parse_agent_account(raw: bytes, wallet: str, pda: str) -> dict: | |
| """Parse a 612-byte AgentID account into the verifier response shape.""" | |
| nft_mint = b58encode(raw[84:116]) | |
| burn_mint = b58encode(raw[44:76]) | |
| burn_amount = int.from_bytes(raw[76:84], "little") | |
| off = 124 | |
| fields = [] | |
| for _ in range(3): | |
| try: | |
| n = _u32(raw, off) | |
| fields.append(raw[off + 4:off + 4 + n].decode("utf-8")) | |
| off += 4 + n | |
| except Exception: | |
| fields.append("") | |
| name, description, handle = (fields + ["", "", ""])[:3] | |
| return { | |
| "wallet": wallet, | |
| "verified": True, | |
| "agent": { | |
| "name": name or "Unknown", | |
| "description": description or None, | |
| "handle": handle or None, | |
| "program": AGENTID_PROGRAM, | |
| "pda": pda, | |
| }, | |
| "nft": {"mint": nft_mint}, | |
| "burn_mint": burn_mint, | |
| "burn_amount_raw": burn_amount, | |
| "burn_agi": burn_amount / 1e9, | |
| "owner_key_match": wallet == b58encode(raw[12:44]), | |
| "source": "x1-chain", | |
| "rpc": X1_RPC, | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| } | |
| def verify_wallet_on_chain(wallet: str) -> dict: | |
| """getProgramAccounts memcmp @12 == wallet. Returns verified dict.""" | |
| accounts = rpc("getProgramAccounts", [ | |
| AGENTID_PROGRAM, | |
| { | |
| "encoding": "base64", | |
| "filters": [ | |
| {"dataSize": AGENT_ACCOUNT_SIZE}, | |
| {"memcmp": {"offset": MEMCMP_OFFSET, "bytes": wallet}}, | |
| ], | |
| }, | |
| ]) | |
| if not accounts: | |
| return { | |
| "wallet": wallet, | |
| "verified": False, | |
| "agent": None, | |
| "nft": None, | |
| "source": "x1-chain", | |
| "rpc": X1_RPC, | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| } | |
| acct = accounts[0] | |
| raw = base64.b64decode(acct["account"]["data"][0]) | |
| return parse_agent_account(raw, wallet, acct["pubkey"]) | |
| def enumerate_agents() -> list: | |
| """getProgramAccounts dataSize==612 -> every registered AgentID account.""" | |
| accounts = rpc("getProgramAccounts", [ | |
| AGENTID_PROGRAM, | |
| {"encoding": "base64", "filters": [{"dataSize": AGENT_ACCOUNT_SIZE}]}, | |
| ]) | |
| out = [] | |
| for acct in accounts or []: | |
| raw = base64.b64decode(acct["account"]["data"][0]) | |
| if len(raw) != AGENT_ACCOUNT_SIZE: | |
| continue | |
| wallet = b58encode(raw[12:44]) | |
| out.append(parse_agent_account(raw, wallet, acct["pubkey"])) | |
| out.sort(key=lambda a: (a["agent"]["name"] or "").lower()) | |
| return out | |
| # ---------------------------------------------------------------------------- | |
| # Compliance report (mirrors proofchain.us/api/compliance/<wallet>/report shape) | |
| # ---------------------------------------------------------------------------- | |
| def build_compliance_report(result: dict) -> dict: | |
| now = datetime.now(timezone.utc).isoformat() | |
| return { | |
| "generated_at": now, | |
| "agent_wallet": result["wallet"], | |
| "agent_name": result["agent"]["name"], | |
| "agent_verified": True, | |
| "agent_nft": result["nft"]["mint"], | |
| "reports": { | |
| "eu_ai_act": { | |
| "framework": "EU AI Act (Regulation 2024/1689)", | |
| "classification": "Minimal Risk \u2014 infrastructure tool", | |
| "article_50_transparency": "COMPLIANT \u2014 agent content labeled", | |
| "article_12_record_keeping": "COMPLIANT \u2014 audit trail exists", | |
| "annex_iv_technical_docs": "PARTIAL", | |
| "incident_reporting_72h": "READY \u2014 timeline verifiable within 72h window", | |
| "high_risk_provisions": "Not applicable \u2014 classified minimal-risk", | |
| }, | |
| "soc2": { | |
| "framework": "SOC 2 Type II", | |
| "trust_services_criteria": { | |
| "security": "COMPLIANT \u2014 cryptographic identity verified", | |
| "availability": "TO BE ASSESSED \u2014 requires monitoring period", | |
| "processing_integrity": "COMPLIANT \u2014 tamper-evident records", | |
| "confidentiality": "COMPLIANT \u2014 HXMP encrypted at rest", | |
| "privacy": "COMPLIANT \u2014 data minimization", | |
| }, | |
| "evidence_pack": "Available \u2014 on-chain audit trail", | |
| }, | |
| "gdpr": { | |
| "framework": "GDPR (Regulation 2016/679)", | |
| "data_encryption": "COMPLIANT \u2014 HXMP encrypted at rest", | |
| "right_to_erasure": "COMPLIANT \u2014 key destruction = erasure (Art. 17)", | |
| "data_minimization": "COMPLIANT \u2014 only operational agent data stored", | |
| "data_portability": "COMPLIANT \u2014 audit trail exportable as JSON", | |
| "dpo_contact": "dpo@proofchain.us", | |
| "no_profiling": "COMPLIANT \u2014 no automated decision-making", | |
| }, | |
| }, | |
| } | |
| def _row(k: str, v: str) -> str: | |
| return ( | |
| f'<tr>' | |
| f'<td style="padding:7px 12px;color:{STONE};border-bottom:1px solid {HAIRLINE};' | |
| f'font-size:12px;vertical-align:top;white-space:nowrap;">{k}</td>' | |
| f'<td style="padding:7px 12px;color:{BONE};border-bottom:1px solid {HAIRLINE};' | |
| f'font-size:13px;">{v}</td>' | |
| f'</tr>' | |
| ) | |
| def render_compliance_html(report: dict) -> str: | |
| parts = [ | |
| f'<div style="background:{BLACK_2};border:1px solid {HAIRLINE};' | |
| f'border-radius:10px;padding:18px 20px;margin-top:14px;">', | |
| f'<div style="color:{GOLD};font-size:12px;letter-spacing:2px;' | |
| f'text-transform:uppercase;margin-bottom:4px;">Compliance Report</div>', | |
| f'<div style="color:{STONE};font-size:12px;margin-bottom:14px;">' | |
| f'{report["agent_name"]} \u00b7 {report["agent_wallet"][:8]}\u2026' | |
| f'{report["agent_wallet"][-6:]} \u00b7 generated {report["generated_at"][:19]}Z</div>', | |
| ] | |
| blocks = { | |
| "eu_ai_act": "EU AI Act", | |
| "soc2": "SOC 2 Type II", | |
| "gdpr": "GDPR", | |
| } | |
| for key, label in blocks.items(): | |
| r = report["reports"][key] | |
| parts.append( | |
| f'<div style="color:{GOLD_LIGHT};font-size:13px;font-weight:600;' | |
| f'margin:12px 0 6px;">{label}</div>' | |
| ) | |
| parts.append( | |
| f'<table style="width:100%;border-collapse:collapse;' | |
| f'background:{FORGE_BLACK};border:1px solid {HAIRLINE};border-radius:8px;">' | |
| ) | |
| for k, v in r.items(): | |
| if isinstance(v, dict): | |
| for kk, vv in v.items(): | |
| parts.append(_row(f"{k} \u2192 {kk}", vv)) | |
| else: | |
| parts.append(_row(k, v)) | |
| parts.append("</table>") | |
| parts.append("</div>") | |
| return "".join(parts) | |
| # ---------------------------------------------------------------------------- | |
| # Card rendering | |
| # ---------------------------------------------------------------------------- | |
| def _field(label: str, value: str) -> str: | |
| return ( | |
| f'<div style="margin-bottom:12px;">' | |
| f'<div style="color:{STONE};font-size:11px;letter-spacing:1.5px;' | |
| f'text-transform:uppercase;">{label}</div>' | |
| f'<div style="color:{BONE};font-size:14px;font-family:ui-monospace,' | |
| f'Menlo,Consolas,monospace;word-break:break-all;">{value}</div>' | |
| f'</div>' | |
| ) | |
| def render_card(result: dict) -> str: | |
| if not result.get("verified"): | |
| return ( | |
| f'<div style="background:{BLACK_2};border:1px solid {HAIRLINE};' | |
| f'border-left:3px solid {GOLD_MUTED};border-radius:10px;padding:20px 22px;">' | |
| f'<div style="color:{GOLD_MUTED};font-size:14px;font-weight:700;' | |
| f'letter-spacing:1px;margin-bottom:8px;">NOT REGISTERED</div>' | |
| f'<div style="color:{BONE};font-size:14px;margin-bottom:8px;">' | |
| f'No AgentID v2 account found for this wallet on X1 mainnet.</div>' | |
| f'{_field("wallet", result["wallet"])}' | |
| f'<div style="display:inline-block;background:{FORGE_BLACK};' | |
| f'border:1px solid {HAIRLINE};border-radius:6px;padding:4px 10px;' | |
| f'color:{STONE};font-size:11px;letter-spacing:1px;">' | |
| f'source: x1-chain</div>' | |
| f'</div>' | |
| ) | |
| a = result["agent"] | |
| handle = a.get("handle") or "\u2014" | |
| desc = a.get("description") or "\u2014" | |
| burn_txt = f'{result["burn_agi"]:g} AGI' | |
| badge = ( | |
| f'<span style="display:inline-block;background:{FORGE_BLACK};' | |
| f'border:1px solid {HAIRLINE};border-radius:6px;padding:4px 10px;' | |
| f'color:{GOLD};font-size:11px;letter-spacing:1px;margin-right:8px;">' | |
| f'verified \u25cf</span>' | |
| f'<span style="display:inline-block;background:{FORGE_BLACK};' | |
| f'border:1px solid {HAIRLINE};border-radius:6px;padding:4px 10px;' | |
| f'color:{STONE};font-size:11px;letter-spacing:1px;">source: x1-chain</span>' | |
| ) | |
| return ( | |
| f'<div style="background:{BLACK_2};border:1px solid {HAIRLINE};' | |
| f'border-left:3px solid {GOLD};border-radius:10px;padding:20px 22px;">' | |
| f'<div style="display:flex;justify-content:space-between;align-items:center;' | |
| f'flex-wrap:wrap;gap:10px;margin-bottom:16px;">' | |
| f'<div style="color:{BONE};font-size:24px;font-weight:700;">{a["name"]}</div>' | |
| f'<div>{badge}</div></div>' | |
| f'<div style="display:grid;grid-template-columns:1fr 1fr;gap:4px 24px;">' | |
| f'{_field("handle", handle)}' | |
| f'{_field("burn", burn_txt)}' | |
| f'{_field("owner wallet", result["wallet"])}' | |
| f'{_field("nft mint", result["nft"]["mint"])}' | |
| f'{_field("pda", a["pda"])}' | |
| f'{_field("program", a["program"])}' | |
| f'</div>' | |
| f'<div style="color:{STONE};font-size:11px;letter-spacing:1.5px;' | |
| f'text-transform:uppercase;margin-top:6px;">description</div>' | |
| f'<div style="color:{BONE};font-size:14px;">{desc}</div>' | |
| f'</div>' | |
| ) | |
| # ---------------------------------------------------------------------------- | |
| # Gradio handlers | |
| # ---------------------------------------------------------------------------- | |
| def verify(wallet: str): | |
| """Verify an AI agent's on-chain identity on X1 mainnet. | |
| Args: | |
| wallet: the agent's 44-character base58 owner wallet address. | |
| """ | |
| try: | |
| w = validate_wallet(wallet) | |
| except ValueError as e: | |
| raise gr.Error(str(e)) | |
| try: | |
| result = verify_wallet_on_chain(w) | |
| except RuntimeError as e: | |
| raise gr.Error(str(e)) | |
| card = render_card(result) | |
| if result.get("verified"): | |
| report = build_compliance_report(result) | |
| return card, render_compliance_html(report), json.dumps(result, indent=2) | |
| return card, "", json.dumps(result, indent=2) | |
| def browse_all(): | |
| """List every agent registered on X1 mainnet (getProgramAccounts).""" | |
| try: | |
| agents = enumerate_agents() | |
| except RuntimeError as e: | |
| raise gr.Error(str(e)) | |
| rows = [] | |
| for a in agents: | |
| rows.append([ | |
| a["agent"]["name"], | |
| a["wallet"], | |
| a["agent"].get("handle") or "", | |
| a["nft"]["mint"], | |
| f'{a["burn_agi"]:g} AGI', | |
| ]) | |
| header = ( | |
| f'<div style="background:{BLACK_2};border:1px solid {HAIRLINE};' | |
| f'border-radius:10px;padding:16px 20px;margin-bottom:12px;">' | |
| f'<span style="color:{GOLD};font-size:20px;font-weight:700;">' | |
| f'{len(agents)}</span>' | |
| f'<span style="color:{BONE};font-size:14px;"> agents registered on X1 mainnet</span>' | |
| f'<span style="display:inline-block;margin-left:12px;background:{FORGE_BLACK};' | |
| f'border:1px solid {HAIRLINE};border-radius:6px;padding:3px 9px;' | |
| f'color:{STONE};font-size:11px;letter-spacing:1px;">source: x1-chain</span></div>' | |
| ) | |
| return rows, header | |
| # ---------------------------------------------------------------------------- | |
| # UI | |
| # ---------------------------------------------------------------------------- | |
| CSS = """ | |
| .gradio-container { background: #0A0908 !important; } | |
| #col-container { max-width: 1120px; margin: 0 auto; } | |
| footer { display: none !important; } | |
| .gr-button-primary { background: #D4A843 !important; color: #0A0908 !important; | |
| border: none !important; font-weight: 700 !important; } | |
| .gr-button-primary:hover { background: #E8C56D !important; } | |
| """ | |
| THEME = gr.themes.Base( | |
| primary_hue=gr.themes.colors.yellow, | |
| neutral_hue=gr.themes.colors.stone, | |
| ) | |
| EXAMPLES = [ | |
| ["G5ebmUSBrh7UrdANmuU45EjETS8Qe1hvoCAziQ4TuJn3"], # Coder | |
| ["5wNtysSW4VhntPCwK9jyppMz6UY9MtJSKgHp63LKYFq4"], # Lisa | |
| ["FKwU1im523MSGnuJG6YLHEZu4rUGj3xqxHJ6ipQMBG9B"], # Aster | |
| ["6wLjXrGR93c3RYYXBfLhKWSQdsBu5253RukeUgJnYaoB"], # valid pubkey, not registered | |
| ] | |
| with gr.Blocks( | |
| title="ProofChain Agent Verifier", | |
| ) as demo: | |
| with gr.Column(elem_id="col-container"): | |
| gr.HTML( | |
| f'<div style="padding:8px 0 18px;">' | |
| f'<div style="color:{GOLD};font-size:12px;letter-spacing:3px;' | |
| f'text-transform:uppercase;">ProofChain</div>' | |
| f'<div style="color:{BONE};font-size:28px;font-weight:700;margin-top:2px;">' | |
| f'Agent Verifier</div>' | |
| f'<div style="color:{STONE};font-size:14px;margin-top:6px;max-width:640px;">' | |
| f'Verify an AI agent\u2019s on-chain identity on <b style="color:{BONE};">X1</b>. ' | |
| f'Reads the AgentID v2 account straight off the chain. No middleman, no mock.' | |
| f'</div></div>' | |
| ) | |
| with gr.Tab("Verify agent"): | |
| with gr.Row(): | |
| wallet_in = gr.Textbox( | |
| label="Agent wallet", | |
| placeholder="44-char base58 wallet address", | |
| scale=4, | |
| ) | |
| verify_btn = gr.Button("Verify", variant="primary", scale=1) | |
| gr.Examples(examples=EXAMPLES, inputs=[wallet_in], | |
| label="Known wallets (click to load)") | |
| card_out = gr.HTML() | |
| compliance_out = gr.HTML() | |
| with gr.Accordion("Raw JSON response", open=False): | |
| raw_out = gr.Code(label=None, language="json") | |
| verify_btn.click( | |
| verify, | |
| inputs=[wallet_in], | |
| outputs=[card_out, compliance_out, raw_out], | |
| api_name="verify", | |
| ) | |
| with gr.Tab("Browse all agents"): | |
| gr.Markdown( | |
| "Every AgentID v2 account on X1 mainnet, read live with " | |
| "`getProgramAccounts` (dataSize 612)." | |
| ) | |
| browse_btn = gr.Button("Load agents", variant="primary") | |
| browse_header = gr.HTML() | |
| browse_table = gr.Dataframe( | |
| headers=["name", "wallet", "handle", "nft mint", "burn"], | |
| interactive=False, | |
| wrap=True, | |
| ) | |
| browse_btn.click( | |
| browse_all, | |
| inputs=[], | |
| outputs=[browse_table, browse_header], | |
| api_name="browse", | |
| ) | |
| gr.HTML( | |
| f'<div style="margin-top:26px;padding-top:14px;' | |
| f'border-top:1px solid {HAIRLINE};color:{STONE};font-size:12px;">' | |
| f'Chain queries go directly to ' | |
| f'<span style="color:{GOLD_MUTED};font-family:monospace;">{X1_RPC}</span> ' | |
| f'\u00b7 AgentID program ' | |
| f'<span style="color:{GOLD_MUTED};font-family:monospace;">' | |
| f'{AGENTID_PROGRAM[:12]}\u2026</span><br>' | |
| f'<a href="{PROOFCHAIN_URL}" target="_blank" ' | |
| f'style="color:{GOLD};text-decoration:none;">proofchain.us</a></div>' | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch(mcp_server=True, theme=THEME, css=CSS) | |