"""BitAddy: one short link for your crypto addresses. Site Console plugin (SITE_MODULE=bitaddy). Public (proxied from https://bitaddy.com): /_b/... product API + app files /_page/ personal pages (/) and short links (/) Admin (https://admin.bitaddy.com/api/site_): pages & links, reports & blocklist, stats, payments, top-ups, prices & wallets. No accounts in the personal sense: a page is managed with its owner key (a secret shown once) or by signing a message with a wallet (Cardano CIP-30, Ethereum personal_sign, Solana signMessage). No email, no names. Paid extras belong to ONE page or ONE link (table ba_perks), never to a person. They are paid in crypto only, straight to the site owner's own wallets (watch-only, see ba_pay.py), either on the spot or from a top-up link: a secret link that holds a dollar balance (ba_topups + ba_ledger). """ import base64, hashlib, hmac, json, mimetypes, os, random, re, secrets, sys, threading, time, urllib.parse from datetime import datetime, timedelta, timezone from decimal import Decimal, InvalidOperation from html import escape from pathlib import Path import ba_coins as coins import ba_cose as cose import ba_eth as eth import ba_names as names import ba_pay as pay import ba_agent as agent import ba_alerts as alerts import ba_payreq as payreq S = None # the core console module (set by init) HERE = Path(__file__).resolve().parent STATIC = HERE / "bitaddy_static" def init(core): global S S = core pay.init(core) agent.init(sys.modules[__name__], core) alerts.init(sys.modules[__name__], core) payreq.init(sys.modules[__name__], core) (Path(S.CFG["DATA_DIR"]) / "bitaddy-img").mkdir(exist_ok=True) if S.CFG.get("DEV") and os.environ.get("BA_TEST_CHAIN"): _test_chain(os.environ["BA_TEST_CHAIN"]) def _test_chain(path): """Local browser tests only (needs the DEV switch, which the live site never has): pretend blockchains and prices read from a JSON file, so a whole purchase can be clicked through without real money.""" global LOOK_GAP def read(): try: return json.loads(Path(path).read_text()) except Exception: return {} pay.incoming = lambda asset, address, since=None, skip=None: [dict(t, amount=int(t["amount"])) for t in read().get("tx", {}).get(asset, [])] pay.known = lambda asset, address: [] pay.start_height = lambda asset: 1 pay.prices = lambda: {k: Decimal(str(v)) for k, v in read().get("prices", {}).items()} pay.MIN_GAP.clear() LOOK_GAP = 1 for k in list(alerts.GAP): # payment alerts look every second on a test copy alerts.GAP[k] = 1 SCHEMA = """ CREATE TABLE IF NOT EXISTS ba_accounts(id INTEGER PRIMARY KEY, created INTEGER NOT NULL, plan_until INTEGER NOT NULL DEFAULT 0, banned INTEGER NOT NULL DEFAULT 0, note TEXT, last_seen INTEGER); CREATE TABLE IF NOT EXISTS ba_idents(id INTEGER PRIMARY KEY, account_id INTEGER NOT NULL, kind TEXT NOT NULL, value TEXT NOT NULL, label TEXT, created INTEGER NOT NULL, UNIQUE(kind, value)); CREATE TABLE IF NOT EXISTS ba_sessions(token TEXT PRIMARY KEY, account_id INTEGER NOT NULL, created INTEGER NOT NULL, last INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS ba_pages(id INTEGER PRIMARY KEY, account_id INTEGER NOT NULL, name TEXT UNIQUE NOT NULL, title TEXT, bio TEXT, avatar TEXT, theme TEXT, coins TEXT NOT NULL DEFAULT '[]', links TEXT NOT NULL DEFAULT '[]', created INTEGER NOT NULL, updated INTEGER NOT NULL, last_visit INTEGER, hidden INTEGER NOT NULL DEFAULT 0, hidden_reason TEXT, views INTEGER NOT NULL DEFAULT 0, scans INTEGER NOT NULL DEFAULT 0); CREATE TABLE IF NOT EXISTS ba_links(id INTEGER PRIMARY KEY, code TEXT UNIQUE NOT NULL, account_id INTEGER, coin TEXT NOT NULL, address TEXT NOT NULL, label TEXT, created INTEGER NOT NULL, last_visit INTEGER, hidden INTEGER NOT NULL DEFAULT 0, hidden_reason TEXT, views INTEGER NOT NULL DEFAULT 0, scans INTEGER NOT NULL DEFAULT 0, creator TEXT); CREATE TABLE IF NOT EXISTS ba_reports(id INTEGER PRIMARY KEY, ts INTEGER NOT NULL, kind TEXT NOT NULL, target TEXT NOT NULL, reason TEXT NOT NULL, note TEXT, reporter TEXT, status TEXT NOT NULL DEFAULT 'open', resolution TEXT, closed_by TEXT, closed INTEGER); CREATE TABLE IF NOT EXISTS ba_block(id INTEGER PRIMARY KEY, kind TEXT NOT NULL, value TEXT NOT NULL, note TEXT, ts INTEGER NOT NULL, by TEXT, UNIQUE(kind, value)); CREATE TABLE IF NOT EXISTS ba_codes(email TEXT PRIMARY KEY, code TEXT NOT NULL, expires INTEGER NOT NULL, tries INTEGER NOT NULL DEFAULT 0, account_id INTEGER); CREATE TABLE IF NOT EXISTS ba_nonces(nonce TEXT PRIMARY KEY, expires INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS ba_orders(id TEXT PRIMARY KEY, account_id INTEGER NOT NULL, item TEXT NOT NULL, usd TEXT NOT NULL, coin TEXT NOT NULL, amount TEXT NOT NULL, base TEXT NOT NULL, address TEXT NOT NULL, start_height INTEGER, created INTEGER NOT NULL, expires INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', tx TEXT, paid_at INTEGER, note TEXT); CREATE TABLE IF NOT EXISTS ba_seen(tx TEXT PRIMARY KEY, ts INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS ba_daily(day TEXT NOT NULL, target TEXT NOT NULL, views INTEGER NOT NULL DEFAULT 0, scans INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(day, target)); """ SCHEMA += """ CREATE TABLE IF NOT EXISTS ba_pay(id TEXT PRIMARY KEY, secret TEXT NOT NULL, kind TEXT NOT NULL, what TEXT NOT NULL DEFAULT '{}', label TEXT, usd TEXT NOT NULL, credit INTEGER NOT NULL DEFAULT 0, asset TEXT NOT NULL, amount TEXT NOT NULL, base TEXT NOT NULL, address TEXT NOT NULL, tag INTEGER, start_height INTEGER, created INTEGER NOT NULL, expires INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending', tx TEXT, paid_at INTEGER, note TEXT, result TEXT, problem INTEGER NOT NULL DEFAULT 0); CREATE TABLE IF NOT EXISTS ba_topups(id INTEGER PRIMARY KEY, token TEXT UNIQUE NOT NULL, cents INTEGER NOT NULL DEFAULT 0, created INTEGER NOT NULL, last_used INTEGER, note TEXT); CREATE TABLE IF NOT EXISTS ba_ledger(id INTEGER PRIMARY KEY, topup_id INTEGER NOT NULL, ts INTEGER NOT NULL, cents INTEGER NOT NULL, what TEXT NOT NULL, ref TEXT); CREATE TABLE IF NOT EXISTS ba_perks(id INTEGER PRIMARY KEY, kind TEXT NOT NULL, ref TEXT NOT NULL, sku TEXT NOT NULL, until INTEGER NOT NULL DEFAULT 0, created INTEGER NOT NULL, src TEXT, UNIQUE(kind, ref, sku)); CREATE TABLE IF NOT EXISTS ba_names(page_id INTEGER PRIMARY KEY, free_name TEXT UNIQUE NOT NULL); CREATE TABLE IF NOT EXISTS ba_requests(id INTEGER PRIMARY KEY, ts INTEGER NOT NULL, name TEXT NOT NULL, email TEXT NOT NULL, note TEXT, status TEXT NOT NULL DEFAULT 'open', closed INTEGER, closed_by TEXT, UNIQUE(name, email)); CREATE TABLE IF NOT EXISTS ba_stray(uid TEXT PRIMARY KEY, asset TEXT NOT NULL, tx TEXT NOT NULL, amount TEXT NOT NULL, tag INTEGER, ts INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'open', note TEXT); """ # Funnel steps (2026-11-27): what visitors DO, step by step, so the owner can see where people stop. Anonymous: a "visit" is a random # tag that lives in one browser tab (sessionStorage) and is gone when the tab closes. No cookie, no IP, nothing tied to a page or link. SCHEMA += """ CREATE TABLE IF NOT EXISTS ba_events(id INTEGER PRIMARY KEY, ts INTEGER NOT NULL, day TEXT NOT NULL, visit TEXT NOT NULL, step TEXT NOT NULL, detail TEXT, path TEXT, tag TEXT, ref TEXT, device TEXT, country TEXT); CREATE INDEX IF NOT EXISTS ba_events_day ON ba_events(day); """ SCHEMA += agent.SCHEMA # calls made through the API / MCP server: counts only SCHEMA += alerts.SCHEMA # payment alerts (ba_alerts.py) SCHEMA += payreq.SCHEMA # payment requests that turn into "Paid" (ba_payreq.py) def db(): return S.DB() def now(): return int(time.time()) # ------------------------------------------------------------------ settings DEFAULT_CFG = { "free_coins": 5, "free_links": 2, "pro_coins": 20, "pro_links": 10, "min_free_name": 5, "min_name": 3, "autohide": 3, "min_pay": "3", "min_topup": "5", "max_topup": "500", "bonus_from": "25", "bonus_pct": 10, "tips": True, "items": {"pro": {"on": True, "usd": "9", "days": 365}, "name4": {"on": True, "usd": "10", "days": 365}, "name3": {"on": True, "usd": "25", "days": 365}, "keep": {"on": True, "usd": "5", "days": 0}, "alert": {"on": True, "usd": "10", "days": 365}}, "sponsor": {"on": False, "text": "", "url": ""}, "refs": [], "pay_off": [], "reserved_off": [], "released": [], "reserved_more": [], } # what each extra is; "for" says whether it belongs to a page or to a short link ITEMS = { "pro": {"name": "Pro page", "for": "page", "blurb": "Your picture and colour, more addresses and links, visit counts, printable QR cards, no sponsor line, never removed."}, "name4": {"name": "4-letter name", "for": "page", "blurb": "A short page address like bitaddy.com/abcd."}, "name3": {"name": "3-letter name", "for": "page", "blurb": "A very short page address like bitaddy.com/sam."}, "keep": {"name": "Keep this link", "for": "link", "blurb": "The short link is not removed for not being used."}, "alert": {"name": "Payment alerts", "for": "alert", "blurb": "A message on Telegram, Discord or a webhook when one address receives a payment."}, } NAME_GRACE = 30 * 86400 # after a paid name's time ends, the owner has this long to renew before the name goes back LINK_IDLE = 180 * 86400 # a free short link nobody visits for this long expires (it stops working) PAGE_IDLE = 365 * 86400 # the same for a free page EXPIRED_KEEP = 90 * 86400 # an expired link or page can still be brought back for this long; then it is deleted # page colours a Pro page can pick: (light, dark); "violet" is the site's own colour THEMES = {"violet": None, "blue": ("#1d5fd6", "#8ab4ff"), "mint": ("#007f5f", "#3ddcaa"), "amber": ("#a15a00", "#ffb238"), "pink": ("#c2256f", "#ff85b8"), "red": ("#c0362c", "#ff8f86")} def cfg(): c = json.loads(json.dumps(DEFAULT_CFG)) for k, v in (S.setting("ba_cfg", {}) or {}).items(): if k == "items": for sku, it in (v or {}).items(): if sku in c["items"] and isinstance(it, dict): c["items"][sku].update(it) elif k in c: c[k] = v return c def wallets(): return S.setting("ba_wallets", {}) or {} def pay_assets(c0=None): """The ways to pay that are open right now: its chain has a receiving wallet and the owner hasn't switched it off.""" c0 = c0 or cfg() w = wallets() return [a for a in pay.ORDER if w.get(pay.ASSETS[a]["chain"]) and a not in (c0.get("pay_off") or [])] def money(cents): return "%d.%02d" % (cents // 100, cents % 100) def dollars(x, lo=None, hi=None, what="Amount"): try: d = Decimal(str(x)).quantize(Decimal("0.01")) except (InvalidOperation, ValueError): raise ValueError("%s must be a number." % what) if lo is not None and d < Decimal(str(lo)): raise ValueError("%s: at least $%s." % (what, lo)) if hi is not None and d > Decimal(str(hi)): raise ValueError("%s: at most $%s." % (what, hi)) return d # ------------------------------------------------------------------ names, safety NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9-]{1,28}[a-z0-9])$") CODE_RE = re.compile(r"^[A-Za-z0-9]{6}$") CODE_ALPHABET = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789" def blocked(kind, value): v = value.strip() v = v.lower() if kind == "name" else v with db() as c: if kind == "name": for r in c.execute("SELECT value FROM ba_block WHERE kind='name'"): if r["value"] and r["value"] in v: return True return False return c.execute("SELECT 1 FROM ba_block WHERE kind='address' AND value=?", (v,)).fetchone() is not None def is_short(name, c0=None): return len(name) < int((c0 or cfg())["min_free_name"]) def name_sku(name): return "name3" if len(name) <= 3 else "name4" def name_problem(name, short_ok=False): n = (name or "").strip().lower() c0 = cfg() if not NAME_RE.match(n): return "Use 3 to 30 lowercase letters, numbers or dashes (not at the start or end)." if "--" in n: return "No double dashes, please." hit = names.check(n, c0.get("reserved_off") or (), set(c0.get("released") or ())) if hit: return "That name is reserved." if hit[0] == "reserved" else "That name isn't allowed." if n in (c0.get("reserved_more") or ()) or blocked("name", n): return "That name isn't available." if len(n) < int(c0["min_name"]): return "Too short." if is_short(n, c0) and not short_ok: return "Names shorter than %d letters are a paid extra. Make your page with a longer name first, then switch to the short one in My links." % int(c0["min_free_name"]) return None EMAIL_RE = re.compile(r"^[^@\s]{1,64}@[^@\s]{1,190}\.[a-z]{2,24}$", re.I) def can_request(name, c0=None): """A reserved name that a person may ask for (a famous name, a brand, a common word or first name, or one the owner reserved). BitAddy's own words, the example names and blocked words can't be asked for.""" c0 = c0 or cfg() if not NAME_RE.match(name or ""): return False hit = names.check(name, c0.get("reserved_off") or (), set(c0.get("released") or ())) if hit: return hit[0] == "reserved" and hit[1] not in names.ALWAYS return name in (c0.get("reserved_more") or ()) def name_taken(c, name, but_page=None): """Taken = a page uses it, a page is keeping it as the free name to fall back to, or someone is paying for it right now.""" r = c.execute("SELECT id FROM ba_pages WHERE name=?", (name,)).fetchone() if r and r["id"] != but_page: return True r = c.execute("SELECT page_id FROM ba_names WHERE free_name=?", (name,)).fetchone() if r and r["page_id"] != but_page: return True for o in c.execute("SELECT what FROM ba_pay WHERE kind='item' AND status='pending' AND expires>?", (now() - 86400,)): w = json.loads(o["what"]) if w.get("name") == name and w.get("page") != but_page: return True return False def clean_text(s, n): s = re.sub(r"[\x00-\x08\x0b-\x1f\x7f]", "", str(s or "")).strip() return s[:n] def check_coins(items, limit): out = [] if not isinstance(items, list): raise ValueError("Bad coin list.") if len(items) > limit: raise ValueError("Up to %d addresses on this plan." % limit) for it in items: coin = str(it.get("coin") or "").upper() addr, why = coins.check(coin, it.get("address")) if not addr: raise ValueError("%s: %s" % (coins.COINS.get(coin, {}).get("name", coin or "Address"), why)) if blocked("address", addr): raise ValueError("That address can't be used on BitAddy.") out.append({"coin": coin, "address": addr, "label": clean_text(it.get("label"), 40), "verified": bool(it.get("verified"))}) return out def check_links(items, limit): out = [] if not isinstance(items, list): raise ValueError("Bad link list.") if len(items) > limit: raise ValueError("Up to %d links on this plan." % limit) for it in items: url = clean_text(it.get("url"), 300) if not re.match(r"^https://[^\s<>\"']+\.[^\s<>\"']+$", url): raise ValueError("Links must start with https://") out.append({"label": clean_text(it.get("label"), 30) or urllib.parse.urlsplit(url).hostname, "url": url}) return out # ------------------------------------------------------------------ extras (perks) on a page or a link def perk_until(c, kind, ref, sku): """None = doesn't have it, 0 = has it for good, otherwise the time it ends.""" r = c.execute("SELECT until FROM ba_perks WHERE kind=? AND ref=? AND sku=?", (kind, str(ref), sku)).fetchone() return None if r is None else r["until"] def has_perk(c, kind, ref, sku, grace=0): u = perk_until(c, kind, ref, sku) return u is not None and (u == 0 or u + grace > now()) def add_perk(c, kind, ref, sku, days, src): u = perk_until(c, kind, ref, sku) new = 0 if (not days or u == 0) else max(now(), u or 0) + int(days) * 86400 c.execute("INSERT INTO ba_perks(kind,ref,sku,until,created,src) VALUES(?,?,?,?,?,?) ON CONFLICT(kind,ref,sku) DO UPDATE SET " "until=excluded.until, src=excluded.src", (kind, str(ref), sku, new, now(), src)) return new def page_pro(c, page_id): return has_perk(c, "page", page_id, "pro") def idle_since(row): return row["last_visit"] or row["created"] def link_expired(c, l): return idle_since(l) < now() - LINK_IDLE and not has_perk(c, "link", l["code"], "keep") def page_expired(c, p): return idle_since(p) < now() - PAGE_IDLE and not page_pro(c, p["id"]) def span_text(d): return (" a year" if d == 365 else " for %d years" % (d // 365)) if d % 365 == 0 else " for %d days" % d def until_text(u): return " for good" if not u else " until " + datetime.fromtimestamp(u, timezone.utc).strftime("%-d %b %Y") def drop_page_extras(c, page_id): c.execute("DELETE FROM ba_perks WHERE kind='page' AND ref=?", (str(page_id),)) c.execute("DELETE FROM ba_names WHERE page_id=?", (page_id,)) # ------------------------------------------------------------------ owners & sessions (an "account" is only a key ring: owner key and/or wallets) def new_account(c): c.execute("INSERT INTO ba_accounts(created, last_seen) VALUES(?,?)", (now(), now())) return c.execute("SELECT last_insert_rowid()").fetchone()[0] def add_ident(c, account_id, kind, value, label=None): r = c.execute("SELECT account_id FROM ba_idents WHERE kind=? AND value=?", (kind, value)).fetchone() if r: if r["account_id"] != account_id: raise ValueError("That %s is already linked to another BitAddy account." % ("wallet" if kind == "wallet" else kind)) return c.execute("INSERT INTO ba_idents(account_id,kind,value,label,created) VALUES(?,?,?,?,?)", (account_id, kind, value, label, now())) def account_for_ident(kind, value): with db() as c: r = c.execute("SELECT account_id FROM ba_idents WHERE kind=? AND value=?", (kind, value)).fetchone() return r["account_id"] if r else None def make_session(h, account_id): t = secrets.token_urlsafe(32) with db() as c: c.execute("INSERT INTO ba_sessions(token,account_id,created,last) VALUES(?,?,?,?)", (S.tok_hash(t), account_id, now(), now())) c.execute("UPDATE ba_accounts SET last_seen=? WHERE id=?", (now(), account_id)) return "ba_sess=%s; Path=/; HttpOnly; SameSite=Lax; Max-Age=%d%s" % (t, 30 * 86400, "" if S.CFG["DEV"] else "; Secure") def session_account(h): t = h.cookie("ba_sess") if not t: return None th = S.tok_hash(t) with db() as c: s = c.execute("SELECT * FROM ba_sessions WHERE token=?", (th,)).fetchone() if not s or s["last"] < now() - 30 * 86400: return None a = c.execute("SELECT * FROM ba_accounts WHERE id=?", (s["account_id"],)).fetchone() if not a or a["banned"]: return None if s["last"] < now() - 300: c.execute("UPDATE ba_sessions SET last=? WHERE token=?", (now(), th)) c.execute("UPDATE ba_accounts SET last_seen=? WHERE id=?", (now(), a["id"])) return a def new_owner_key(): return "ba-" + secrets.token_urlsafe(18) # ------------------------------------------------------------------ wallet signatures def sign_message(nonce): return "Sign in to BitAddy.com\n\nThis proves you own this wallet. It costs nothing and moves no funds.\n\nCode: " + nonce def take_nonce(nonce): with db() as c: r = c.execute("SELECT * FROM ba_nonces WHERE nonce=?", (nonce or "",)).fetchone() c.execute("DELETE FROM ba_nonces WHERE nonce=? OR expires= now()) def verify_wallet(b, expect_address=None): """b: {chain, nonce, ...}. Returns (chain_coin, address). Raises ValueError.""" chain = str(b.get("chain") or "").upper() nonce = str(b.get("nonce") or "") if not take_nonce(nonce): raise ValueError("That sign-in request expired. Please try again.") msg = sign_message(nonce) if chain == "ADA": addr_hex = str(b.get("address_hex") or "") try: raw = bytes.fromhex(addr_hex) except ValueError: raise ValueError("Unreadable wallet address.") if not raw or raw[0] >> 4 not in (0, 2, 4, 6): raise ValueError("Please use a normal Cardano payment address.") addr = cose.ck.bech32_encode("addr", raw) if raw[0] & 0x0F == 1 else None if not addr: raise ValueError("Please use a Cardano mainnet wallet.") cose.verify_owner(str(b.get("signature") or ""), str(b.get("key") or ""), msg, raw) elif chain == "ETH": addr = eth.recover_address(msg, str(b.get("signature") or "")) claimed = str(b.get("address") or "") if claimed and claimed.lower() != addr.lower(): raise ValueError("The signature came from a different wallet.") elif chain == "SOL": addr = str(b.get("address") or "") ok, _ = coins.check("SOL", addr) if not ok: raise ValueError("Unreadable Solana address.") try: pub = coins.b58decode(addr) sig = base64.b64decode(str(b.get("signature") or "")) except Exception: raise ValueError("Unreadable signature.") if len(pub) != 32 or len(sig) != 64 or not cose.ed25519_verify(pub, msg.encode(), sig): raise ValueError("The signature didn't check out.") else: raise ValueError("Pick Cardano, Ethereum or Solana.") if expect_address and expect_address.lower() != addr.lower(): raise ValueError("Your wallet signed with a different address than the one on the page.") return chain, addr # ------------------------------------------------------------------ what is being bought def resolve_item(h, b): """Checks a request to buy an extra. -> (sku, dollars, what, label). Page extras need the page's owner; link extras don't.""" c0 = cfg() sku = str(b.get("sku") or "") name = None if sku == "alert": # payment alerts belong to an alert link, not to a page or a short link (ba_alerts.py) return alerts.resolve(b, c0) if sku == "name": name = str(b.get("name") or "").strip().lower() why = name_problem(name, short_ok=True) if why: raise ValueError(why) if not is_short(name, c0): raise ValueError("That name is free: just change your page's address to it.") sku = name_sku(name) it = c0["items"].get(sku) if sku not in ITEMS or not it or not it.get("on"): raise ValueError("That extra isn't for sale right now.") usd = dollars(it["usd"], what="Price") days = int(it.get("days") or 0) if ITEMS[sku]["for"] == "page": a = need_account(h) with db() as c: p = own_page(c, a, b.get("page_id")) if name and name_taken(c, name, but_page=p["id"]): raise ValueError("That name is taken.") if sku == "pro" and perk_until(c, "page", p["id"], "pro") == 0: raise ValueError("This page already has Pro for good.") what = {"sku": sku, "page": p["id"], "days": days} if name: what["name"] = name label = "%s: bitaddy.com/%s" % (ITEMS[sku]["name"], name or p["name"]) else: code = str(b.get("code") or "") with db() as c: if not CODE_RE.match(code) or not c.execute("SELECT 1 FROM ba_links WHERE code=?", (code,)).fetchone(): raise ValueError("That short link doesn't exist.") if perk_until(c, "link", code, "keep") == 0: raise ValueError("This link is already kept for good.") what = {"sku": sku, "link": code, "days": days} label = "%s: bitaddy.com/%s" % (ITEMS[sku]["name"], code) return sku, usd, what, label def apply_item(what, src): """Switches a paid extra on. Returns a sentence for the buyer. Raises ValueError if it can't be done any more.""" sku, days = what["sku"], int(what.get("days") or 0) if sku == "alert": return alerts.apply(what, src) with db() as c: if "page" in what: p = c.execute("SELECT * FROM ba_pages WHERE id=?", (what["page"],)).fetchone() if not p: raise ValueError("the page no longer exists") if sku == "pro": u = add_perk(c, "page", p["id"], "pro", days, src) return "Pro is on for bitaddy.com/%s%s." % (p["name"], until_text(u)) name = what["name"] if p["name"] != name: if name_taken(c, name, but_page=p["id"]): raise ValueError("the name bitaddy.com/%s was taken in the meantime" % name) if not is_short(p["name"]): # remember the free name: the page goes back to it if the short name isn't renewed c.execute("INSERT INTO ba_names(page_id,free_name) VALUES(?,?) ON CONFLICT(page_id) DO UPDATE SET free_name=excluded.free_name", (p["id"], p["name"])) c.execute("DELETE FROM ba_perks WHERE kind='page' AND ref=? AND sku='name'", (str(p["id"]),)) # a new name starts its own time c.execute("UPDATE ba_pages SET name=?, updated=? WHERE id=?", (name, now(), p["id"])) u = add_perk(c, "page", p["id"], "name", days, src) return "bitaddy.com/%s is yours%s." % (name, until_text(u)) if not c.execute("SELECT 1 FROM ba_links WHERE code=?", (what["link"],)).fetchone(): raise ValueError("the short link no longer exists") u = add_perk(c, "link", what["link"], "keep", days, src) return "bitaddy.com/%s is kept%s." % (what["link"], until_text(u)) # ------------------------------------------------------------------ orders (paying on the spot, topping up, tips) def baseline(asset, address): """The first time an address is watched for a coin, everything already in it is marked as seen, so old history is never mistaken for a new payment. Doubles as a check that the coin can be read at all before an order is taken.""" key = asset + "|" + address done = S.setting("ba_base", []) or [] if key in done: return try: ids = pay.known(asset, address) except Exception: raise ValueError("%s payments can't be checked right now. Please pick another coin, or try again in a few minutes." % pay.ASSETS[asset]["name"]) with db() as c: for uid in ids: c.execute("INSERT OR IGNORE INTO ba_seen(tx,ts) VALUES(?,?)", (asset + ":" + uid, now())) S.set_setting("ba_base", (S.setting("ba_base", []) or []) + [key]) def order_public(o, secret=None): a = pay.ASSETS.get(o["asset"], {}) d = {k: o[k] for k in ("id", "kind", "label", "usd", "asset", "amount", "address", "tag", "created", "expires", "status", "tx", "note", "result", "paid_at")} d.update(symbol=pay.symbol(o["asset"]), asset_name=a.get("name", o["asset"]), wait=a.get("wait", ""), problem=bool(o["problem"]), explorer=pay.explorer(o["asset"], o["tx"]) if o["tx"] else None, uri=coins.COINS.get(a.get("chain"), {}).get("uri") if not a.get("token") else "") if secret: d["secret"] = secret return d def new_order(kind, usd, what, label, asset, credit=0): c0 = cfg() if asset not in pay.ASSETS or asset not in pay_assets(c0): raise ValueError("That way to pay isn't available right now.") address = wallets()[pay.ASSETS[asset]["chain"]] baseline(asset, address) # network calls: all done before the database is opened height = pay.start_height(asset) pay.prices() secret = secrets.token_urlsafe(12) with db() as c: if c.execute("SELECT COUNT(*) FROM ba_pay WHERE status='pending'").fetchone()[0] >= 300: raise ValueError("BitAddy is very busy right now. Please try again in a little while.") taken = {r["base"] for r in c.execute("SELECT base FROM ba_pay WHERE asset=? AND status='pending'", (asset,))} base = pay.make_amount(usd, asset, taken) tag = None if pay.ASSETS[asset]["chain"] == "XRP": tags = {r["tag"] for r in c.execute("SELECT tag FROM ba_pay WHERE asset='XRP' AND status='pending'")} tag = next(t for t in iter(lambda: random.randint(10 ** 8, 4 * 10 ** 9), None) if t not in tags) oid = "BA-" + secrets.token_hex(4).upper() c.execute("INSERT INTO ba_pay(id,secret,kind,what,label,usd,credit,asset,amount,base,address,tag,start_height,created,expires) " "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", (oid, S.tok_hash(secret), kind, json.dumps(what), label, str(usd), int(credit), asset, pay.fmt_amount(base, asset), base, address, tag, height, now(), now() + 3600)) o = dict(c.execute("SELECT * FROM ba_pay WHERE id=?", (oid,)).fetchone()) S.audit("visitor", "BitAddy order", "%s %s: %s %s" % (oid, label, o["amount"], asset)) return order_public(o, secret) def fulfil(o): """An order was paid: hand over what it was for.""" what, problem = json.loads(o["what"]), 0 try: if o["kind"] == "topup": with db() as c: if not c.execute("UPDATE ba_topups SET cents=cents+?, last_used=? WHERE id=?", (o["credit"], now(), what["topup"])).rowcount: raise ValueError("the top-up link no longer exists") c.execute("INSERT INTO ba_ledger(topup_id,ts,cents,what,ref) VALUES(?,?,?,?,?)", (what["topup"], now(), o["credit"], "Added with %s %s" % (o["amount"], pay.symbol(o["asset"])), o["id"])) res = "$%s was added to your top-up link." % money(o["credit"]) elif o["kind"] == "item": res = apply_item(what, o["id"]) else: res = "Thank you for the tip!" except ValueError as e: problem = 1 res = "Your payment arrived, but %s. Please write to hello@bitaddy.com with your order number and we'll sort it out." % e with db() as c: c.execute("UPDATE ba_pay SET result=?, problem=? WHERE id=?", (res, problem, o["id"])) return res def mark_paid(o, tx, uid=None, by="chain"): with db() as c: if uid: c.execute("INSERT OR IGNORE INTO ba_seen(tx,ts) VALUES(?,?)", (o["asset"] + ":" + uid, now())) r = c.execute("UPDATE ba_pay SET status='paid', tx=?, paid_at=?, note=NULL WHERE id=? AND status IN ('pending','expired')", (tx, now(), o["id"])) if not r.rowcount: return False fulfil(o) S.audit("bitaddy" if by == "chain" else by, "BitAddy payment", "order %s (%s), %s %s, tx %s" % (o["id"], o["label"], o["amount"], o["asset"], (tx or "")[:20])) return True CHECK_LOCK = threading.Lock() LAST_LOOK = {} LOOK_GAP = 40 # seconds between looks at one coin while someone is paying def check_payments(force=False): """Looks at the receiving addresses that have open orders. Called every half minute by the console, and when a buyer's screen asks how its order is doing. Each coin is only asked as often as its free service allows; once an order's hour is over it is only looked for every ten minutes (payments up to a day late still count).""" if not CHECK_LOCK.acquire(False): return try: with db() as c: c.execute("UPDATE ba_pay SET status='expired' WHERE status='pending' AND expires now() for o in olist) gap = max(pay.MIN_GAP.get(asset, LOOK_GAP), LOOK_GAP if fresh else 600) if not force and time.time() - LAST_LOOK.get((asset, address), 0) < gap: continue LAST_LOOK[(asset, address)] = time.time() with db() as c: seen = {r["tx"] for r in c.execute("SELECT tx FROM ba_seen WHERE tx LIKE ?", (asset + ":%",))} try: txs = pay.incoming(asset, address, min((o["start_height"] or 0) for o in olist), {s.split(":", 1)[1] for s in seen}) except Exception as e: LAST_ERR[asset] = (now(), str(e)[:200]) continue LAST_ERR.pop(asset, None) for t in txs: if asset + ":" + t["uid"] in seen: continue o = match(olist, t) if o and not t["confirmed"]: with db() as c: c.execute("UPDATE ba_pay SET note='seen, waiting for it to confirm', tx=? WHERE id=? AND status='pending'", (t["tx"], o["id"])) elif o: if mark_paid(o, t["tx"], t["uid"]): o["status"] = "paid" elif t["confirmed"]: stray(asset, t, olist) finally: CHECK_LOCK.release() LAST_ERR = {} def match(olist, t): for o in olist: if o["status"] != "pending": continue if str(t["amount"]) == o["base"]: return o # XRP: the destination tag says which order it is, so a hair less than asked (an exchange's fee) is still accepted if o["tag"] and t.get("tag") == o["tag"] and t["amount"] * 100 >= int(o["base"]) * 98: return o return None def stray(asset, t, olist): """A payment that matches no open order (wrong amount, or very late). Kept for the owner to look at; dust is ignored.""" p = pay.PRICE["p"].get(asset) worth = (Decimal(t["amount"]) / (Decimal(10) ** pay.ASSETS[asset]["dec"]) * p) if p else None with db() as c: c.execute("INSERT OR IGNORE INTO ba_seen(tx,ts) VALUES(?,?)", (asset + ":" + t["uid"], now())) if worth is not None and worth < Decimal("0.5"): return near = [o["id"] for o in olist if o["tag"] and t.get("tag") == o["tag"]] c.execute("INSERT OR IGNORE INTO ba_stray(uid,asset,tx,amount,tag,ts,note) VALUES(?,?,?,?,?,?,?)", (asset + ":" + t["uid"], asset, t["tx"], pay.fmt_amount(t["amount"], asset), t.get("tag"), now(), ("carries the tag of order %s but is too small" % near[0]) if near else None)) # ------------------------------------------------------------------ stats def count_visit(h, kind, target_id, target_key, scan): ua = h.headers.get("User-Agent", "") if not ua or S.BOT_RE.search(ua): return day = datetime.now(timezone.utc).strftime("%Y-%m-%d") col = "scans" if scan else "views" table = "ba_pages" if kind == "page" else "ba_links" with db() as c: c.execute("UPDATE %s SET %s=%s+1, last_visit=? WHERE id=?" % (table, col, col), (now(), target_id)) c.execute("INSERT INTO ba_daily(day,target,%s) VALUES(?,?,1) ON CONFLICT(day,target) DO UPDATE SET %s=%s+1" % (col, col, col), (day, target_key)) # ------------------------------------------------------------------ public HTML def coin_name(c): return coins.COINS.get(c, {}).get("name", c) MARK = ('') GEAR_BTN = '' def page_html(title, body, theme=None, desc="", noindex=False, canonical=""): pair = THEMES.get(theme or "") style = ("" % pair) if pair else "" return """ %s%s%s %s
%s """ % ( escape(title), escape(desc), '' if noindex else "", ('' % escape(canonical)) if canonical else "", style, MARK, GEAR_BTN, body) WARN = ('

Always check the address in your wallet before you send. BitAddy only confirms who owns an address ' 'when it shows ✓ Verified.

') AMOUNT_RE = re.compile(r"^(?:0|[1-9]\d{0,11})(?:\.\d{1,8})?$") def coin_block(c, i, ask=None): addr = c["address"] ver = '✓ Verified' if c.get("verified") else \ 'Not verified' asked = ('

The owner of this link asks for %s %s

' % (escape(ask), escape(c["coin"]))) if ask else "" return """
%s%s%s
%s
%s
Ends in %s
""" % (escape(addr), escape(c["coin"]), escape(coins.COINS.get(c["coin"], {}).get("uri", "")), (' data-amt="%s"' % escape(ask)) if ask else "", escape(coin_name(c["coin"])), (' · ' + escape(c["label"])) if c.get("label") else "", ver, asked, i, escape(addr), escape(addr[-6:]), escape(addr)) def sponsor_html(): sp = cfg().get("sponsor") or {} if not sp.get("on") or not sp.get("text") or not str(sp.get("url") or "").startswith("https://"): return "" return '' % (escape(sp["url"]), escape(sp["text"])) def ask_for(q, coin_list): """?a=12.5 (and &c=ADA on a page with several coins): the index of the address being asked for, and the amount.""" a = str(q.get("a") or "") if not AMOUNT_RE.match(a) or not coin_list: return None, None want = str(q.get("c") or "").upper() for i, c in enumerate(coin_list): if not want or c["coin"] == want: return i, a return None, None def render_page(p, pro, q): coins_l = json.loads(p["coins"]) links_l = json.loads(p["links"]) ai, amt = ask_for(q, coins_l) av = ('' % escape(p["avatar"])) if (p["avatar"] and pro) else \ '
%s
' % escape((p["title"] or p["name"])[:1].upper()) links = "".join('%s ↗' % (escape(l["url"]), escape(l["label"])) for l in links_l) body = """
%s

