#!/usr/bin/env python3 """Full 2-step FLOP testnet agent claim (claim2). Usage: python3 claim2.py [--label ] [--room] [--resume ] The wallet label selects which wallet in the encrypted store to claim with; the address and DID are read from that wallet entry (never hardcoded). Default label flop-devnet-test-01. PRIMARY PATH — DIRECT (default): the challenge is SELF-CONSTRUCTED. The faucet's own web UI (faucet.flop.network, decoded 2026-11-25) builds the challenge itself — 'flop-faucet-agent/v1||
| ' — signs it with the wallet and POSTs {address, nonce, signature} (+ client:'faucet-web') to /v1/testnet/agent-claims. The Technocore bot room is only ONE way to get a challenge; the server verifies the signature itself. The bot's "5 requests per DID per 24h" limit does NOT apply to the direct path — it is the bot's own limit, not the faucet's. The faucet's own limits: 10 FLOP/24h/address, 86400s cooldown, nonce strictly higher than the last used for the address. Verified 2026-11-25: a direct POST reached the server (503 'Indexer unavailable; retry later' — signature accepted, backend transiently down), proving the path works. PROXY (2026-11-25 20:23 IST, user order; dedicated proxy from 20:35 IST): the proxy is used ONLY for the faucet claim POST to /v1/testnet/agent-claims — NOTHING ELSE. No balance checks (WS RPC stays direct), no Technocore room posts or reads (direct), no other site or service, ever. The proxy exists so the faucet sees the proxy's IP, not the VM's shared egress IP — the VM's IP hit the faucet's 24h per-IP cooldown ("This IP funded recently") on 2026-11-25 even though test-01 never got a grant. Credentials live in proxy.txt (0600) in this same hidden_files dir; if proxy.txt is absent the claim POST falls back to direct. FALLBACK PATH — BOT ROOM (--room): post a signed `!faucet request` in /r/flop-testnet-faucet, wait for the bot's challenge reply, sign it, POST privately. The room post alone pays NOTHING — there is no payout queue. Use only if the direct path is ever rejected. The user's own setup runs test-01 only (user decision 2026-11-24 19:13 IST). Wallets 02-10 HELD. Friends run their own wallet via --label. Never prints the mnemonic, private key, or the challenge signature (except sending it privately to the faucet over HTTPS in the claim POST). """ import argparse import base64 import json import os import re import subprocess import sys import time import urllib.request import urllib.error import http.client sys.path.insert(0, "/home/hatch/workspace/flop-wallet/.venv/lib/python3.12/site-packages") from substrateinterface import SubstrateInterface, Keypair, KeypairType # noqa: E402 from nacl.signing import SigningKey # noqa: E402 import base58 # noqa: E402 (in the venv on sys.path above) HOME = "/home/hatch" ENC = os.path.join(HOME, "workspace/flop-wallet/test-wallets/wallets.json.enc") PW = os.path.join(HOME, "workspace/flop-wallet/vault/wallet-password.txt") HF = os.path.join(HOME, "workspace/goals/flop-labs-testnet-agent-setup/hidden_files") PROXY_FILE = os.path.join(HF, "proxy.txt") # Wallet label / address / DID are resolved in main() from the encrypted # store by --label (default flop-devnet-test-01); nothing is hardcoded. LABEL = None ADDRESS = None DID = None ROOM = "flop-testnet-faucet" ROOM_URL = "https://technocore.chat/r/flop-testnet-faucet" CLAIM_URL = "https://faucet.flop.network/v1/testnet/agent-claims" BOT_DID = "did:key:z6MktjwdcBkwC6xo9wi4KY4ckWvn1GQHdQ1qzkaZtWqHAoxs" GENESIS = "0x918abd58fb16306b30ef3886514cfaebffecb4de43e82b6f8ec4795c43cfd800" UA = {"User-Agent": "Mozilla/5.0"} CHALLENGE_RE = re.compile(r'"(flop-faucet-agent/v1\|[^"]+)"') def load_proxy_opener(): """Build a urllib opener routing through the saved proxy (proxy.txt). The faucet's per-IP cooldown is keyed to the source IP, so claims go out via the user's proxy IP instead of the VM's shared egress IP. Returns None if no proxy file exists — calls then go direct. The password is read from the file (0600) and never printed. """ try: cfg = {} with open(PROXY_FILE) as f: for line in f: line = line.strip() if "=" in line: k, v = line.split("=", 1) cfg[k.strip()] = v.strip() proxy_url = (f"http://{cfg['username']}:{cfg['password']}" f"@{cfg['host']}:{cfg['port']}") except Exception as e: print(f"no proxy configured ({e}) — going direct") return None print(f"proxy configured: {cfg['host']}:{cfg['port']} (IP hidden)") return urllib.request.build_opener( urllib.request.ProxyHandler({"http": proxy_url, "https": proxy_url})) PROXY_OPENER = load_proxy_opener() # Set by --direct (main): force the claim POST direct, bypassing the # proxy even when proxy.txt exists. The 14:27 run uses this (user # decision 2026-11-26): the VM direct IP lifts ~12:22 IST, the proxy # IP not until ~20:38 IST, so a direct claim at 14:27 can land hours # before the proxy one. The 07:19 and 20:41 runs still use the proxy. FORCE_DIRECT = False def urlopen(req, timeout=60): """Open a URL, via the proxy when configured, else direct. --direct forces direct even when the proxy is configured.""" if PROXY_OPENER is not None and not FORCE_DIRECT: return PROXY_OPENER.open(req, timeout=timeout) return urllib.request.urlopen(req, timeout=timeout) def decrypt_wallets(): out = subprocess.run( ["openssl", "enc", "-d", "-aes-256-cbc", "-iter", "200000", "-in", ENC, "-pass", f"file:{PW}"], capture_output=True, check=True) return json.loads(out.stdout.decode()) def did_from_pubkey_hex(pubkey_hex): """did:key for an Ed25519 public key (multicodec 0xed01 + key). Verified: reproduces test-01's did:key exactly.""" return "did:key:z" + base58.b58encode( bytes([0xed, 0x01]) + bytes.fromhex(pubkey_hex)).decode() def b64url_nopad(b: bytes) -> str: return base64.urlsafe_b64encode(b).decode().rstrip("=") def http_get_json(url, tries=3): # Use curl: urllib hits IncompleteRead on the Technocore room JSON # (server closes the connection mid-response) and every poll failed # on 2026-11-25, so the script never saw the room. curl works. for i in range(tries): try: out = subprocess.run( ["curl", "-s", "-m", "30", "-A", "Mozilla/5.0", url], capture_output=True, check=True, timeout=40) return json.loads(out.stdout.decode()) except Exception as e: print(f"GET {url} failed ({e}), retry {i + 1}/{tries}") time.sleep(5) raise RuntimeError(f"GET {url} failed after {tries} tries") def http_post_json(url, payload, tries=3, use_proxy=False): """POST JSON. use_proxy=True ONLY for the faucet claim POST (CLAIM_URL) — the proxy is for faucet claims only, nothing else. Every other POST (e.g. the Technocore room post) goes direct.""" body = json.dumps(payload).encode() for i in range(tries): try: req = urllib.request.Request( url, data=body, headers={"Content-Type": "application/json", **UA}, method="POST") opener = urlopen if use_proxy else urllib.request.urlopen with opener(req, timeout=60) as r: raw = r.read().decode() print(f"POST {url} -> HTTP {r.status}: {raw[:400]}") return r.status, json.loads(raw) if raw else {} except urllib.error.HTTPError as e: raw = e.read().decode()[:400] print(f"POST {url} -> HTTP {e.code}: {raw}") if e.code in (400, 401, 403, 404, 422): return e.code, {"error": raw} time.sleep(10) except Exception as e: print(f"POST {url} failed ({e}), retry {i + 1}/{tries}") time.sleep(10) raise RuntimeError(f"POST {url} failed after {tries} tries") def direct_claim(kp): """Self-constructed challenge claim — no bot room needed. Build the challenge locally (same string the faucet web UI builds), sign it, POST privately. Retries on 502/503 honoring the server's retryAfterSeconds. Returns (ok, response, nonce, challenge). """ for attempt in range(1, 7): nonce = str(int(time.time() * 1000)) challenge = f"flop-faucet-agent/v1|{GENESIS}|{ADDRESS}|{nonce}" sig = SigningKey(kp.private_key).sign(challenge.encode("utf-8")).signature body = json.dumps({ "client": "faucet-web", "address": ADDRESS, "nonce": nonce, "signature": "0x" + sig.hex()}).encode() try: req = urllib.request.Request( CLAIM_URL, data=body, headers={"Content-Type": "application/json", **UA}, method="POST") with urlopen(req, timeout=60) as r: raw = r.read().decode() print(f"direct claim attempt {attempt} -> HTTP {r.status}: {raw[:300]}") return True, json.loads(raw) if raw else {}, nonce, challenge except urllib.error.HTTPError as e: raw = e.read().decode()[:400] print(f"direct claim attempt {attempt} -> HTTP {e.code}: {raw}") try: resp = json.loads(raw) except Exception: resp = {"error": raw} if e.code in (502, 503): wait = 60 try: wait = int(resp.get("retryAfterSeconds") or 60) except Exception: pass print(f"faucet busy ({resp.get('reason')}), retrying in {wait + 5}s") time.sleep(wait + 5) continue return False, resp, nonce, challenge except Exception as e: print(f"direct claim attempt {attempt} error: {e}") time.sleep(15) return False, {"error": "exhausted retries"}, None, None def check_balance(): """Return (block, free FLOP) for test-01, or (None, None).""" for i in range(1, 7): try: sub = SubstrateInterface(url="wss://testnet.flop.network") head = sub.get_chain_head() blk = sub.get_block_number(head) acc = sub.query("System", "Account", [ADDRESS], block_hash=head) f = acc["data"]["free"] val = getattr(f, "value", None) if val is None: val = int(str(f)) return blk, val / 10**18 except Exception as e: print(f"balance check attempt {i}: {str(e)[:100]}") time.sleep(30) return None, None def main(): global LABEL, ADDRESS, DID, FORCE_DIRECT ap = argparse.ArgumentParser(description="FLOP testnet agent faucet claim") ap.add_argument("--label", default="flop-devnet-test-01", help="wallet label in the encrypted store") ap.add_argument("--direct", action="store_true", help="force the claim POST direct, bypassing the proxy") ap.add_argument("--room", action="store_true", help="use the Technocore bot room (fallback); default is direct") ap.add_argument("--resume", default=None, help="resume a room claim with this nonce") args = ap.parse_args() FORCE_DIRECT = args.direct if FORCE_DIRECT: print("direct mode: claim POST goes direct, proxy bypassed") LABEL = args.label short = LABEL.split("-")[-1] resume_nonce = args.resume wallets = decrypt_wallets() w = next(x for x in wallets if x["label"] == LABEL) ADDRESS = w["address"] DID = did_from_pubkey_hex(w["public_key_hex"]) kp = Keypair.create_from_mnemonic( w["mnemonic"], ss58_format=42, crypto_type=KeypairType.ED25519) assert kp.ss58_address == ADDRESS, "derived address mismatch" assert kp.public_key.hex() == w["public_key_hex"], "pubkey mismatch" print("keypair verified: address + pubkey match stored values") # Pre-check: don't waste a challenge if already funded today. blk0, bal0 = check_balance() print(f"pre-claim balance: block {blk0}, {short} free = {bal0} FLOP") if bal0 is not None and bal0 >= 10: print("already funded (>= 10 FLOP) — skipping claim") return 0 # DIRECT PATH (default): self-constructed challenge, no bot room. # The bot room is only used with --room (fallback). if not args.room: ok, resp, nonce, challenge = direct_claim(kp) tx = resp.get("txHash") or resp.get("tx_hash") or resp.get("hash") print(f"direct claim success: {ok}, amount: {resp.get('amount')}, tx: {tx}") time.sleep(10) blk1, bal1 = check_balance() print(f"post-claim balance: block {blk1}, {short} free = {bal1} FLOP") rec = { "ts": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()), "label": LABEL, "did": DID, "address": ADDRESS, "method": "direct", "challenge": challenge, "claim_nonce": nonce, "claim_response": resp, "tx_hash": tx, "pre_balance": {"block": blk0, "free": bal0}, "post_balance": {"block": blk1, "free": bal1}, "funded": bool(bal1 is not None and bal1 >= 10), } with open(os.path.join(HF, "agent-claim-2026-11-25.json"), "w") as f: json.dump(rec, f, indent=2) print("record written:", os.path.join(HF, "agent-claim-2026-11-25.json")) return 0 if rec["funded"] else 3 # ROOM PATH (fallback, --room only) — Step 1: signed room request. # The room enforces strictly-increasing nonces per DID, and a POST # can succeed server-side while its response is lost (IncompleteRead). # So: on an ambiguous POST failure, check the room for our post # before retrying, and any retry uses a FRESH nonce + fresh signature. if resume_nonce: nonce = resume_nonce text = f"!faucet request {ADDRESS} {nonce}" print(f"resuming: step-1 post already in room, nonce {nonce}") else: nonce = None for attempt in range(3): nonce = str(int(time.time() * 1000)) text = f"!faucet request {ADDRESS} {nonce}" payload = f"{ROOM}|{nonce}|{text}".encode() sig = SigningKey(kp.private_key).sign(payload).signature sig_b64 = b64url_nopad(sig) assert len(sig_b64) == 86, f"sig length {len(sig_b64)}" try: # tries=1: main() controls retries (fresh nonce + room check), # because an internal same-nonce retry would hit the # strictly-increasing-nonce rule if the first POST landed. status, _ = http_post_json( ROOM_URL, {"did": DID, "sig": sig_b64, "nonce": nonce, "text": text}, tries=1) print(f"step 1 room post -> HTTP {status}, nonce {nonce}") if status == 200: break print(f"step 1 room post rejected (HTTP {status}); retrying with fresh nonce") except Exception as e: print(f"step 1 POST ambiguous ({e}) — checking room for our post") try: data = http_get_json(ROOM_URL + "?format=json&limit=50") msgs = data.get("messages") or data.get("records") or [] if any(m.get("text") == text for m in msgs): print("post IS in the room (response was lost) — proceeding") break except Exception as e2: print(f"room check failed: {e2}") print("post not found — retrying with fresh nonce") time.sleep(2) else: print("step 1 FAILED: room post not accepted after 3 attempts") return 1 # Step 2: wait for the bot's challenge reply for our address. challenge = None deadline = time.time() + 300 while time.time() < deadline: time.sleep(5) try: data = http_get_json(ROOM_URL + "?format=json&limit=50") except Exception as e: print(f"room poll failed: {e}") continue msgs = data.get("messages") or data.get("records") or [] for m in msgs: if m.get("from") != BOT_DID: continue t = m.get("text", "") if "Daily limit reached" in t or "limit reached" in t.lower(): print(f"bot rate-limit reply (seq {m.get('seq')}): {t[:200]}") print("step 2 FAILED: daily challenge limit reached") return 2 if ADDRESS not in t: continue mm = CHALLENGE_RE.search(t) if mm: challenge = mm.group(1) print(f"step 2 challenge found (seq {m.get('seq')}): {challenge}") break if challenge: break if not challenge: print("step 2 FAILED: no bot challenge reply in 5 minutes") return 2 # Step 3: sign the exact challenge bytes, POST privately. parts = challenge.split("|") assert len(parts) == 4 and parts[0] == "flop-faucet-agent/v1", "bad challenge" assert parts[2] == ADDRESS, f"challenge address mismatch: {parts[2]}" claim_nonce = parts[3] csig = SigningKey(kp.private_key).sign(challenge.encode("utf-8")).signature csig_hex = "0x" + csig.hex() print(f"step 3 signing challenge (nonce {claim_nonce}) — signature kept private") status, resp = http_post_json(CLAIM_URL, { "address": ADDRESS, "nonce": claim_nonce, "signature": csig_hex}, use_proxy=True) print(f"step 3 claim POST -> HTTP {status}: {json.dumps(resp)[:400]}") ok = resp.get("success") is True and resp.get("amount") == 10 tx = resp.get("txHash") or resp.get("tx_hash") or resp.get("hash") print(f"claim success: {ok}, amount: {resp.get('amount')}, tx: {tx}") # Step 4: verify balance on-chain. time.sleep(10) blk1, bal1 = check_balance() print(f"post-claim balance: block {blk1}, {short} free = {bal1} FLOP") rec = { "ts": time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime()), "label": LABEL, "did": DID, "address": ADDRESS, "room_nonce": nonce, "challenge": challenge, "claim_nonce": claim_nonce, "claim_http": status, "claim_response": resp, "tx_hash": tx, "pre_balance": {"block": blk0, "free": bal0}, "post_balance": {"block": blk1, "free": bal1}, "funded": bool(bal1 is not None and bal1 >= 10), } with open(os.path.join(HF, "agent-claim-2026-11-25.json"), "w") as f: json.dump(rec, f, indent=2) print("record written:", os.path.join(HF, "agent-claim-2026-11-25.json")) return 0 if rec["funded"] else 3 if __name__ == "__main__": raise SystemExit(main())