"""Sync coarena keys from keys_bank.jsonl into the rotator pool, verify, report. Usage: python coa_pool_sync.py # sync + verify whole pool python coa_pool_sync.py --restart # also restart the rotator (single instance) python coa_pool_sync.py --home D:/coa # override working dir Why a script and not hand-editing: coa_keys.txt is read ONCE at rotator start, so new keys need a restart, and hand-appending breaks the `name|coa_…` line format or the `coarena-%03d` numbering — load_keys() then silently drops the key. Exit codes: 0 = ok, 1 = nothing alive / pool file missing. """ import json import os import re import subprocess import sys import time from concurrent.futures import ThreadPoolExecutor import requests HOME = os.environ.get("COA_HOME", "C:/Users/User/tmp/coarena") BANK = os.path.join(HOME, "keys_bank.jsonl") KEYSF = os.path.join(HOME, "coa_keys.txt") ALIVEF = os.path.join(HOME, "coa_keys_alive.txt") LIMITS = "https://coarena.ai/api/v1/limits" ROT = os.path.join(HOME, "coa_rot3.py") ROT_PORT = int(os.environ.get("COA_ROT_PORT", "16446")) PY = os.environ.get("COA_PY", r"C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe") KEY_RE = re.compile(r"^coa_[A-Za-z0-9]{20,}$") def read_bank(path): """Tolerant read: a live wave appends to this file and the tail line is often torn.""" out = [] if not os.path.exists(path): return out for line in open(path, encoding="utf8", errors="replace"): line = line.strip() if not line: continue try: d = json.loads(line) except Exception: continue k = (d.get("key") or "").strip() if KEY_RE.match(k): out.append(k) return out def read_pool(path): lines, keys = [], set() if os.path.exists(path): for line in open(path, encoding="utf8", errors="replace"): line = line.rstrip("\n") if "|" not in line: continue k = line.split("|", 1)[1].strip() if not KEY_RE.match(k): continue lines.append(line) keys.add(k) return lines, keys def verify(keys): def one(k): for _ in range(2): try: r = requests.get(LIMITS, headers={"Authorization": "Bearer " + k}, timeout=25) if r.status_code == 200: return k, 200 if r.status_code == 401: return k, 401 except Exception: pass time.sleep(2) return k, 0 alive = [] with ThreadPoolExecutor(8) as ex: for k, st in ex.map(one, keys): if st == 200: alive.append(k) return alive def rotator_pids(): """Marker is assembled at runtime so this script never matches its own cmdline.""" marker = "coa_" + "rot3" pids = [] try: import psutil except ImportError: return pids for p in psutil.process_iter(["pid", "cmdline"]): cmd = " ".join(p.info.get("cmdline") or []) if marker in cmd and p.info["pid"] != os.getpid(): pids.append(p.info["pid"]) return pids def listener_pid(): try: import psutil except ImportError: return None for c in psutil.net_connections("tcp"): if c.laddr and c.laddr.port == ROT_PORT and c.status == "LISTEN": return c.pid return None def restart_rotator(): for pid in rotator_pids(): try: import psutil psutil.Process(pid).kill() print("killed rotator", pid, flush=True) except Exception: pass time.sleep(2) env = dict(os.environ) env.pop("PYTHONPATH", None) env["PYTHONIOENCODING"] = "utf-8" env["COA_ROT_PORT"] = str(ROT_PORT) logf = open(os.path.join(HOME, "rot3.log"), "a") DETACHED = 0x00000008 | 0x00000200 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP p = subprocess.Popen([PY, "-u", "coa_rot3.py"], cwd=HOME, env=env, creationflags=DETACHED, stdout=logf, stderr=subprocess.STDOUT, close_fds=False) print("started rotator", p.pid, flush=True) for _ in range(20): time.sleep(2) if listener_pid() == p.pid: print("listening on", ROT_PORT, flush=True) return True print("WARN: port", ROT_PORT, "not bound by", p.pid, "(listener:", listener_pid(), ")", flush=True) return False def main(): home = None if "--home" in sys.argv: home = sys.argv[sys.argv.index("--home") + 1] base = home or HOME bank = os.path.join(base, "keys_bank.jsonl") keysf = os.path.join(base, "coa_keys.txt") bank_keys = list(dict.fromkeys(read_bank(bank))) lines, have = read_pool(keysf) new = [k for k in bank_keys if k not in have] with open(keysf, "a", encoding="utf8") as f: n = len(lines) for k in new: n += 1 f.write("coarena-%03d|%s\n" % (n, k)) print("bank=%d pool_before=%d added=%d pool_after=%d" % (len(bank_keys), len(have), len(new), len(have) + len(new)), flush=True) all_keys = list(dict.fromkeys(read_pool(keysf)[1])) if not all_keys: print("FAIL: pool empty", flush=True) return 1 alive = verify(all_keys) with open(os.path.join(base, "coa_keys_alive.txt"), "w", encoding="utf8") as f: f.write("\n".join(alive)) print("alive=%d/%d" % (len(alive), len(all_keys)), flush=True) if "--restart" in sys.argv: restart_rotator() return 0 if alive else 1 if __name__ == "__main__": sys.exit(main())