%s

bitaddy.com/%s

%s%s%s
%s

· Make your own BitAddy

%s
""" % (av, escape(p["title"] or p["name"]), escape(p["name"]), ('

%s

' % escape(p["bio"])) if p["bio"] else "", ('' % links) if links else "", WARN, "".join(coin_block(c, i, amt if i == ai else None) for i, c in enumerate(coins_l)) or '

No addresses yet.

', escape(p["name"]), "" if pro else sponsor_html()) return page_html("%s · BitAddy" % (p["title"] or p["name"]), body, p["theme"] if pro else None, desc="%s's crypto addresses on BitAddy: %s" % (p["title"] or p["name"], ", ".join(coin_name(c["coin"]) for c in coins_l)), canonical="https://%s/%s" % (S.CFG["SITE_DOMAIN"], p["name"]), noindex=bool(amt)) def render_link(l, kept, q): c = {"coin": l["coin"], "address": l["address"], "label": l["label"], "verified": False} _, amt = ask_for(q, [c]) c0 = cfg() offer = not kept and c0["items"]["keep"].get("on") and pay_assets(c0) # only when it can really be bought kd = c0["items"]["keep"].get("days") or 0 keep = ' · Keep this link%s' % (escape(l["code"]), span_text(kd) if kd else " for good") if offer else "" body = """
%s

