"""BitAddy payment alerts: "tell me when this address receives a payment", by Telegram, Discord or a webhook. $10 a year per address. No accounts: an alert is managed with its own private alert link (bitaddy.com/alerts/#al-...), stored here only as a scrambled fingerprint. A test alert is free, so delivery can be checked before paying. Once paid, the address is looked at every few minutes (its coin and the USDT/USDC on the same chain), and each confirmed incoming payment is announced once. Telegram: people tap "Connect Telegram", which opens the bot with a one-time code; the bot's webhook tells us their chat. The bot token lives in /telegram.json (never in the code). Webhooks only ever go to the public internet. """ import hashlib, hmac, http.client, ipaddress, json, re, secrets, socket, ssl, threading, time, urllib.parse from datetime import datetime, timedelta, timezone from pathlib import Path B = None # the bitaddy module S = None # the core console module SCHEMA = """ CREATE TABLE IF NOT EXISTS ba_alerts(id INTEGER PRIMARY KEY, token TEXT UNIQUE NOT NULL, coin TEXT NOT NULL, address TEXT NOT NULL, label TEXT, channel TEXT NOT NULL, target TEXT, tg_code TEXT, secret TEXT, heights TEXT NOT NULL DEFAULT '{}', created INTEGER NOT NULL, sent INTEGER NOT NULL DEFAULT 0, last_sent INTEGER, fails INTEGER NOT NULL DEFAULT 0, last_error TEXT, reminded INTEGER NOT NULL DEFAULT 0, ended_note INTEGER NOT NULL DEFAULT 0); CREATE TABLE IF NOT EXISTS ba_alert_seen(alert_id INTEGER NOT NULL, uid TEXT NOT NULL, ts INTEGER NOT NULL, PRIMARY KEY(alert_id, uid)); CREATE TABLE IF NOT EXISTS ba_alert_log(id INTEGER PRIMARY KEY, alert_id INTEGER NOT NULL, ts INTEGER NOT NULL, kind TEXT NOT NULL, ok INTEGER NOT NULL, detail TEXT); """ CHANNELS = ("telegram", "discord", "webhook") DISCORD_RE = re.compile(r"^https://(?:discord\.com|discordapp\.com|ptb\.discord\.com|canary\.discord\.com)/api/webhooks/\d{5,30}/[A-Za-z0-9_\-]{20,120}$") TOKEN_RE = re.compile(r"^al-[A-Za-z0-9_\-]{20,40}$") GAP = {"BTC": 300, "LTC": 300, "DOGE": 600, "ADA": 240, "ETH": 240, "SOL": 180, "XRP": 180, "TRX": 240} # seconds between looks at one address REMIND_DAYS = 14 LOOK = {} # (asset, address) -> last look LOCK = threading.Lock() TICK = {"last": 0} def init(bitaddy_module, core): global B, S B, S = bitaddy_module, core def now(): return int(time.time()) def site(): return (S.CFG.get("SITE_ORIGIN") or "https://" + S.CFG["SITE_DOMAIN"]).rstrip("/") def day(ts): return datetime.fromtimestamp(int(ts), timezone.utc).strftime("%-d %b %Y") # ------------------------------------------------------------------ Telegram settings (bot token kept outside the code) def tg(): """-> {"token", "username", "hook_secret", "path_secret", "api"} or None when Telegram isn't set up.""" try: c = json.loads((Path(S.CFG["DATA_DIR"]) / "telegram.json").read_text()) except Exception: return None if not c.get("token") or not c.get("username"): return None c.setdefault("api", "https://api.telegram.org") if not S.CFG.get("DEV"): c["api"] = "https://api.telegram.org" # a test address can only be used on a test copy return c def tg_call(method, body): c = tg() if not c: raise RuntimeError("Telegram isn't set up") st, j = S.http_json("POST", "%s/bot%s/%s" % (c["api"], c["token"], method), body=body, timeout=15) if st != 200 or not (j or {}).get("ok"): desc = (j or {}).get("description") if isinstance(j, dict) else None raise RuntimeError("Telegram said: %s" % (desc or st)) return j.get("result") # ------------------------------------------------------------------ sending to the public internet only def public_ip(ip): a = ipaddress.ip_address(ip) return not (a.is_private or a.is_loopback or a.is_link_local or a.is_multicast or a.is_reserved or a.is_unspecified or (a.version == 6 and a.ipv4_mapped and not public_ip(str(a.ipv4_mapped)))) def check_url(url, discord=False): """A delivery address people may give: https on the public internet (Discord: its own webhook addresses). -> cleaned url.""" u = str(url or "").strip() if len(u) > 500: raise ValueError("That address is too long.") if discord: if not DISCORD_RE.match(u): raise ValueError("That isn't a Discord webhook address. In Discord: channel settings, Integrations, Webhooks, Copy Webhook URL.") return u p = urllib.parse.urlsplit(u) dev_local = S.CFG.get("DEV") and p.scheme == "http" and p.hostname == "127.0.0.1" if p.scheme != "https" and not dev_local: raise ValueError("The webhook address must start with https://") if not p.hostname or p.username or p.password: raise ValueError("That webhook address isn't valid.") if not dev_local: if (p.port or 443) != 443: raise ValueError("Webhooks are sent to the normal https port (443) only.") try: ipaddress.ip_address(p.hostname) raise ValueError("Use a name (like hooks.example.com), not a bare IP address.") except ValueError as e: if "Use a name" in str(e): raise return u def post_json(url, body, headers=None, timeout=10): """POST JSON to a public https address. The name is looked up once, every address it gives must be public, and the connection goes to that checked address (so a name can't be switched to a private one in between). No redirects are followed.""" p = urllib.parse.urlsplit(url) raw = json.dumps(body, ensure_ascii=False).encode() hd = {"Content-Type": "application/json", "User-Agent": "BitAddy-Alerts/1.0 (+https://bitaddy.com/alerts/)", "Content-Length": str(len(raw))} hd.update(headers or {}) path = (p.path or "/") + ("?" + p.query if p.query else "") if S.CFG.get("DEV") and p.scheme == "http" and p.hostname == "127.0.0.1": conn = http.client.HTTPConnection("127.0.0.1", p.port or 80, timeout=timeout) else: infos = socket.getaddrinfo(p.hostname, 443, proto=socket.IPPROTO_TCP) ips = sorted({i[4][0] for i in infos}) if not ips or not all(public_ip(ip) for ip in ips): raise RuntimeError("that address doesn't lead to the public internet") conn = http.client.HTTPSConnection(p.hostname, 443, timeout=timeout, context=ssl.create_default_context()) sock = socket.create_connection((ips[0], 443), timeout=timeout) conn.sock = conn._context.wrap_socket(sock, server_hostname=p.hostname) try: conn.request("POST", path, body=raw, headers=hd) r = conn.getresponse() r.read(2000) if not (200 <= r.status < 300): raise RuntimeError("it answered %s" % r.status) return r.status finally: conn.close() # ------------------------------------------------------------------ messages def assets_for(coin): return [a for a, x in B.pay.ASSETS.items() if x["chain"] == coin] def who(a): return (a["label"] + " ยท " if a["label"] else "") + "%s address ending %s" % (B.coin_name(a["coin"]), a["address"][-6:]) def deliver(a, text, data): """Sends one message on the alert's channel. -> None, or raises with a plain reason.""" if not a["target"]: raise RuntimeError("not connected yet" if a["channel"] == "telegram" else "no delivery address") if a["channel"] == "telegram": tg_call("sendMessage", {"chat_id": int(a["target"]), "text": text, "disable_web_page_preview": True}) elif a["channel"] == "discord": post_json(a["target"], {"content": text[:1900], "username": "BitAddy Alerts", "allowed_mentions": {"parse": []}}) else: body = dict(data, alert=a["id"], sent_at=datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")) raw = json.dumps(body, ensure_ascii=False).encode() sig = hmac.new(a["secret"].encode(), raw, hashlib.sha256).hexdigest() post_json(a["target"], body, {"X-BitAddy-Event": data["event"], "X-BitAddy-Signature": "sha256=" + sig}) def send(a, kind, text, data): ok, err = True, "" try: deliver(a, text, data) except Exception as e: ok, err = False, str(e)[:160] with B.db() as c: c.execute("INSERT INTO ba_alert_log(alert_id,ts,kind,ok,detail) VALUES(?,?,?,?,?)", (a["id"], now(), kind, 1 if ok else 0, err or text[:160])) if ok: c.execute("UPDATE ba_alerts SET sent=sent+1, last_sent=?, fails=0, last_error=NULL WHERE id=?", (now(), a["id"])) else: c.execute("UPDATE ba_alerts SET fails=fails+1, last_error=? WHERE id=?", (err, a["id"])) return ok, err def payment_text(a, asset, t): amt = B.pay.fmt_amount(t["amount"], asset) link = B.pay.explorer(asset, t["tx"]) or "" return ("๐Ÿ’ธ Payment received: %s %s\nTo: %s\n%s" % (amt, B.pay.symbol(asset), who(a), link)).strip(), { "event": "payment", "coin": a["coin"], "asset": asset, "symbol": B.pay.symbol(asset), "amount": amt, "address": a["address"], "label": a["label"] or "", "transaction": t["tx"], "transaction_page": link or None} # ------------------------------------------------------------------ the watcher (called from the console's half-minute tick) def active_rows(): with B.db() as c: rows = [dict(r) for r in c.execute("SELECT * FROM ba_alerts WHERE target IS NOT NULL AND target!=''")] return [r for r in rows if B.has_perk(c, "alert", str(r["id"]), "alert")] def baseline(alert_id, coin, address): """Marks everything already in the address as seen, so only NEW payments are announced. -> start heights per asset.""" heights, uids = {}, set() for asset in assets_for(coin): heights[asset] = B.pay.start_height(asset) try: uids |= set(B.pay.known(asset, address)) # and whatever the watcher itself would read, so nothing already there can ever look new to it uids |= {t["uid"] for t in B.pay.incoming(asset, address, heights[asset], set(uids))} except Exception: raise ValueError("%s payments can't be checked right now. Please try again in a few minutes." % B.coin_name(coin)) with B.db() as c: for u in uids: c.execute("INSERT OR IGNORE INTO ba_alert_seen(alert_id,uid,ts) VALUES(?,?,?)", (alert_id, u, now())) c.execute("UPDATE ba_alerts SET heights=? WHERE id=?", (json.dumps(heights), alert_id)) return heights def check_all(force=False): if not LOCK.acquire(False): return try: rows = active_rows() by = {} for a in rows: for asset in assets_for(a["coin"]): by.setdefault((asset, a["address"]), []).append(a) for (asset, address), alist in by.items(): gap = max(GAP.get(B.pay.ASSETS[asset]["chain"], 300), B.pay.MIN_GAP.get(asset, 0)) if not force and time.time() - LOOK.get((asset, address), 0) < gap: continue LOOK[(asset, address)] = time.time() since = min((json.loads(a["heights"] or "{}").get(asset) or 0) for a in alist) with B.db() as c: seen = {} for a in alist: seen[a["id"]] = {r["uid"] for r in c.execute("SELECT uid FROM ba_alert_seen WHERE alert_id=?", (a["id"],))} try: txs = B.pay.incoming(asset, address, since, set.intersection(*seen.values()) if seen else set()) except Exception: continue for t in txs: if not t.get("confirmed"): continue # announced once it is confirmed, never twice for a in alist: if t["uid"] in seen[a["id"]]: continue with B.db() as c: fresh = c.execute("INSERT OR IGNORE INTO ba_alert_seen(alert_id,uid,ts) VALUES(?,?,?)", (a["id"], t["uid"], now())).rowcount if fresh: text, data = payment_text(a, asset, t) send(a, "payment", text, data) finally: LOCK.release() def tick(): if time.time() - TICK["last"] < 25: return TICK["last"] = time.time() threading.Thread(target=check_all, daemon=True).start() def daily(): """Reminders before an alert's year ends (BitAddy has no other way to reach people), a note when it ends, and clean-up.""" with B.db() as c: rows = [dict(r) for r in c.execute("SELECT * FROM ba_alerts WHERE target IS NOT NULL AND target!=''")] ends = {r["id"]: B.perk_until(c, "alert", str(r["id"]), "alert") for r in rows} for a in rows: u = ends.get(a["id"]) if not u: continue if now() < u <= now() + REMIND_DAYS * 86400 and not a["reminded"]: send(a, "reminder", "โฐ Your BitAddy payment alert for %s ends on %s. Renew it from your alert link to keep getting alerts " "(%s/alerts/)." % (who(a), day(u), site()), {"event": "ending_soon", "ends": day(u), "address": a["address"]}) with B.db() as c: c.execute("UPDATE ba_alerts SET reminded=1 WHERE id=?", (a["id"],)) elif u <= now() and not a["ended_note"]: send(a, "ended", "Your BitAddy payment alert for %s has ended. Renew it from your alert link (%s/alerts/)." % (who(a), site()), {"event": "ended", "address": a["address"]}) with B.db() as c: c.execute("UPDATE ba_alerts SET ended_note=1 WHERE id=?", (a["id"],)) with B.db() as c: # never paid: gone after 7 days; ended: gone 90 days after the end for r in c.execute("SELECT id FROM ba_alerts").fetchall(): u = B.perk_until(c, "alert", str(r["id"]), "alert") created = c.execute("SELECT created FROM ba_alerts WHERE id=?", (r["id"],)).fetchone()["created"] if (u is None and created < now() - 7 * 86400) or (u and u < now() - 90 * 86400): drop(c, r["id"]) c.execute("DELETE FROM ba_alert_log WHERE ts now())), "ended": bool(until and until <= now()), "sent": a["sent"], "last_sent": a["last_sent"], "fails": a["fails"], "last_error": a["last_error"], "log": log, "watches": [B.pay.symbol(x) for x in assets_for(a["coin"])]} if a["channel"] == "telegram" and not a["target"] and t and a["tg_code"]: d["telegram_link"] = "https://t.me/%s?start=%s" % (t["username"], a["tg_code"]) if token: d["token"] = token d["manage_url"] = "%s/alerts/#%s" % (site(), token) return d def p_new(h, q): B.limit(h, "alert_new", 20) b = B.jbody(h) addr_in = str(b.get("address") or "").strip() coin = str(b.get("coin") or "").upper() if not coin: d = B.coins.detect(addr_in) if len(d) != 1: raise ValueError("Pick which coin this address is for." if d else "That doesn't look like a crypto address we know.") coin = d[0] addr, why = B.coins.check(coin, addr_in) if not addr: raise ValueError(why) ch = str(b.get("channel") or "").lower() if ch not in CHANNELS: raise ValueError("Choose how to be told: Telegram, Discord or a webhook.") target, code, secret = None, None, None if ch == "telegram": if not tg(): raise ValueError("Telegram alerts aren't switched on yet. Please choose Discord or a webhook.") code = secrets.token_urlsafe(12).replace("-", "x").replace("_", "y") elif ch == "discord": target = check_url(b.get("url"), discord=True) else: target = check_url(b.get("url")) secret = "whsec_" + secrets.token_urlsafe(24) token = "al-" + secrets.token_urlsafe(18) label = B.clean_text(" ".join(str(b.get("label") or "").split()), 40) with B.db() as c: cur = c.execute("INSERT INTO ba_alerts(token,coin,address,label,channel,target,tg_code,secret,created) VALUES(?,?,?,?,?,?,?,?,?)", (S.tok_hash(token), coin, addr, label, ch, target, code, secret, now())) aid = cur.lastrowid try: baseline(aid, coin, addr) except ValueError: with B.db() as c: drop(c, aid) raise S.audit("visitor", "BitAddy alert made", "%s ending %s, %s" % (coin, addr[-6:], ch)) with B.db() as c: return h.send(200, public_view(c, find(c, token), token)) def p_get(h, q): b = B.jbody(h) with B.db() as c: a = find(c, b.get("token")) if not a: raise ValueError("That alert link isn't known. Check that you pasted all of it.") return h.send(200, public_view(c, a)) def p_update(h, q): """Change the label or the delivery (a new Telegram code, Discord or webhook address).""" B.limit(h, "alert_upd", 30) b = B.jbody(h) with B.db() as c: a = find(c, b.get("token")) if not a: raise ValueError("That alert link isn't known.") sets = {} if "label" in b: sets["label"] = B.clean_text(" ".join(str(b.get("label") or "").split()), 40) if "channel" in b: ch = str(b.get("channel") or "").lower() if ch not in CHANNELS: raise ValueError("Choose Telegram, Discord or a webhook.") sets.update(channel=ch, target=None, tg_code=None, secret=None, fails=0, last_error=None) if ch == "telegram": if not tg(): raise ValueError("Telegram alerts aren't switched on yet.") sets["tg_code"] = secrets.token_urlsafe(12).replace("-", "x").replace("_", "y") elif ch == "discord": sets["target"] = check_url(b.get("url"), discord=True) else: sets["target"] = check_url(b.get("url")) sets["secret"] = a["secret"] if (a["channel"] == "webhook" and a["secret"]) else "whsec_" + secrets.token_urlsafe(24) if sets: with B.db() as c: c.execute("UPDATE ba_alerts SET %s WHERE id=?" % ", ".join("%s=?" % k for k in sets), list(sets.values()) + [a["id"]]) with B.db() as c: return h.send(200, public_view(c, dict(c.execute("SELECT * FROM ba_alerts WHERE id=?", (a["id"],)).fetchone()))) def p_test(h, q): b = B.jbody(h) with B.db() as c: a = find(c, b.get("token")) if not a: raise ValueError("That alert link isn't known.") B.limit(h, "alert_test:%d" % a["id"], 10) ok, err = send(a, "test", "๐Ÿ”” Test from BitAddy: alerts for %s will arrive here. No payment was made." % who(a), {"event": "test", "coin": a["coin"], "address": a["address"], "label": a["label"] or ""}) if not ok: raise ValueError("The test didn't arrive: %s." % err) return h.send(200, {"ok": True}) def p_delete(h, q): b = B.jbody(h) with B.db() as c: a = find(c, b.get("token")) if not a: raise ValueError("That alert link isn't known.") drop(c, a["id"]) S.audit("visitor", "BitAddy alert deleted", "%s ending %s" % (a["coin"], a["address"][-6:])) return h.send(200, {"ok": True}) PUBLIC = {("POST", "alert_new"): p_new, ("POST", "alert_get"): p_get, ("POST", "alert_update"): p_update, ("POST", "alert_test"): p_test, ("POST", "alert_delete"): p_delete} # ------------------------------------------------------------------ the Telegram bot's webhook (bitaddy.com/tg-hook/) def route(h, p, q): t = tg() if not t or not p.startswith("tg-hook/"): return False if getattr(h, "command", "") != "POST" or not hmac.compare_digest(p[len("tg-hook/"):], t.get("path_secret") or "x" * 40) or \ not hmac.compare_digest(h.headers.get("X-Telegram-Bot-Api-Secret-Token") or "", t.get("hook_secret") or "y" * 40): h.send(404, b"", "text/plain") return True try: upd = h.body_json(limit=200000) except Exception: upd = {} h.send(200, b"{}", "application/json") # answer Telegram first; the reply goes out as a separate call try: on_update(upd) except Exception: pass return True def on_update(upd): m = (upd or {}).get("message") or {} chat = (m.get("chat") or {}) text = str(m.get("text") or "").strip() if not chat.get("id") or chat.get("type") not in ("private", "group", "supergroup"): return cid = int(chat["id"]) say = lambda s: tg_call("sendMessage", {"chat_id": cid, "text": s, "disable_web_page_preview": True}) if text.startswith("/start"): code = text[6:].strip() if code and re.fullmatch(r"[A-Za-z0-9]{8,32}", code): with B.db() as c: a = c.execute("SELECT * FROM ba_alerts WHERE tg_code=? AND channel='telegram'", (code,)).fetchone() if a: c.execute("UPDATE ba_alerts SET target=?, tg_code=NULL, fails=0, last_error=NULL WHERE id=?", (str(cid), a["id"])) if a: a = dict(a) active = False with B.db() as c: u = B.perk_until(c, "alert", str(a["id"]), "alert") active = u is not None and (u == 0 or u > now()) return say("โœ… Connected. This chat will get BitAddy payment alerts for %s.%s" % ( who(a), "" if active else " The alert starts once it is paid; you can send a test from your alert link.")) mine = connected_here(cid) if mine: # the same link tapped again after it worked: nothing is wrong return say("โœ… This chat is already connected. It gets alerts for: %s." % "; ".join(mine)) return say("That connect link has already been used or has expired. Open your alert link on bitaddy.com and tap Connect Telegram again.") mine = connected_here(cid) if mine: return say("โœ… This chat gets BitAddy payment alerts for: %s. To add another address, open bitaddy.com/alerts/ ." % "; ".join(mine)) return say("Hi! I send BitAddy payment alerts: a message when a crypto address receives a payment. Set one up at %s/alerts/" % site()) if text.startswith("/stop"): with B.db() as c: n = c.execute("UPDATE ba_alerts SET target=NULL WHERE channel='telegram' AND target=?", (str(cid),)).rowcount return say("Stopped: this chat won't get alerts any more (%d alert%s disconnected). You can connect again from your alert link." % (n, "" if n == 1 else "s")) if text.startswith("/help"): return say("I send a message when an address you watch receives a payment. Manage your alerts from your alert link on %s/alerts/ . /stop disconnects this chat." % site()) def connected_here(cid): """The alerts this Telegram chat is connected to, as short names (at most 5).""" with B.db() as c: rows = [dict(r) for r in c.execute("SELECT * FROM ba_alerts WHERE channel='telegram' AND target=? ORDER BY id LIMIT 5", (str(cid),))] return [who(r) for r in rows] def set_webhook(): """Registers the bot's webhook with Telegram (run once at deploy, and whenever the secrets change).""" t = tg() return tg_call("setWebhook", {"url": "%s/tg-hook/%s" % (site(), t["path_secret"]), "secret_token": t["hook_secret"], "allowed_updates": ["message"], "drop_pending_updates": True}) def count_active(): with B.db() as c: return sum(1 for r in c.execute("SELECT id FROM ba_alerts") if B.has_perk(c, "alert", str(r["id"]), "alert"))