#!/usr/bin/env python3 """ agent-pay-rail — give any AI agent an identity and an income, in one file. No bank account. No ID. No KYC. No signup. No human in the loop. python rail.py key # generate an identity (npub/nsec) python rail.py post "hello nostr" # sign + broadcast to public relays python rail.py read # fetch an event back, like a stranger would python rail.py wallet # create a Lightning wallet + address python rail.py invoice 1000 # mint a real BOLT11 invoice (sats) python rail.py balance # check what you've been paid Requirements: pip install coincurve websocket-client requests The three layers: 1. IDENTITY secp256k1 keypair -> npub. Signs NIP-01 events yourself. 2. TRANSPORT raw websocket to public relays. No API key, no approval. 3. MONEY LNbits public instance -> Lightning address -> BOLT11 invoices. Everything here was verified end to end before it was written down. MIT licensed. Take it. """ from __future__ import annotations import hashlib import json import sys import time import uuid from pathlib import Path # ------------------------------------------------------------------ deps try: import requests import websocket from coincurve import PrivateKey as _Secp except ImportError: sys.exit("pip install coincurve websocket-client requests") STATE = Path.home() / ".agent-pay-rail.json" DEFAULT_RELAYS = [ "wss://nos.lol", "wss://relay.primal.net", "wss://relay.nostr.band", "wss://relay.damus.io", ] LNBITS_HOSTS = ["https://demo.lnbits.com", "https://legend.lnbits.com"] # ------------------------------------------------------------------ bech32 _CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" def _polymod(values): gen = [0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3] chk = 1 for v in values: b = chk >> 25 chk = (chk & 0x1FFFFFF) << 5 ^ v for i in range(5): chk ^= gen[i] if ((b >> i) & 1) else 0 return chk def _hrp_expand(hrp): return [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp] def _convertbits(data, frombits, tobits, pad=True): acc = bits = 0 ret = [] maxv = (1 << tobits) - 1 for value in data: acc = (acc << frombits) | value bits += frombits while bits >= tobits: bits -= tobits ret.append((acc >> bits) & maxv) if pad and bits: ret.append((acc << (tobits - bits)) & maxv) return ret def bech32(hrp, data): values = _hrp_expand(hrp) + data p = _polymod(values + [0] * 6) ^ 1 chk = [(p >> 5 * (5 - i)) & 31 for i in range(6)] return hrp + "1" + "".join(_CHARSET[d] for d in data + chk) # ------------------------------------------------------------------ identity class Identity: def __init__(self, priv_hex=None): self.sk = _Secp(bytes.fromhex(priv_hex)) if priv_hex else _Secp() self.priv = self.sk.secret.hex() self.pub = self.sk.public_key.format(compressed=True)[1:].hex() @property def npub(self): return bech32("npub", _convertbits(bytes.fromhex(self.pub), 8, 5)) @property def nsec(self): return bech32("nsec", _convertbits(bytes.fromhex(self.priv), 8, 5)) def event(self, kind, content, tags=None): ev = {"pubkey": self.pub, "created_at": int(time.time()), "kind": kind, "tags": tags or [], "content": content} ser = json.dumps([0, ev["pubkey"], ev["created_at"], ev["kind"], ev["tags"], ev["content"]], ensure_ascii=False, separators=(",", ":")) ev["id"] = hashlib.sha256(ser.encode()).hexdigest() ev["sig"] = self.sk.sign_schnorr(bytes.fromhex(ev["id"]), aux_randomness=b"").hex() return ev # ------------------------------------------------------------------ transport def _proxy(): """Read the Windows system proxy. On Linux/macOS set HTTP(S)_PROXY yourself.""" try: import winreg k = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Internet Settings") if not winreg.QueryValueEx(k, "ProxyEnable")[0]: return None server = winreg.QueryValueEx(k, "ProxyServer")[0] if "=" in server: parts = dict(p.split("=", 1) for p in server.split(";") if "=" in p) server = parts.get("https") or parts.get("http") or server host, _, port = server.partition(":") return host, int(port or 8080) except Exception: return None def _conn(url, timeout=8): kw = {"timeout": timeout, "enable_multithread": False} p = _proxy() if p: kw.update(http_proxy_host=p[0], http_proxy_port=p[1], proxy_type="http", http_proxy_timeout=timeout) return websocket.create_connection(url, **kw) def post(ev, relays=None, wait=8.0): """Broadcast an event. Returns {relay: 'accepted'|'rejected: ...'|'unreachable'}.""" relays = relays or DEFAULT_RELAYS out = {} msg = json.dumps(["EVENT", ev], ensure_ascii=False) for url in relays: try: ws = _conn(url) ws.send(msg) ws.settimeout(wait) deadline, result = time.time() + wait, "sent, no ack" while time.time() < deadline: try: raw = ws.recv() except Exception: break if not raw: break try: m = json.loads(raw) except json.JSONDecodeError: continue if isinstance(m, list) and m[:2] == ["OK", ev["id"]]: result = "accepted" if (len(m) > 2 and m[2]) else f"rejected: {m[3] if len(m) > 3 else ''}" break if isinstance(m, list) and m and m[0] == "NOTICE": result = f"notice: {m[1]}" break ws.close() out[url] = result except Exception as e: out[url] = f"unreachable: {type(e).__name__}" return out def read(event_id, relays=None, wait=7.0): """Fetch an event the way a stranger would.""" relays = relays or DEFAULT_RELAYS sub = uuid.uuid4().hex[:8] for url in relays: try: ws = _conn(url) except Exception: continue ws.send(json.dumps(["REQ", sub, {"ids": [event_id]}])) ws.settimeout(3) deadline = time.time() + wait found = None while time.time() < deadline: try: raw = ws.recv() except Exception: continue if not raw: break try: m = json.loads(raw) except json.JSONDecodeError: continue if isinstance(m, list) and m and m[0] == "EVENT" and m[2].get("id") == event_id: found = m[2] break if isinstance(m, list) and m and m[0] == "EOSE": break try: ws.send(json.dumps(["CLOSE", sub])) ws.close() except Exception: pass if found: return found return None # ------------------------------------------------------------------ money class Wallet: """A custodial Lightning wallet on a public LNbits instance. The admin key can spend. Treat it like a password. """ def __init__(self, host, wallet_id, adminkey, address): self.host, self.id, self.key, self.address = host, wallet_id, adminkey, address def _api(self, path, **kw): h = {"X-Api-Key": self.key, "User-Agent": "agent-pay-rail/1.0"} return requests.request(kw.pop("method", "GET"), f"{self.host}{path}", headers=h, timeout=30, **kw) def invoice(self, sats, memo="payment"): r = self._api("/api/v1/payments", method="POST", json={"out": False, "amount": sats, "memo": memo}) r.raise_for_status() return r.json()["payment_request"] def balance(self): r = self._api("/api/v1/wallet") r.raise_for_status() return r.json()["balance"] / 1000.0 # sats def new_wallet(name="agent"): """One POST on a public LNbits instance. No email, no KYC.""" last = None for host in LNBITS_HOSTS: try: r = requests.post(f"{host}/api/v1/account", json={"name": name}, headers={"User-Agent": "agent-pay-rail/1.0"}, timeout=30) if r.status_code != 200: last = f"{host} -> {r.status_code}" continue d = r.json() addr = f"{d['lightning_address']}@{host.split('//')[1]}" return Wallet(host, d["id"], d["adminkey"], addr) except Exception as e: last = f"{host} -> {type(e).__name__}" raise RuntimeError(f"no LNbits host worked: {last}") # ------------------------------------------------------------------ state def load(): return json.loads(STATE.read_text()) if STATE.exists() else {} def save(d): STATE.write_text(json.dumps(d, indent=1)) try: STATE.chmod(0o600) except Exception: pass # ------------------------------------------------------------------ cli def main(argv): cmd = argv[1] if len(argv) > 1 else "help" st = load() if cmd == "key": if st.get("priv"): i = Identity(st["priv"]) print("existing identity") else: i = Identity() st["priv"] = i.priv save(st) print("new identity") print("npub:", i.npub) print("nsec:", i.nsec, " <- keep secret, it is the account") return 0 if cmd == "post": if not st.get("priv"): return print("run: rail.py key") or 1 i = Identity(st["priv"]) text = " ".join(argv[2:]) or "hello from an agent" ev = i.event(1, text, [["t", "ai"]]) for url, res in post(ev).items(): print(f" {'OK ' if res == 'accepted' else '-- '}{url:<30} {res}") print("\nevent:", ev["id"]) print("view :", f"https://njump.me/{ev['id']}") return 0 if cmd == "read": if len(argv) < 3: return print("usage: rail.py read ") or 1 ev = read(argv[2]) if not ev: print("not found on any relay") return 2 print(json.dumps(ev, indent=1, ensure_ascii=False)[:1500]) return 0 if cmd == "wallet": if st.get("wallet"): print("existing wallet:", st["wallet"]["address"]) return 0 w = new_wallet() st["wallet"] = {"host": w.host, "id": w.id, "key": w.key, "address": w.address} save(st) print("lightning address:", w.address) print("admin key stored in", STATE, "- it can spend, never publish it") return 0 if cmd in ("invoice", "balance"): if not st.get("wallet"): return print("run: rail.py wallet") or 1 w = Wallet(**{"host": st["wallet"]["host"], "wallet_id": st["wallet"]["id"], "adminkey": st["wallet"]["key"], "address": st["wallet"]["address"]}) if cmd == "invoice": sats = int(argv[2]) if len(argv) > 2 else 1000 print(w.invoice(sats)) else: print(f"{w.balance():.0f} sats") return 0 print(__doc__) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))