%s

bitaddy.com/%s

%s
%s

· Make your own BitAddy%s

%s
""" % ( escape(l["coin"][:1]), escape(l["label"] or (coin_name(l["coin"]) + " address")), escape(l["code"]), WARN, coin_block(c, 0, amt), escape(l["code"]), keep, sponsor_html()) return page_html("%s · BitAddy" % (l["label"] or coin_name(l["coin"]) + " address"), body, noindex=True) def render_msg(title, text, code=404, more="", small=""): body = '

%s

%s

Go to the BitAddy home page%s

%s
' % ( escape(title), escape(text), more, ('

%s

' % escape(small)) if small else "") return code, page_html(title + " · BitAddy", body, noindex=True) def render_expired(kind, key): """A link or page that stopped working because nobody used it. It can still be brought back for a while.""" days = EXPIRED_KEEP // 86400 if kind == "link": c0 = cfg() more = (' Bring it back and keep it' % escape(key)) \ if c0["items"]["keep"].get("on") and pay_assets(c0) else "" return render_msg("This link has expired", "bitaddy.com/%s wasn't used for %d days, so it was switched off. If it was yours, you can make " "a new one in a few seconds." % (key, LINK_IDLE // 86400), 410, more, "An expired link is removed for good %d days after it expires." % days) return render_msg("This page has expired", "bitaddy.com/%s wasn't visited for a year, so it was switched off. If it's your page, open " "My links to bring it back. That's free." % key, 410, ' Open My links', "An expired page is removed for good %d days after it expires." % days) def render_example(key): """The names and the short link BitAddy uses as examples in its own pages. They belong to nobody and lead back to BitAddy.""" body = ('

This is only an example

bitaddy.com/%s is an example address that BitAddy uses to show ' 'what a link looks like. It belongs to nobody and holds no crypto address.

' '

Make your own on BitAddy

') % escape(key) return 200, page_html("An example · BitAddy", body, noindex=True) # ------------------------------------------------------------------ public routes def public(h, method, path, q): try: if path.startswith("/_page/"): return serve_page(h, path[len("/_page"):], q) if path.startswith("/_b/static/"): name = path[len("/_b/static/"):] f = STATIC / name if not re.fullmatch(r"[a-z0-9_\-]+\.(js|css|svg)", name) or not f.exists(): return h.err(404, "Not found.") ct = mimetypes.guess_type(name)[0] + ("; charset=utf-8" if not name.endswith(".svg") else "") return h.send(200, f.read_bytes(), ct, cache="public, max-age=300") if path.startswith("/_b/img/"): name = path[len("/_b/img/"):] f = Path(S.CFG["DATA_DIR"]) / "bitaddy-img" / name if not re.fullmatch(r"[a-f0-9]{32}\.(png|jpg|webp)", name) or not f.exists(): return h.err(404, "Not found.") return h.send(200, f.read_bytes(), mimetypes.guess_type(name)[0], cache="public, max-age=86400") name = path[len("/_b/"):].replace("/", "_").replace("-", "_") fn = PUBLIC.get((method, name)) if not fn: return h.err(404, "Not found.") if method == "POST": o = h.headers.get("Origin") if h.headers.get("X-BitAddy") != "1" or (o and not S.CFG["DEV"] and o != S.CFG["SITE_ORIGIN"]): return h.err(403, "Request refused.") return fn(h, q) except ValueError as e: return h.err(400, str(e)) def serve_page(h, path, q): p = urllib.parse.unquote(path).strip("/") if agent.route(h, p, q): # bitaddy.com/mcp, /api/v1/..., /openapi.json: for AI agents and other programs (ba_agent.py) return if alerts.route(h, p, q): # bitaddy.com/tg-hook/: the Telegram bot's webhook (ba_alerts.py) return if payreq.route(h, p, q): # bitaddy.com/r/: a payment request (ba_payreq.py) return if not p or "/" in p: code, html = render_msg("Nothing here", "There's nothing at this address.") return h.send(code, html, "text/html; charset=utf-8") if p in names.EXAMPLE_CODES or p.lower() in names.EXAMPLES: code, html = render_example(p if p in names.EXAMPLE_CODES else p.lower()) return h.send(code, html, "text/html; charset=utf-8") scan = q.get("q") == "1" if CODE_RE.match(p) and p != p.lower(): with db() as c: l = c.execute("SELECT * FROM ba_links WHERE code=?", (p,)).fetchone() kept = bool(l) and has_perk(c, "link", p, "keep") gone = bool(l) and link_expired(c, l) if l: if l["hidden"]: code, html = render_msg("Under review", "This link was reported and is hidden while we check it.", 410) return h.send(code, html, "text/html; charset=utf-8") if gone: code, html = render_expired("link", p) return h.send(code, html, "text/html; charset=utf-8", cache="no-cache") count_visit(h, "link", l["id"], "l:" + l["code"], scan) return h.send(200, render_link(l, kept, q), "text/html; charset=utf-8", cache="no-cache") name = p.lower() with db() as c: pg = c.execute("SELECT * FROM ba_pages WHERE name=?", (name,)).fetchone() acct = c.execute("SELECT * FROM ba_accounts WHERE id=?", (pg["account_id"],)).fetchone() if pg else None pro = bool(pg) and page_pro(c, pg["id"]) gone = bool(pg) and page_expired(c, pg) moved = None if pg else c.execute("SELECT p.name FROM ba_names n JOIN ba_pages p ON p.id=n.page_id WHERE n.free_name=?", (name,)).fetchone() if moved: # the page's old free name still leads to it while it has a short name return h.send(302, b"", "text/plain", headers={"Location": "/" + moved["name"]}) if pg and p != name: return h.send(301, b"", "text/plain", headers={"Location": "/" + name}) if not pg: code, html = render_msg("Nothing here", "There's nothing at bitaddy.com/%s. The link may have expired and been removed, or the address " "may have a small typo." % p[:40]) return h.send(code, html, "text/html; charset=utf-8") if pg["hidden"] or (acct and acct["banned"]): code, html = render_msg("Under review", "This page was reported and is hidden while we check it.", 410) return h.send(code, html, "text/html; charset=utf-8") if gone: code, html = render_expired("page", pg["name"]) return h.send(code, html, "text/html; charset=utf-8", cache="no-cache") count_visit(h, "page", pg["id"], "p:" + pg["name"], scan) return h.send(200, render_page(pg, pro, q), "text/html; charset=utf-8", cache="no-cache") def jbody(h): return h.body_json(limit=8 * 1024 * 1024) def need_account(h): a = session_account(h) if not a: raise ValueError("Please sign in first.") return a def limit(h, key, n, window=3600): k = "ba:%s:%s" % (key, h.ip()) if S.too_many([k], [n], window=window): raise ValueError("Too many tries for now. Please wait a while and try again.") S.add_fail(k) def p_config(h, q): c0 = cfg() assets = pay_assets(c0) sp = c0.get("sponsor") or {} return h.send(200, { "coins": [{"id": k, "name": coins.COINS[k]["name"]} for k in coins.ORDER], "limits": {k: c0[k] for k in ("free_coins", "free_links", "pro_coins", "pro_links", "min_free_name", "min_name")}, "idle": {"link_days": LINK_IDLE // 86400, "page_days": PAGE_IDLE // 86400, "keep_days": EXPIRED_KEEP // 86400}, "items": {k: {"name": ITEMS[k]["name"], "for": ITEMS[k]["for"], "blurb": ITEMS[k]["blurb"], "usd": str(v["usd"]), "days": int(v.get("days") or 0), "on": bool(v.get("on"))} for k, v in c0["items"].items() if k in ITEMS}, "assets": [{"id": a, "name": pay.ASSETS[a]["name"], "symbol": pay.symbol(a), "wait": pay.ASSETS[a]["wait"]} for a in assets], "pay_on": bool(assets), "min_pay": str(c0["min_pay"]), "min_topup": str(c0["min_topup"]), "max_topup": str(c0["max_topup"]), "bonus_from": str(c0["bonus_from"]), "bonus_pct": int(c0["bonus_pct"] or 0), "tips": bool(c0.get("tips")) and bool(assets), "themes": {k: (v[0] if v else "") for k, v in THEMES.items()}, "sponsor": {"text": sp["text"], "url": sp["url"]} if sponsor_html() else None, "refs": [r for r in (c0.get("refs") or []) if r.get("name") and str(r.get("url") or "").startswith("https://")]}) def p_check_name(h, q): b = jbody(h) name = str(b.get("name") or "").strip().lower() c0 = cfg() why = name_problem(name, short_ok=True) short = not why and is_short(name, c0) if not why: with db() as c: if name_taken(c, name, but_page=int(b.get("page_id") or 0) or None): why = "That name is taken." it = c0["items"].get(name_sku(name)) if short else None if short and not why and not (it and it.get("on")): why = "Short names aren't available right now." return h.send(200, {"ok": not why, "why": why, "short": bool(short and not why), "usd": str(it["usd"]) if it else None, "days": int(it.get("days") or 0) if it else None, "request": bool(why) and can_request(name, c0)}) def p_name_request(h, q): """Ask for a reserved name. The only place BitAddy takes an email address, and only so the owner can answer.""" limit(h, "namereq", 5) b = jbody(h) name = str(b.get("name") or "").strip().lower() email = str(b.get("email") or "").strip() if not can_request(name): raise ValueError("That name can't be requested.") if not EMAIL_RE.match(email) or len(email) > 200: raise ValueError("That email address doesn't look right.") with db() as c: if c.execute("SELECT COUNT(*) FROM ba_requests WHERE status='open'").fetchone()[0] >= 3000: raise ValueError("We have a lot of requests right now. Please try again in a few days.") c.execute("INSERT OR IGNORE INTO ba_requests(ts,name,email,note) VALUES(?,?,?,?)", (now(), name, email.lower(), clean_text(b.get("note"), 300))) S.audit("visitor", "BitAddy name request", name) return h.send(200, {"ok": True}) def p_detect(h, q): b = jbody(h) return h.send(200, {"coins": coins.detect(b.get("address"))}) def p_link(h, q): """Short link for one address.""" limit(h, "link", 30) b = jbody(h) coin = str(b.get("coin") or "").upper() if not coin: d = coins.detect(b.get("address")) 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 = coins.check(coin, b.get("address")) if not addr: raise ValueError(why) if blocked("address", addr): raise ValueError("That address can't be used on BitAddy.") a = session_account(h) label = clean_text(b.get("label"), 40) with db() as c: if a: r = c.execute("SELECT code FROM ba_links WHERE account_id=? AND coin=? AND address=? AND COALESCE(label,'')=?", (a["id"], coin, addr, label)).fetchone() else: r = c.execute("SELECT code FROM ba_links WHERE account_id IS NULL AND coin=? AND address=? AND COALESCE(label,'')=?", (coin, addr, label)).fetchone() if r: # the same address and label again: the same link, and asking for it counts as using it (an expired one comes back) c.execute("UPDATE ba_links SET last_visit=? WHERE code=?", (now(), r["code"])) return h.send(200, {"code": r["code"], "existing": True}) for _ in range(20): code = "".join(secrets.choice(CODE_ALPHABET) for _ in range(6)) if code != code.lower() and code not in names.EXAMPLE_CODES and not c.execute("SELECT 1 FROM ba_links WHERE code=?", (code,)).fetchone(): break c.execute("INSERT INTO ba_links(code,account_id,coin,address,label,created,last_visit,creator) VALUES(?,?,?,?,?,?,?,?)", (code, a["id"] if a else None, coin, addr, label, now(), now(), hashlib.sha256((h.ip() + S.CFG["DATA_DIR"]).encode()).hexdigest()[:12])) return h.send(200, {"code": code}) def p_page_create(h, q): limit(h, "page", 10) b = jbody(h) a = session_account(h) c0 = cfg() name = str(b.get("name") or "").strip().lower() why = name_problem(name) if why: raise ValueError(why) cl = check_coins(b.get("coins") or [], int(c0["free_coins"])) for x in cl: x["verified"] = False if not cl: raise ValueError("Add at least one address.") ll = check_links(b.get("links") or [], int(c0["free_links"])) key = None headers = {} with db() as c: if name_taken(c, name): raise ValueError("That name is taken.") if a: aid = a["id"] if c.execute("SELECT COUNT(*) FROM ba_pages WHERE account_id=?", (aid,)).fetchone()[0] >= 10: raise ValueError("One owner key can hold up to 10 pages.") else: aid = new_account(c) key = new_owner_key() add_ident(c, aid, "key", S.tok_hash(key), "Owner key") c.execute("INSERT INTO ba_pages(account_id,name,title,bio,coins,links,created,updated,last_visit) VALUES(?,?,?,?,?,?,?,?,?)", (aid, name, clean_text(b.get("title"), 60) or name, clean_text(b.get("bio"), 280), json.dumps(cl), json.dumps(ll), now(), now(), now())) if not a: headers["Set-Cookie"] = make_session(h, aid) return h.send(200, {"ok": True, "name": name, "key": key}, headers=headers) def p_me(h, q): a = session_account(h) if not a: return h.send(200, {"signed_in": False}) with db() as c: pages = [dict(r) for r in c.execute("SELECT * FROM ba_pages WHERE account_id=? ORDER BY created", (a["id"],))] links = [dict(r) for r in c.execute("SELECT * FROM ba_links WHERE account_id=? ORDER BY created DESC", (a["id"],))] ids = [{"kind": r["kind"], "label": r["label"], "value": (r["value"] if r["kind"] == "wallet" else ""), "created": r["created"]} for r in c.execute("SELECT * FROM ba_idents WHERE account_id=? AND kind IN ('key','wallet')", (a["id"],))] for p in pages: p["coins"] = json.loads(p["coins"]) p["links"] = json.loads(p["links"]) pu, nu = perk_until(c, "page", p["id"], "pro"), perk_until(c, "page", p["id"], "name") p["pro"] = pu is not None and (pu == 0 or pu > now()) p["pro_until"] = pu p["short"] = is_short(p["name"]) p["name_until"] = nu p["name_back"] = (nu + NAME_GRACE) if nu else None fn = c.execute("SELECT free_name FROM ba_names WHERE page_id=?", (p["id"],)).fetchone() p["free_name"] = fn["free_name"] if fn else None p["expires_at"] = None if p["pro"] else idle_since(p) + PAGE_IDLE p["expired"] = page_expired(c, p) p["deleted_at"] = (p["expires_at"] + EXPIRED_KEEP) if p["expired"] else None for l in links: ku = perk_until(c, "link", l["code"], "keep") l["keep"] = ku is not None and (ku == 0 or ku > now()) l["keep_until"] = ku l["expires_at"] = None if l["keep"] else idle_since(l) + LINK_IDLE l["expired"] = link_expired(c, l) l["deleted_at"] = (l["expires_at"] + EXPIRED_KEEP) if l["expired"] else None return h.send(200, {"signed_in": True, "pages": pages, "links": links, "idents": ids}) def own_page(c, a, pid): p = c.execute("SELECT * FROM ba_pages WHERE id=? AND account_id=?", (int(pid or 0), a["id"])).fetchone() if not p: raise ValueError("Page not found.") return p def p_page_save(h, q): a = need_account(h) b = jbody(h) c0 = cfg() with db() as c: p = own_page(c, a, b.get("id")) pro = page_pro(c, p["id"]) old = {x["address"]: x.get("verified") for x in json.loads(p["coins"])} cl = check_coins(b.get("coins") or [], int(c0["pro_coins"] if pro else c0["free_coins"])) if not cl: raise ValueError("Add at least one address.") for x in cl: x["verified"] = bool(old.get(x["address"])) # a tick only survives if the address didn't change ll = check_links(b.get("links") or [], int(c0["pro_links"] if pro else c0["free_links"])) theme = b.get("theme") if b.get("theme") in THEMES and pro else p["theme"] avatar = p["avatar"] if "avatar" in b and pro: avatar = b["avatar"] if (b["avatar"] and re.fullmatch(r"[a-f0-9]{32}\.(png|jpg|webp)", b["avatar"])) else None c.execute("UPDATE ba_pages SET title=?,bio=?,coins=?,links=?,theme=?,avatar=?,updated=?,last_visit=? WHERE id=?", (clean_text(b.get("title"), 60) or p["name"], clean_text(b.get("bio"), 280), json.dumps(cl), json.dumps(ll), theme, avatar, now(), now(), p["id"])) # saving counts as using the page return h.send(200, {"ok": True}) def p_revive(h, q): """The owner brings an expired page or short link back. Free.""" a = need_account(h) limit(h, "revive", 30) b = jbody(h) with db() as c: if b.get("code"): n = c.execute("UPDATE ba_links SET last_visit=? WHERE code=? AND account_id=?", (now(), str(b["code"]), a["id"])).rowcount else: n = c.execute("UPDATE ba_pages SET last_visit=? WHERE id=?", (now(), own_page(c, a, b.get("id"))["id"])).rowcount if not n: raise ValueError("Not found.") return h.send(200, {"ok": True}) def p_page_rename(h, q): """Change a page's address to another free name. (Short names are bought, see resolve_item.) A page that had a paid short name gives it up by doing this.""" a = need_account(h) b = jbody(h) name = str(b.get("name") or "").strip().lower() why = name_problem(name) if why: raise ValueError(why) with db() as c: p = own_page(c, a, b.get("id")) if name_taken(c, name, but_page=p["id"]): raise ValueError("That name is taken.") c.execute("UPDATE ba_pages SET name=?, updated=? WHERE id=?", (name, now(), p["id"])) c.execute("DELETE FROM ba_names WHERE page_id=?", (p["id"],)) c.execute("DELETE FROM ba_perks WHERE kind='page' AND ref=? AND sku='name'", (str(p["id"]),)) return h.send(200, {"ok": True, "name": name}) def p_page_delete(h, q): a = need_account(h) b = jbody(h) with db() as c: p = own_page(c, a, b.get("id")) c.execute("DELETE FROM ba_pages WHERE id=?", (p["id"],)) drop_page_extras(c, p["id"]) return h.send(200, {"ok": True}) def p_link_delete(h, q): a = need_account(h) b = jbody(h) code = str(b.get("code") or "") with db() as c: if c.execute("DELETE FROM ba_links WHERE code=? AND account_id=?", (code, a["id"])).rowcount: c.execute("DELETE FROM ba_perks WHERE kind='link' AND ref=?", (code,)) return h.send(200, {"ok": True}) def p_avatar(h, q): a = need_account(h) limit(h, "avatar", 30) b = jbody(h) with db() as c: p = own_page(c, a, b.get("page_id")) if not page_pro(c, p["id"]): raise ValueError("A picture comes with a Pro page.") raw = base64.b64decode(b.get("data") or "") ext = {"image/png": "png", "image/jpeg": "jpg", "image/webp": "webp"}.get(b.get("type")) sig_ok = raw.startswith(b"\x89PNG") or raw.startswith(b"\xff\xd8\xff") or (raw[:4] == b"RIFF" and raw[8:12] == b"WEBP") if not ext or not sig_ok: raise ValueError("Pictures only (PNG, JPG or WebP).") if len(raw) > 2 * 1024 * 1024: raise ValueError("Pictures up to 2 MB.") name = "%s.%s" % (secrets.token_hex(16), ext) (Path(S.CFG["DATA_DIR"]) / "bitaddy-img" / name).write_bytes(raw) return h.send(200, {"avatar": name}) def p_signin_key(h, q): limit(h, "key", 20) key = str(jbody(h).get("key") or "").strip() aid = account_for_ident("key", S.tok_hash(key)) if key.startswith("ba-") else None if not aid: raise ValueError("That owner key doesn't match any page.") return h.send(200, {"ok": True}, headers={"Set-Cookie": make_session(h, aid)}) def p_signin_nonce(h, q): limit(h, "nonce", 60) n = secrets.token_hex(12) with db() as c: c.execute("INSERT INTO ba_nonces(nonce,expires) VALUES(?,?)", (n, now() + 600)) return h.send(200, {"nonce": n, "message": sign_message(n)}) def p_signin_wallet(h, q): limit(h, "wallet", 30) b = jbody(h) chain, addr = verify_wallet(b) ident = "%s:%s" % (chain, addr) a = session_account(h) with db() as c: r = c.execute("SELECT account_id FROM ba_idents WHERE kind='wallet' AND value=?", (ident,)).fetchone() if a and b.get("link"): add_ident(c, a["id"], "wallet", ident, "%s wallet" % coin_name(chain)) aid = a["id"] elif r: aid = r["account_id"] else: aid = new_account(c) add_ident(c, aid, "wallet", ident, "%s wallet" % coin_name(chain)) return h.send(200, {"ok": True, "address": addr}, headers={"Set-Cookie": make_session(h, aid)}) def p_newkey(h, q): """Signed in: make a fresh owner key (replaces old keys).""" a = need_account(h) key = new_owner_key() with db() as c: c.execute("DELETE FROM ba_idents WHERE account_id=? AND kind='key'", (a["id"],)) add_ident(c, a["id"], "key", S.tok_hash(key), "Owner key") return h.send(200, {"key": key}) def p_ident_remove(h, q): a = need_account(h) b = jbody(h) with db() as c: n = c.execute("SELECT COUNT(*) FROM ba_idents WHERE account_id=? AND kind IN ('key','wallet')", (a["id"],)).fetchone()[0] if n <= 1: raise ValueError("Keep at least one way to open your pages.") if b.get("kind") not in ("key", "wallet"): raise ValueError("Unknown.") c.execute("DELETE FROM ba_idents WHERE account_id=? AND kind=? AND (value=? OR kind='key')", (a["id"], str(b.get("kind") or ""), str(b.get("value") or ""))) return h.send(200, {"ok": True}) def p_verify_address(h, q): a = need_account(h) limit(h, "verify", 30) b = jbody(h) with db() as c: p = own_page(c, a, b.get("page_id")) cl = json.loads(p["coins"]) i = int(b.get("index", -1)) if not (0 <= i < len(cl)): raise ValueError("Address not found.") if cl[i]["coin"] not in ("ADA", "ETH", "SOL"): raise ValueError("Wallet checks work for Cardano, Ethereum and Solana addresses for now.") b["chain"] = cl[i]["coin"] verify_wallet(b, expect_address=cl[i]["address"]) cl[i]["verified"] = True with db() as c: c.execute("UPDATE ba_pages SET coins=?, updated=? WHERE id=?", (json.dumps(cl), now(), p["id"])) return h.send(200, {"ok": True}) def p_signout(h, q): t = h.cookie("ba_sess") if t: with db() as c: c.execute("DELETE FROM ba_sessions WHERE token=?", (S.tok_hash(t),)) return h.send(200, {"ok": True}, headers={"Set-Cookie": "ba_sess=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0"}) REASONS = {"scam": "Scam or fraud", "impersonation": "Pretends to be someone else", "wrong": "Wrong or stolen address", "abuse": "Offensive or harmful", "other": "Something else"} def p_report(h, q): limit(h, "report", 10) b = jbody(h) kind = b.get("kind") target = str(b.get("target") or "")[:40] reason = b.get("reason") if kind not in ("page", "link") or reason not in REASONS or not target: raise ValueError("Pick a reason.") reporter = hashlib.sha256((h.ip() + "|" + S.CFG["DATA_DIR"]).encode()).hexdigest()[:16] with db() as c: exists = c.execute("SELECT 1 FROM ba_pages WHERE name=?", (target,)).fetchone() if kind == "page" else \ c.execute("SELECT 1 FROM ba_links WHERE code=?", (target,)).fetchone() if not exists: raise ValueError("Not found.") if c.execute("SELECT 1 FROM ba_reports WHERE kind=? AND target=? AND reporter=? AND status='open'", (kind, target, reporter)).fetchone(): return h.send(200, {"ok": True, "again": True}) c.execute("INSERT INTO ba_reports(ts,kind,target,reason,note,reporter) VALUES(?,?,?,?,?,?)", (now(), kind, target, reason, clean_text(b.get("note"), 500), reporter)) n = c.execute("SELECT COUNT(DISTINCT reporter) FROM ba_reports WHERE kind=? AND target=? AND status='open'", (kind, target)).fetchone()[0] auto = int(cfg()["autohide"]) if auto and n >= auto: if kind == "page": c.execute("UPDATE ba_pages SET hidden=1, hidden_reason=? WHERE name=? AND hidden=0", ("auto: %d reports" % n, target)) else: c.execute("UPDATE ba_links SET hidden=1, hidden_reason=? WHERE code=? AND hidden=0", ("auto: %d reports" % n, target)) S.audit("visitor", "BitAddy report", "%s %s: %s" % (kind, target, REASONS[reason])) return h.send(200, {"ok": True}) def topup_row(c, token): token = str(token or "").strip() m = re.search(r"bt-[A-Za-z0-9_\-]{20,40}", token) # also accepts the whole link pasted in return c.execute("SELECT * FROM ba_topups WHERE token=?", (S.tok_hash(m.group(0)),)).fetchone() if m else None def topup_public(c, t): hist = [dict(r) for r in c.execute("SELECT ts, cents, what FROM ba_ledger WHERE topup_id=? ORDER BY id DESC LIMIT 40", (t["id"],))] return {"cents": t["cents"], "balance": money(t["cents"]), "created": t["created"], "history": hist} def p_topup_new(h, q): limit(h, "topupnew", 10) token = "bt-" + secrets.token_urlsafe(18) with db() as c: c.execute("INSERT INTO ba_topups(token,created) VALUES(?,?)", (S.tok_hash(token), now())) return h.send(200, {"token": token}) def p_topup(h, q): limit(h, "topup", 120) with db() as c: t = topup_row(c, jbody(h).get("token")) if not t: raise ValueError("That top-up link isn't known. Check that you pasted all of it.") return h.send(200, topup_public(c, t)) def p_spend(h, q): """Pay for an extra from a top-up link's balance: no waiting for a blockchain.""" limit(h, "spend", 60) b = jbody(h) sku, usd, what, label = resolve_item(h, b) cents = int(usd * 100) with db() as c: t = topup_row(c, b.get("token")) if not t: raise ValueError("That top-up link isn't known. Check that you pasted all of it.") if not c.execute("UPDATE ba_topups SET cents=cents-?, last_used=? WHERE id=? AND cents>=?", (cents, now(), t["id"], cents)).rowcount: raise ValueError("This top-up link holds $%s, and this costs $%s. Add to it first." % (money(t["cents"]), money(cents))) c.execute("INSERT INTO ba_ledger(topup_id,ts,cents,what,ref) VALUES(?,?,?,?,?)", (t["id"], now(), -cents, label, sku)) try: res = apply_item(what, "topup:%d" % t["id"]) except ValueError as e: with db() as c: # give the money back c.execute("UPDATE ba_topups SET cents=cents+? WHERE id=?", (cents, t["id"])) c.execute("INSERT INTO ba_ledger(topup_id,ts,cents,what,ref) VALUES(?,?,?,?,?)", (t["id"], now(), cents, "Returned: " + label, sku)) raise ValueError("That didn't work (%s). Nothing was taken from your top-up link." % e) S.audit("visitor", "BitAddy top-up spent", "%s, $%s" % (label, money(cents))) with db() as c: left = c.execute("SELECT cents FROM ba_topups WHERE id=?", (t["id"],)).fetchone()["cents"] return h.send(200, {"ok": True, "result": res, "balance": money(left)}) def p_order(h, q): limit(h, "order", 30) b = jbody(h) c0 = cfg() kind = b.get("kind") asset = str(b.get("asset") or "").upper() if kind == "item": sku, usd, what, label = resolve_item(h, b) return h.send(200, new_order("item", usd, what, label, asset)) if kind == "topup": usd = dollars(b.get("usd"), c0["min_topup"], c0["max_topup"], "Top-up") with db() as c: t = topup_row(c, b.get("token")) if not t: raise ValueError("That top-up link isn't known. Check that you pasted all of it.") cents = int(usd * 100) bonus = cents * int(c0["bonus_pct"] or 0) // 100 if usd >= Decimal(str(c0["bonus_from"])) else 0 label = "Top-up of $%s" % money(cents) + (" (+ $%s extra)" % money(bonus) if bonus else "") return h.send(200, new_order("topup", usd, {"topup": t["id"]}, label, asset, credit=cents + bonus)) if kind == "tip": if not c0.get("tips"): raise ValueError("Tips are switched off right now.") usd = dollars(b.get("usd"), c0["min_pay"], 1000, "Tip") return h.send(200, new_order("tip", usd, {}, "Tip for BitAddy", asset)) raise ValueError("Unknown order.") def p_order_status(h, q): with db() as c: o = c.execute("SELECT * FROM ba_pay WHERE id=?", (q.get("id", ""),)).fetchone() if not o or not hmac.compare_digest(o["secret"], S.tok_hash(q.get("s", ""))): raise ValueError("Order not found.") if o["status"] == "pending": threading.Thread(target=check_payments, daemon=True).start() return h.send(200, order_public(o)) def p_stats(h, q): """Day-by-day visits of one Pro page, last 30 days.""" a = need_account(h) start = (datetime.now(timezone.utc) - timedelta(days=29)).strftime("%Y-%m-%d") with db() as c: p = own_page(c, a, q.get("page")) if not page_pro(c, p["id"]): raise ValueError("Day-by-day counts come with a Pro page.") rows = [dict(r) for r in c.execute("SELECT day, views, scans FROM ba_daily WHERE day>=? AND target=? ORDER BY day", (start, "p:" + p["name"]))] return h.send(200, {"rows": rows}) # ------------------------------------------------------------------ funnel steps (see SCHEMA note) EV_STEPS = { "view", "leave", "tab_page", "link_start", "link_made", "page_start", "page_made", "copy_link", "open_made", "save_key", "problem", "pay_open", "pay_closed", "pay_coin", "pay_topup", "paid", "signin", "name_request", "upage", "u_copy", "u_qr", "u_amount", "u_make", "u_report", "share_link", "qr_save", "u_share", "u_qr_save", "alert_start", "alert_made", "alert_test", "req_start", "req_made", "u_req_paid", "cards_print", } EV_VISIT_RE = re.compile(r"^[a-z0-9]{16}$") EV_TAG_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,39}$") EV_LIMIT = 600 # steps per connection per hour; plenty for a person, cheap to check (kept in memory, nothing written) EV_RATE = {} EV_KEEP_DAYS = 400 def ev_scrub(s, n=60): """Free text in a step's detail (our own error messages, coin names): no long tokens like addresses or keys survive.""" s = re.sub(r"[A-Za-z0-9_\-]{20,}", "…", str(s or "")) return re.sub(r"\s+", " ", s).strip()[:n] def ev_rate_ok(ip): t = now() if len(EV_RATE) > 5000: for k in [k for k, v in EV_RATE.items() if v[0] < t - 3600]: EV_RATE.pop(k, None) w = EV_RATE.get(ip) if not w or w[0] < t - 3600: EV_RATE[ip] = [t, 1] return True w[1] += 1 return w[1] <= EV_LIMIT def p_ev(h, q): """One step of a visit. Always answers 204 (even when the step is ignored), so the page never waits on it.""" ua = h.headers.get("User-Agent", "") if not ua or S.BOT_RE.search(ua) or not ev_rate_ok(h.ip()): return h.send(204, b"", "text/plain") try: b = h.body_json(limit=2000) except Exception: return h.send(204, b"", "text/plain") if not isinstance(b, dict): return h.send(204, b"", "text/plain") visit, step = str(b.get("v") or ""), str(b.get("s") or "") if not EV_VISIT_RE.match(visit) or step not in EV_STEPS: return h.send(204, b"", "text/plain") path = str(b.get("p") or "/")[:100].split("?")[0].split("#")[0] if not path.startswith("/"): path = "/" tag = str(b.get("tag") or "").lower()[:40] tag = tag if EV_TAG_RE.match(tag) else "" ref = "" try: ref = (urllib.parse.urlsplit(str(b.get("r") or "")[:200]).hostname or "").lower() except Exception: pass if ref.startswith("www."): ref = ref[4:] if ref in (S.CFG["SITE_DOMAIN"], "127.0.0.1", "localhost"): ref = "" w = str(b.get("w") or "0") w = int(w) if w.isdigit() else 0 device = "phone" if 0 < w < 700 else ("tablet" if w < 1100 and w else ("computer" if w else "")) country = (h.headers.get("CF-IPCountry") or "")[:2].upper() if country in ("XX", "T1"): country = "" detail = ev_scrub(b.get("d")) if step == "leave": # seconds since the visit started detail = str(min(int(detail), 86400)) if detail.isdigit() else "" day = datetime.now(timezone.utc).strftime("%Y-%m-%d") with db() as c: c.execute("INSERT INTO ba_events(ts,day,visit,step,detail,path,tag,ref,device,country) VALUES(?,?,?,?,?,?,?,?,?,?)", (now(), day, visit, step, detail, path, tag, ref, device, country)) return h.send(204, b"", "text/plain") SHARED = {"copy_link", "open_made", "share_link", "qr_save"} # the signs we can see that someone passed their new link on # the two funnels, in order: (label, steps that count as reaching it) FUNNEL_MAKE = [("Visited BitAddy", None), ("Started making a link or page", {"link_start", "page_start"}), ("Made a link or page", {"link_made", "page_made"}), ("Copied, shared or opened their new link", SHARED)] FUNNEL_PAY = [("Looked at paid extras", {"pay_open", "pay_closed", "@pricing"}), ("Picked a coin to pay with", {"pay_coin", "pay_topup"}), ("Paid", {"paid"})] MAKE_ADVICE = { 1: "Most visitors leave without starting. Make the first step more obvious: the address box at the very top, with a one-line example.", 2: "People start but don't finish. Look at the most common problems below, and make the form shorter.", 3: "People make a link but don't copy, share or open it. Check that Copy and Share are easy to see right after a link is made.", } def funnel_data(days, only_src=""): days = max(1, min(int(days), 365)) start = (datetime.now(timezone.utc) - timedelta(days=days - 1)).strftime("%Y-%m-%d") since = now() - days * 86400 V = {} with db() as c: rows = c.execute("SELECT visit, step, detail, path, tag, ref, device, ts FROM ba_events WHERE day>=? ORDER BY id LIMIT 300000", (start,)).fetchall() truth = { "links": c.execute("SELECT COUNT(*) FROM ba_links WHERE created>=?", (since,)).fetchone()[0], "pages": c.execute("SELECT COUNT(*) FROM ba_pages WHERE created>=?", (since,)).fetchone()[0], "links_used": c.execute("SELECT COUNT(*) FROM ba_links WHERE created>=? AND views+scans>0", (since,)).fetchone()[0], "pages_used": c.execute("SELECT COUNT(*) FROM ba_pages WHERE created>=? AND views+scans>0", (since,)).fetchone()[0], "paid": [dict(r) for r in c.execute("SELECT kind, COUNT(*) n, ROUND(SUM(CAST(usd AS REAL)),2) usd FROM ba_pay WHERE status='paid' AND paid_at>=? " "GROUP BY kind ORDER BY n DESC", (since,))], } for r in rows: v = V.get(r["visit"]) if v is None: v = V[r["visit"]] = {"steps": set(), "src": "", "device": r["device"] or "", "secs": 0, "upage_only": True, "made_kind": set(), "n": 0, "first": ""} st = r["step"] if not v["src"] and (r["tag"] or r["ref"]): v["src"] = ("tag:" + r["tag"]) if r["tag"] else r["ref"] if st == "leave": v["secs"] = max(v["secs"], int(r["detail"] or 0) if (r["detail"] or "").isdigit() else 0) continue v["steps"].add(st) v["n"] += 1 if not v["first"] and not (st.startswith("u_")): # the first page opening; small actions on it can arrive out of order v["first"] = st if st == "view" and (r["path"] or "").startswith("/pricing"): v["steps"].add("@pricing") if st not in ("upage", "u_copy", "u_qr", "u_amount", "u_make", "u_report", "u_share", "u_qr_save"): v["upage_only"] = False if st in ("link_made", "page_made"): v["made_kind"].add(st) v.setdefault("details", []).append((st, r["detail"] or "")) # visits that only looked at someone's BitAddy page are counted separately (they came for that person, not for BitAddy) site = {k: v for k, v in V.items() if not v["upage_only"]} upage = [v for v in V.values() if v["first"] == "upage"] # arrived through someone's page or link (not a maker opening their own) for v in V.values(): if not v["src"]: v["src"] = "(direct)" if only_src: site = {k: v for k, v in site.items() if v["src"] == only_src} n = len(site) def reached(v, steps): return steps is None or bool(v["steps"] & steps) def funnel(spec, base): out, prev = [], None for i, (label, steps) in enumerate(spec): k = sum(1 for v in base if reached(v, steps)) out.append({"label": label, "n": k, "of_all": round(100 * k / n, 1) if n else 0, "of_prev": (round(100 * k / prev, 1) if prev else 0) if i else 100}) prev = k return out vals = list(site.values()) make, pay = funnel(FUNNEL_MAKE, vals), funnel(FUNNEL_PAY, vals) # where each visit ended def end_of(v): s = v["steps"] if "paid" in s: return "Paid for something" if s & {"pay_coin", "pay_topup"}: return "Left during a payment" if s & SHARED: return "Made and copied, shared or opened a link" if s & {"link_made", "page_made"}: return "Made something, then left without copying it" if s & {"link_start", "page_start"}: return "Started making something, didn't finish" if "signin" in s or "name_request" in s: return "Opened My links or asked for a name" if s & {"pay_open", "pay_closed", "@pricing"}: return "Looked at prices, then left" return "Only looked around, then left" ends = {} for v in vals: e = end_of(v) ends[e] = ends.get(e, 0) + 1 # sources src = {} for v in vals: s = src.setdefault(v["src"], {"k": v["src"], "visits": 0, "made": 0, "shared": 0, "paid": 0}) s["visits"] += 1 s["made"] += 1 if v["steps"] & {"link_made", "page_made"} else 0 s["shared"] += 1 if v["steps"] & SHARED else 0 s["paid"] += 1 if "paid" in v["steps"] else 0 sources = sorted(src.values(), key=lambda x: (-x["visits"], x["k"]))[:25] for x in sources: # ai = an AI assistant, search = a search engine, social, tag = one of the owner's tagged links, site, direct x["kind"] = agent.source_kind(x["k"]) def tally(step, fmt=None): t = {} steps_ = step if isinstance(step, tuple) else (step,) for v in vals: for st, d in v.get("details", []): if st in steps_: k = fmt(d) if fmt else d if k: t[k] = t.get(k, 0) + 1 return [{"k": k, "n": x} for k, x in sorted(t.items(), key=lambda kv: -kv[1])[:10]] secs = sorted(v["secs"] for v in vals if v["secs"]) devices = {} for v in vals: devices[v["device"] or "unknown"] = devices.get(v["device"] or "unknown", 0) + 1 feats = { "tab_page": sum(1 for v in vals if "tab_page" in v["steps"]), "links_made": sum(1 for v in vals if "link_made" in v["steps"]), "pages_made": sum(1 for v in vals if "page_made" in v["steps"]), "save_key": sum(1 for v in vals if "save_key" in v["steps"]), "signin": sum(1 for v in vals if "signin" in v["steps"]), "name_request": sum(1 for v in vals if "name_request" in v["steps"]), "pay_closed": sum(1 for v in vals if "pay_closed" in v["steps"]), "share_link": sum(1 for v in vals if "share_link" in v["steps"]), "qr_save": sum(1 for v in vals if "qr_save" in v["steps"]), } spread = {"views": len(upage), "make": sum(1 for v in upage if "u_make" in v["steps"]), "copy": sum(1 for v in upage if "u_copy" in v["steps"]), "qr": sum(1 for v in upage if "u_qr" in v["steps"]), "amount": sum(1 for v in upage if "u_amount" in v["steps"]), "report": sum(1 for v in upage if "u_report" in v["steps"]), "share": sum(1 for v in upage if v["steps"] & {"u_share", "u_qr_save"})} res = {"days": days, "visits": n, "src": only_src, "make": make, "pay": pay, "ends": sorted(({"k": k, "n": x} for k, x in ends.items()), key=lambda e: -e["n"]), "sources": sources, "coins": tally("link_made"), "pay_for": tally(("pay_open", "pay_closed")), "paid_for": tally("paid"), "problems": tally("problem", problem_label), "devices": sorted(({"k": k, "n": x} for k, x in devices.items()), key=lambda e: -e["n"]), "median_secs": secs[len(secs) // 2] if secs else 0, "features": feats, "spread": spread, "truth": truth} res["insights"] = funnel_insights(res) return res PROBLEM_WHERE = {"page": "Making a page", "link": "Making a short link"} def problem_label(d): where, _, msg = d.partition(": ") return ("%s: %s" % (PROBLEM_WHERE[where], msg)) if msg and where in PROBLEM_WHERE else d def pct(a, b): return round(100 * a / b) if b else 0 def funnel_insights(r): """Plain-word findings, most useful first. Each is {text, kind}: kind 'act' = do something, 'info' = good to know, 'warn' = data caveat.""" out, n, make, pay = [], r["visits"], r["make"], r["pay"] if n == 0: return [{"kind": "warn", "text": "No visits recorded in this period yet. Steps are counted from now on; check back after people have used the site."}] if n < 30: out.append({"kind": "warn", "text": "Only %d visit%s so far: too few to trust the percentages. Treat everything below as early hints." % (n, "" if n == 1 else "s")}) # the biggest drop in make & share, once enough people reached the step before it worst = None for i in range(1, len(make)): if make[i - 1]["n"] >= 5: lost = 100 - make[i]["of_prev"] if worst is None or lost > worst[1]: worst = (i, lost) if worst and worst[1] >= 40: i = worst[0] out.append({"kind": "act", "text": "Biggest drop: of the %d who %s, only %d (%d%%) went on to %s. %s" % ( make[i - 1]["n"], make[i - 1]["label"].lower(), make[i]["n"], make[i]["of_prev"], make[i]["label"].lower(), MAKE_ADVICE[i])}) made = make[2]["n"] if made: out.append({"kind": "info", "text": "%d of %d visits (%d%%) made a link or page." % (made, n, pct(made, n))}) # sources worth more (or less) of your time with_enough = [s for s in r["sources"] if s["visits"] >= 10] rate = made / n if n else 0 best = max(with_enough, key=lambda s: s["made"] / s["visits"], default=None) if best and rate and best["made"] / best["visits"] >= 1.5 * rate and best["made"] >= 3: out.append({"kind": "act", "text": "%s brings visitors who make links %.1f× more often than average (%d of %d). Put more of your effort there." % ( src_label(best["k"]), (best["made"] / best["visits"]) / rate, best["made"], best["visits"])}) for s in with_enough: if s["visits"] >= 15 and s["made"] == 0 and s["k"] != "(direct)": out.append({"kind": "act", "text": "%s sent %d visits and none made anything. Check what those visitors expect to find." % (src_label(s["k"]), s["visits"])}) if r["problems"]: p = r["problems"][0] out.append({"kind": "act", "text": "Most common problem people hit: \"%s\" (%d time%s). Clearer wording or a smarter form here helps the most." % ( p["k"], p["n"], "" if p["n"] == 1 else "s")}) if r["features"]["pay_closed"]: out.append({"kind": "act", "text": "%d visit%s tried to buy an extra while paying was switched off. Add your receiving wallets to start selling." % ( r["features"]["pay_closed"], "" if r["features"]["pay_closed"] == 1 else "s")}) if pay[0]["n"] >= 10 and pay[1]["n"] == 0: out.append({"kind": "act", "text": "%d visits looked at paid extras but nobody picked a coin. The price or the offer may not fit what people want." % pay[0]["n"]}) elif pay[1]["n"] >= 5 and pay[2]["n"] == 0: out.append({"kind": "act", "text": "%d visits started paying but none finished. Walk through a payment yourself to see where it gets hard." % pay[1]["n"]}) elif pay[2]["n"]: out.append({"kind": "info", "text": "%d visit%s paid for something (%d%% of visits)." % (pay[2]["n"], "" if pay[2]["n"] == 1 else "s", pct(pay[2]["n"], n))}) f = r["features"] if n >= 50 and f["tab_page"] < 0.05 * n: out.append({"kind": "info", "text": "Only %d%% of visitors open the \"Page for all my coins\" tab. Either pages aren't wanted, or the tab is easy to miss." % pct(f["tab_page"], n)}) if f["links_made"] + f["pages_made"] >= 10 and f["pages_made"] and f["save_key"] < 0.5 * f["pages_made"]: out.append({"kind": "act", "text": "Most people who make a page don't copy or download their owner key, so they may lose the way back in."}) sp = r["spread"] if sp["views"]: out.append({"kind": "info", "text": "%d visit%s came to look at someone's BitAddy page or link; %d (%d%%) clicked \"Make your own\"." % ( sp["views"], "" if sp["views"] == 1 else "s", sp["make"], pct(sp["make"], sp["views"]))}) if r["coins"]: out.append({"kind": "info", "text": "Most new links are for %s (%d of %d)." % (r["coins"][0]["k"], r["coins"][0]["n"], sum(x["n"] for x in r["coins"]))}) return out def src_label(k): return ("Your \"%s\" link" % k[4:]) if k.startswith("tag:") else ("Direct visits" if k == "(direct)" else k) def a_funnel(h, m): days = int(h.q.get("days", 7)) if str(h.q.get("days", 7)).isdigit() else 7 src = str(h.q.get("src") or "")[:80] return h.send(200, funnel_data(days, src)) PUBLIC = { ("GET", "config"): p_config, ("POST", "check_name"): p_check_name, ("POST", "detect"): p_detect, ("POST", "link"): p_link, ("POST", "page_create"): p_page_create, ("GET", "me"): p_me, ("POST", "page_save"): p_page_save, ("POST", "page_rename"): p_page_rename, ("POST", "page_delete"): p_page_delete, ("POST", "link_delete"): p_link_delete, ("POST", "avatar"): p_avatar, ("POST", "signin_key"): p_signin_key, ("GET", "signin_nonce"): p_signin_nonce, ("POST", "signin_wallet"): p_signin_wallet, ("POST", "newkey"): p_newkey, ("POST", "ident_remove"): p_ident_remove, ("POST", "verify_address"): p_verify_address, ("POST", "signout"): p_signout, ("POST", "report"): p_report, ("POST", "order"): p_order, ("GET", "order"): p_order_status, ("POST", "revive"): p_revive, ("POST", "name_request"): p_name_request, ("POST", "topup_new"): p_topup_new, ("POST", "topup"): p_topup, ("POST", "spend"): p_spend, ("GET", "stats"): p_stats, ("POST", "ev"): p_ev, } PUBLIC.update(alerts.PUBLIC) PUBLIC.update(payreq.PUBLIC) # ------------------------------------------------------------------ admin tools (admin.bitaddy.com /api/site_*) def a_overview(h, m): month = datetime.now(timezone.utc).strftime("%Y-%m") with db() as c: paid = [dict(x) for x in c.execute("SELECT strftime('%Y-%m', paid_at, 'unixepoch') month, kind, asset, COUNT(*) n, SUM(CAST(usd AS REAL)) usd " "FROM ba_pay WHERE status='paid' GROUP BY month, kind, asset ORDER BY month DESC")] r = {"pages": c.execute("SELECT COUNT(*) FROM ba_pages").fetchone()[0], "links": c.execute("SELECT COUNT(*) FROM ba_links").fetchone()[0], "pro": c.execute("SELECT COUNT(*) FROM ba_perks WHERE kind='page' AND sku='pro' AND (until=0 OR until>?)", (now(),)).fetchone()[0], "short_names": c.execute("SELECT COUNT(*) FROM ba_perks WHERE kind='page' AND sku='name' AND (until=0 OR until>?)", (now(),)).fetchone()[0], "kept": c.execute("SELECT COUNT(*) FROM ba_perks WHERE kind='link' AND sku='keep' AND (until=0 OR until>?)", (now(),)).fetchone()[0], "open_reports": c.execute("SELECT COUNT(*) FROM ba_reports WHERE status='open'").fetchone()[0], "hidden": c.execute("SELECT (SELECT COUNT(*) FROM ba_pages WHERE hidden=1)+(SELECT COUNT(*) FROM ba_links WHERE hidden=1)").fetchone()[0], "new_pages_7d": c.execute("SELECT COUNT(*) FROM ba_pages WHERE created>?", (now() - 7 * 86400,)).fetchone()[0], "to_check": c.execute("SELECT (SELECT COUNT(*) FROM ba_stray WHERE status='open')+(SELECT COUNT(*) FROM ba_pay WHERE problem=1)").fetchone()[0], "name_requests": c.execute("SELECT COUNT(*) FROM ba_requests WHERE status='open'").fetchone()[0], "alerts": sum(1 for x in c.execute("SELECT id FROM ba_alerts") if has_perk(c, "alert", str(x["id"]), "alert")), "topup_held": c.execute("SELECT COALESCE(SUM(cents),0) FROM ba_topups").fetchone()[0], "paid": paid, "month": month, "month_usd": round(sum(x["usd"] or 0 for x in paid if x["month"] == month), 2), "all_usd": round(sum(x["usd"] or 0 for x in paid), 2), "pay_ready": pay_assets(), "watch_errors": {k: v[1] for k, v in LAST_ERR.items()}} return h.send(200, r) def a_items(h, m): q = (h.q.get("q") or "").strip() kind = h.q.get("kind") or "pages" flt = h.q.get("filter") or "all" like = "%" + q.lower() + "%" with db() as c: if kind == "links": sql = "SELECT * FROM ba_links WHERE (lower(code) LIKE ? OR lower(address) LIKE ? OR lower(COALESCE(label,'')) LIKE ?)" args = [like, like, like] else: sql = "SELECT * FROM ba_pages WHERE (name LIKE ? OR lower(COALESCE(title,'')) LIKE ? OR lower(coins) LIKE ?)" args = [like, like, like] if flt == "hidden": sql += " AND hidden=1" sql += " ORDER BY created DESC LIMIT 200" rows = [dict(r) for r in c.execute(sql, args)] for r in rows: if "coins" in r: r["coins"] = json.loads(r["coins"]) r["links"] = json.loads(r["links"]) return h.send(200, {"items": rows}) def a_item(h, m): kind, key = h.q.get("kind"), h.q.get("key", "") with db() as c: if kind == "page": it = c.execute("SELECT * FROM ba_pages WHERE name=?", (key,)).fetchone() else: it = c.execute("SELECT * FROM ba_links WHERE code=?", (key,)).fetchone() if not it: return h.err(404, "Not found.") it = dict(it) acct = c.execute("SELECT * FROM ba_accounts WHERE id=?", (it["account_id"],)).fetchone() if it.get("account_id") else None ids = [{"kind": r["kind"], "label": r["label"], "value": "(secret)" if r["kind"] == "key" else r["value"]} for r in c.execute("SELECT * FROM ba_idents WHERE account_id=? AND kind IN ('key','wallet')", (it.get("account_id"),))] reps = [dict(r) for r in c.execute("SELECT * FROM ba_reports WHERE kind=? AND target=? ORDER BY ts DESC", (kind, key))] daily = [dict(r) for r in c.execute("SELECT * FROM ba_daily WHERE target=? ORDER BY day DESC LIMIT 60", (("p:" if kind == "page" else "l:") + key,))] perks = [dict(r) for r in c.execute("SELECT sku, until, src, created FROM ba_perks WHERE kind=? AND ref=?", (kind, str(it["id"]) if kind == "page" else key))] if "coins" in it: it["coins"] = json.loads(it["coins"]) it["links"] = json.loads(it["links"]) return h.send(200, {"item": it, "account": dict(acct) if acct else None, "idents": ids, "reports": reps, "daily": daily, "perks": perks}) def a_item_action(h, m): b = h.j() kind, key, act = b.get("kind"), str(b.get("key") or ""), b.get("action") table, col = ("ba_pages", "name") if kind == "page" else ("ba_links", "code") with db() as c: row = c.execute("SELECT * FROM %s WHERE %s=?" % (table, col), (key,)).fetchone() if not row: return h.err(404, "Not found.") ref = str(row["id"]) if kind == "page" else key if act == "hide": c.execute("UPDATE %s SET hidden=1, hidden_reason=? WHERE %s=?" % (table, col), ("by " + h.who() + ": " + clean_text(b.get("reason"), 200), key)) elif act == "unhide": c.execute("UPDATE %s SET hidden=0, hidden_reason=NULL WHERE %s=?" % (table, col), (key,)) elif act == "delete": c.execute("DELETE FROM %s WHERE %s=?" % (table, col), (key,)) if kind == "page": drop_page_extras(c, row["id"]) else: c.execute("DELETE FROM ba_perks WHERE kind='link' AND ref=?", (key,)) elif act == "unverify" and kind == "page": cl = json.loads(row["coins"]) for x in cl: x["verified"] = False c.execute("UPDATE ba_pages SET coins=? WHERE name=?", (json.dumps(cl), key)) elif act in ("gift", "ungift"): # give or take away an extra by hand (owner only) if "settings" not in S.CAN[h.user["role"]]: return h.err(403, "Only an owner can do that.") sku = "keep" if kind == "link" else "pro" if act == "gift": add_perk(c, kind, ref, sku, max(0, min(int(b.get("days") or 0), 3650)), "gift by " + h.who()) else: c.execute("DELETE FROM ba_perks WHERE kind=? AND ref=? AND sku=?", (kind, ref, sku)) else: return h.err(400, "Unknown action.") S.audit(h.who(), "BitAddy " + act, "%s %s" % (kind, key)) return h.send(200, {"ok": True}) def a_reports(h, m): st = h.q.get("status") or "open" with db() as c: rows = [dict(r) for r in c.execute("SELECT * FROM ba_reports WHERE status=? ORDER BY ts DESC LIMIT 300", (st,))] for r in rows: if r["kind"] == "page": x = c.execute("SELECT hidden, title, coins FROM ba_pages WHERE name=?", (r["target"],)).fetchone() else: x = c.execute("SELECT hidden, label title, address coins FROM ba_links WHERE code=?", (r["target"],)).fetchone() r["exists"] = bool(x) r["hidden"] = bool(x and x["hidden"]) r["title"] = x["title"] if x else "" return h.send(200, {"reports": rows, "reasons": REASONS}) def a_report_action(h, m): b = h.j() rid = int(b.get("id", 0)) act = b.get("action") # keep | hide | delete | ban with db() as c: r = c.execute("SELECT * FROM ba_reports WHERE id=?", (rid,)).fetchone() if not r: return h.err(404, "Not found.") table, col = ("ba_pages", "name") if r["kind"] == "page" else ("ba_links", "code") if act == "keep": c.execute("UPDATE %s SET hidden=0, hidden_reason=NULL WHERE %s=? AND hidden_reason LIKE 'auto:%%'" % (table, col), (r["target"],)) elif act == "hide": c.execute("UPDATE %s SET hidden=1, hidden_reason=? WHERE %s=?" % (table, col), ("report: " + r["reason"], r["target"])) elif act in ("delete", "ban"): if act == "ban": if r["kind"] == "page": p = c.execute("SELECT coins FROM ba_pages WHERE name=?", (r["target"],)).fetchone() addrs = [x["address"] for x in json.loads(p["coins"])] if p else [] else: l = c.execute("SELECT address FROM ba_links WHERE code=?", (r["target"],)).fetchone() addrs = [l["address"]] if l else [] for ad in addrs: c.execute("INSERT OR IGNORE INTO ba_block(kind,value,note,ts,by) VALUES('address',?,?,?,?)", (ad, "from report #%d (%s)" % (rid, r["reason"]), now(), h.who())) c.execute("UPDATE ba_links SET hidden=1, hidden_reason='blocked address' WHERE address=?", (ad,)) c.execute("DELETE FROM %s WHERE %s=?" % (table, col), (r["target"],)) else: return h.err(400, "Unknown action.") c.execute("UPDATE ba_reports SET status='closed', resolution=?, closed_by=?, closed=? WHERE kind=? AND target=? AND status='open'", (act, h.who(), now(), r["kind"], r["target"])) S.audit(h.who(), "BitAddy report closed", "%s %s: %s" % (r["kind"], r["target"], act)) return h.send(200, {"ok": True}) def a_block(h, m): if m == "POST": if "edit" not in S.CAN[h.user["role"]]: return h.err(403, "Your role can't do that.") b = h.j() kind = b.get("kind") note_line = None with db() as c: if b.get("remove"): r = c.execute("SELECT * FROM ba_block WHERE id=?", (int(b["remove"]),)).fetchone() c.execute("DELETE FROM ba_block WHERE id=?", (int(b["remove"]),)) n = 0 if r and r["kind"] == "address": # bring back what this block hid (but not things hidden for other reasons, or using another blocked address) still = {x["value"] for x in c.execute("SELECT value FROM ba_block WHERE kind='address'")} n += c.execute("UPDATE ba_links SET hidden=0, hidden_reason=NULL WHERE address=? AND hidden_reason='blocked address'", (r["value"],)).rowcount for p in c.execute("SELECT id, coins FROM ba_pages WHERE hidden_reason='blocked address'").fetchall(): addrs = {x["address"] for x in json.loads(p["coins"])} if r["value"] in addrs and not (addrs & still): c.execute("UPDATE ba_pages SET hidden=0, hidden_reason=NULL WHERE id=?", (p["id"],)) n += 1 note_line = "removed %s %s (%d shown again)" % (r["kind"], r["value"][:24], n) if r else "removed an entry" else: v = str(b.get("value") or "").strip() if kind == "address": if not coins.detect(v): return h.err(400, "That isn't a crypto address we recognise.") elif kind == "name": v = v.lower() if not re.fullmatch(r"[a-z0-9-]{2,30}", v): return h.err(400, "Use 2 to 30 letters, numbers or dashes.") else: return h.err(400, "Pick address or name.") c.execute("INSERT OR IGNORE INTO ba_block(kind,value,note,ts,by) VALUES(?,?,?,?,?)", (kind, v, clean_text(b.get("note"), 200), now(), h.who())) n = 0 if kind == "address": n += c.execute("UPDATE ba_links SET hidden=1, hidden_reason='blocked address' WHERE address=?", (v,)).rowcount for p in c.execute("SELECT id, coins FROM ba_pages").fetchall(): if any(x["address"] == v for x in json.loads(p["coins"])): c.execute("UPDATE ba_pages SET hidden=1, hidden_reason='blocked address' WHERE id=?", (p["id"],)) n += 1 note_line = "added %s %s (%d hidden)" % (kind, v[:24], n) if note_line: S.audit(h.who(), "BitAddy blocklist", note_line) # after the write above is finished (one writer at a time) with db() as c: rows = [dict(r) for r in c.execute("SELECT * FROM ba_block ORDER BY ts DESC")] return h.send(200, {"block": rows, "reserved": []}) def a_stats(h, m): days = max(1, min(int(h.q.get("days", 30)), 365)) start = (datetime.now(timezone.utc) - timedelta(days=days - 1)).strftime("%Y-%m-%d") with db() as c: top = [dict(r) for r in c.execute("SELECT target, SUM(views) views, SUM(scans) scans FROM ba_daily WHERE day>=? GROUP BY target " "ORDER BY SUM(views)+SUM(scans) DESC LIMIT 25", (start,))] per = {r["day"]: dict(r) for r in c.execute("SELECT day, SUM(views) views, SUM(scans) scans FROM ba_daily WHERE day>=? GROUP BY day", (start,))} newp = {r["d"]: r["n"] for r in c.execute("SELECT date(created,'unixepoch') d, COUNT(*) n FROM ba_pages WHERE created>=? GROUP BY d", (now() - days * 86400,))} series = [] for i in range(days): d = (datetime.now(timezone.utc) - timedelta(days=days - 1 - i)).strftime("%Y-%m-%d") x = per.get(d, {}) series.append({"day": d, "views": x.get("views") or 0, "scans": x.get("scans") or 0, "new": newp.get(d, 0)}) return h.send(200, {"top": top, "series": series}) def a_owners(h, m): """Key rings (an owner key and/or wallets) and what they hold. Banning one hides its pages and signs it out.""" if m == "POST": if "settings" not in S.CAN[h.user["role"]]: return h.err(403, "Only an owner can do that.") b = h.j() aid = int(b.get("id", 0)) if b.get("action") not in ("ban", "unban"): return h.err(400, "Unknown action.") with db() as c: if not c.execute("SELECT 1 FROM ba_accounts WHERE id=?", (aid,)).fetchone(): return h.err(404, "Not found.") c.execute("UPDATE ba_accounts SET banned=? WHERE id=?", (1 if b["action"] == "ban" else 0, aid)) if b["action"] == "ban": c.execute("DELETE FROM ba_sessions WHERE account_id=?", (aid,)) S.audit(h.who(), "BitAddy owner", "%sned key ring #%d" % (b["action"], aid)) return h.send(200, {"ok": True}) q = "%" + (h.q.get("q") or "").strip().lower() + "%" with db() as c: accts = [dict(r) for r in c.execute( "SELECT DISTINCT a.* FROM ba_accounts a LEFT JOIN ba_idents i ON i.account_id=a.id LEFT JOIN ba_pages p ON p.account_id=a.id " "WHERE lower(COALESCE(i.value,'')) LIKE ? OR COALESCE(p.name,'') LIKE ? OR CAST(a.id AS TEXT) LIKE ? ORDER BY a.created DESC LIMIT 200", (q, q, q))] for a in accts: a["idents"] = [{"kind": r["kind"], "value": "(secret)" if r["kind"] == "key" else r["value"]} for r in c.execute("SELECT * FROM ba_idents WHERE account_id=? AND kind IN ('key','wallet')", (a["id"],))] a["pages"] = [r["name"] for r in c.execute("SELECT name FROM ba_pages WHERE account_id=?", (a["id"],))] a["links"] = c.execute("SELECT COUNT(*) FROM ba_links WHERE account_id=?", (a["id"],)).fetchone()[0] return h.send(200, {"owners": accts}) def a_payments(h, m): """Orders, and payments that matched no order. POST (owner): settle an order by hand, or dismiss a stray payment.""" if m == "POST": if "settings" not in S.CAN[h.user["role"]]: return h.err(403, "Only an owner can do that.") b = h.j() act = b.get("action") if act == "dismiss": with db() as c: c.execute("UPDATE ba_stray SET status='dismissed', note=? WHERE uid=?", ("dismissed by " + h.who(), str(b.get("uid") or ""))) elif act == "sorted": with db() as c: c.execute("UPDATE ba_pay SET problem=0 WHERE id=?", (str(b.get("id") or ""),)) elif act == "settle": # count a payment (a stray one, or one the owner saw in their wallet) for an order with db() as c: o = c.execute("SELECT * FROM ba_pay WHERE id=?", (str(b.get("id") or "").strip().upper(),)).fetchone() st = c.execute("SELECT * FROM ba_stray WHERE uid=? AND status='open'", (str(b.get("uid") or ""),)).fetchone() if b.get("uid") else None if not o: return h.err(404, "No order with that number.") if o["status"] == "paid": return h.err(400, "That order is already paid.") if st and st["asset"] != o["asset"]: return h.err(400, "That payment is in %s, the order asked for %s." % (st["asset"], o["asset"])) tx = st["tx"] if st else clean_text(b.get("tx"), 120) if not mark_paid(dict(o), tx or "by hand", by=h.who()): return h.err(400, "That order can't be settled.") if st: with db() as c: c.execute("UPDATE ba_stray SET status='settled', note=? WHERE uid=?", ("counted for order %s by %s" % (o["id"], h.who()), st["uid"])) else: return h.err(400, "Unknown action.") S.audit(h.who(), "BitAddy payments", "%s %s" % (act, b.get("id") or b.get("uid") or "")) with db() as c: rows = [dict(r) for r in c.execute("SELECT id,kind,label,usd,credit,asset,amount,tag,created,expires,status,tx,paid_at,note,result,problem " "FROM ba_pay ORDER BY created DESC LIMIT 300")] strays = [dict(r) for r in c.execute("SELECT * FROM ba_stray ORDER BY ts DESC LIMIT 200")] for r in rows: r["explorer"] = pay.explorer(r["asset"], r["tx"]) if r["tx"] and len(r["tx"]) > 20 else None for s in strays: s["explorer"] = pay.explorer(s["asset"], s["tx"]) return h.send(200, {"orders": rows, "strays": strays}) def a_topups(h, m): """Top-up links (never the links themselves: only their balances). POST (owner): add or take away by hand, with a note.""" if m == "POST": if "settings" not in S.CAN[h.user["role"]]: return h.err(403, "Only an owner can do that.") b = h.j() try: cents = int(dollars(b.get("usd"), -1000, 1000) * 100) except ValueError as e: return h.err(400, str(e)) note = clean_text(b.get("note"), 120) or "Changed by BitAddy" with db() as c: t = c.execute("SELECT * FROM ba_topups WHERE id=?", (int(b.get("id") or 0),)).fetchone() if not t: return h.err(404, "Not found.") if t["cents"] + cents < 0: return h.err(400, "It only holds $%s." % money(t["cents"])) c.execute("UPDATE ba_topups SET cents=cents+? WHERE id=?", (cents, t["id"])) c.execute("INSERT INTO ba_ledger(topup_id,ts,cents,what,ref) VALUES(?,?,?,?,?)", (t["id"], now(), cents, note, "admin:" + h.who())) S.audit(h.who(), "BitAddy top-up changed", "#%d by $%s: %s" % (t["id"], money(abs(cents)) if cents >= 0 else "-" + money(-cents), note)) with db() as c: rows = [dict(r) for r in c.execute("SELECT t.id, t.cents, t.created, t.last_used, (SELECT COUNT(*) FROM ba_ledger l WHERE l.topup_id=t.id) moves " "FROM ba_topups t WHERE t.cents>0 OR t.last_used IS NOT NULL ORDER BY COALESCE(t.last_used, t.created) DESC LIMIT 300")] for r in rows: r["history"] = [dict(x) for x in c.execute("SELECT ts, cents, what, ref FROM ba_ledger WHERE topup_id=? ORDER BY id DESC LIMIT 12", (r["id"],))] total = c.execute("SELECT COALESCE(SUM(cents),0) FROM ba_topups").fetchone()[0] return h.send(200, {"topups": rows, "held": total}) def a_prices(h, m): """Limits, prices, receiving wallets, which coins are open, tips, the sponsor line and partner links.""" if m == "POST": b = h.j() c0 = cfg() try: for k in ("free_coins", "free_links", "pro_coins", "pro_links", "min_free_name", "min_name", "autohide", "bonus_pct"): if k in b: c0[k] = max(0, min(int(b[k]), 100)) c0["min_name"] = max(3, int(c0["min_name"])) c0["min_free_name"] = max(int(c0["min_name"]), int(c0["min_free_name"])) for k, lo, hi in (("min_pay", 1, 100), ("min_topup", 1, 100), ("max_topup", 5, 5000), ("bonus_from", 1, 5000)): if k in b: c0[k] = str(dollars(b[k], lo, hi, k.replace("_", " "))) for sku, it in (b.get("items") or {}).items(): if sku in c0["items"] and isinstance(it, dict): if "usd" in it: c0["items"][sku]["usd"] = str(dollars(it["usd"], 1, 1000, ITEMS[sku]["name"] + " price")) if "days" in it: c0["items"][sku]["days"] = max(0, min(int(it["days"]), 3650)) if "on" in it: c0["items"][sku]["on"] = bool(it["on"]) if "tips" in b: c0["tips"] = bool(b["tips"]) if "pay_off" in b: c0["pay_off"] = [a for a in b["pay_off"] if a in pay.ASSETS] if "sponsor" in b: sp = b["sponsor"] or {} url = clean_text(sp.get("url"), 300) if sp.get("on") and (not clean_text(sp.get("text"), 90) or not re.match(r"^https://[^\s<>\"']+\.[^\s<>\"']+$", url)): raise ValueError("The sponsor line needs its words and a link that starts with https://") c0["sponsor"] = {"on": bool(sp.get("on")), "text": clean_text(sp.get("text"), 90), "url": url} if "refs" in b: refs = [] for r in (b["refs"] or [])[:12]: url = clean_text(r.get("url"), 300) if not clean_text(r.get("name"), 40) or not re.match(r"^https://[^\s<>\"']+\.[^\s<>\"']+$", url): raise ValueError("Each partner needs a name and a link that starts with https://") refs.append({"name": clean_text(r.get("name"), 40), "url": url, "note": clean_text(r.get("note"), 140), "paid": bool(r.get("paid", True))}) c0["refs"] = refs w = wallets() for chain in pay.CHAINS: if chain in (b.get("wallets") or {}): v = str(b["wallets"][chain] or "").strip() w[chain] = pay.check_address(chain, v) if v else "" except (ValueError, TypeError) as e: return h.err(400, str(e)) changed = [k for k in pay.CHAINS if (wallets().get(k) or "") != (w.get(k) or "")] S.set_setting("ba_cfg", c0) S.set_setting("ba_wallets", w) S.audit(h.who(), "BitAddy prices & wallets", "saved" + ((" · receiving wallet changed: " + ", ".join(changed)) if changed else "")) p = {} if h.q.get("prices"): try: p = {k: str(v) for k, v in pay.prices().items()} except Exception: p = {} return h.send(200, {"cfg": cfg(), "wallets": wallets(), "chains": [{"id": k, "name": pay.ASSETS[k]["name"], "also": [pay.ASSETS[a]["name"] for a in pay.ORDER if pay.ASSETS[a]["chain"] == k and a != k]} for k in pay.CHAINS], "assets": [{"id": a, "name": pay.ASSETS[a]["name"]} for a in pay.ORDER], "items": ITEMS, "ready": pay_assets(), "prices": p, "price_source": pay.PRICE["src"], "watch_errors": {k: v[1] for k, v in LAST_ERR.items()}}) def a_reserved(h, m): """Reserved names: the built-in groups (switch a group off, or release single names), the owner's own extra names, and a box to look up what would happen to any name.""" c0 = cfg() if m == "POST": if "settings" not in S.CAN[h.user["role"]]: return h.err(403, "Only an owner can do that.") b = h.j() act = b.get("action") name = str(b.get("name") or "").strip().lower() off, rel, more = set(c0.get("reserved_off") or []), set(c0.get("released") or []), set(c0.get("reserved_more") or []) if act == "request_done": with db() as c: c.execute("UPDATE ba_requests SET status='closed', closed=?, closed_by=? WHERE id=?", (now(), h.who(), int(b.get("id") or 0))) S.audit(h.who(), "BitAddy name request closed", str(b.get("id"))) act = None elif act == "group": g = b.get("group") if g not in names.SETS or g in names.ALWAYS: return h.err(400, "That group can't be switched.") (off.discard if b.get("on") else off.add)(g) elif act in ("release", "unrelease", "reserve", "unreserve"): if not NAME_RE.match(name): return h.err(400, "Type a name: 3 to 30 lowercase letters, numbers or dashes.") if act == "release": hit = names.check(name) if not hit or hit[0] != "reserved" or hit[1] in names.ALWAYS: return h.err(400, "That name isn't on a reserved list that can be released.") rel.add(name) elif act == "unrelease": rel.discard(name) elif act == "reserve": more.add(name) rel.discard(name) else: more.discard(name) else: return h.err(400, "Unknown action.") if act: c0.update(reserved_off=sorted(off), released=sorted(rel), reserved_more=sorted(more)) S.set_setting("ba_cfg", c0) S.audit(h.who(), "BitAddy reserved names", "%s %s" % (act, name or b.get("group"))) c0 = cfg() look = None q = (h.q.get("q") or "").strip().lower() if q: hit = names.check(q, c0.get("reserved_off") or (), set(c0.get("released") or ())) why = name_problem(q, short_ok=True) with db() as c: taken = bool(NAME_RE.match(q)) and name_taken(c, q) look = {"name": q, "why": why, "taken": taken, "kind": hit[0] if hit else None, "group": hit[1] if hit else None, "group_name": names.GROUP_NAMES.get(hit[1], "") if hit else "", "can_release": bool(hit and hit[0] == "reserved" and hit[1] not in names.ALWAYS), "extra": q in (c0.get("reserved_more") or []), "released": q in (c0.get("released") or [])} n = names.counts() listing = None g = h.q.get("group") if g in names.SETS: # every name of one group, for browsing rel = set(c0.get("released") or []) listing = {"group": g, "fixed": g in names.ALWAYS, "names": [{"name": x, "released": x in rel} for x in sorted(names.SETS[g])]} with db() as c: reqs = [dict(r) for r in c.execute("SELECT id, ts, name, email, note FROM ba_requests WHERE status='open' ORDER BY ts DESC LIMIT 300")] for r in reqs: r["still_reserved"] = can_request(r["name"], c0) return h.send(200, {"requests": reqs, "listing": listing, "groups": [{"id": g, "name": names.GROUP_NAMES[g], "count": n[g], "on": g not in (c0.get("reserved_off") or []), "fixed": g in names.ALWAYS, "sample": sorted(names.SETS[g])[:12]} for g in names.GROUP_NAMES], "released": c0.get("released") or [], "more": c0.get("reserved_more") or [], "blocked_words": len(names.BAD_PARTS) + len(names.BAD_EXACT) + len(names.PARTS), "look": look}) def a_checknow(h, m): check_payments(force=True) return h.send(200, {"ok": True, "watch_errors": {k: v[1] for k, v in LAST_ERR.items()}}) ADMIN = { "overview": (a_overview, "view"), "items": (a_items, "view"), "item": (a_item, "view"), "item_action": (a_item_action, "edit"), "reports": (a_reports, "view"), "report_action": (a_report_action, "edit"), "block": (a_block, "view"), "stats": (a_stats, "view"), "owners": (a_owners, "view"), "payments": (a_payments, "view"), "topups": (a_topups, "view"), "prices": (a_prices, "settings"), "checknow": (a_checknow, "settings"), "reserved": (a_reserved, "view"), "funnel": (a_funnel, "view"), "agents": (agent.a_agents, "view"), } # ------------------------------------------------------------------ jobs def tick(): with db() as c: pending = c.execute("SELECT COUNT(*) FROM ba_pay WHERE status='pending'").fetchone()[0] if pending: # nothing is asked of any blockchain service while nobody is paying check_payments() alerts.tick() # paid payment alerts: each watched address is looked at every few minutes payreq.tick() # open payment requests, the same way def daily(): for k in [k for k, v in pay.SOL_DONE.items() if v < time.time() - 3 * 86400]: pay.SOL_DONE.pop(k, None) agent.daily() alerts.daily() payreq.daily() with db() as c: c.execute("DELETE FROM ba_nonces WHERE expires0 AND until?))", (now() - PAGE_IDLE - EXPIRED_KEEP,) + live) c.execute("DELETE FROM ba_links WHERE COALESCE(last_visit, created)?))", (now() - LINK_IDLE - EXPIRED_KEEP,) + live) c.execute("DELETE FROM ba_perks WHERE (kind='page' AND ref NOT IN (SELECT CAST(id AS TEXT) FROM ba_pages)) OR " "(kind='link' AND ref NOT IN (SELECT code FROM ba_links)) OR (until>0 AND until