"""BitAddy payment requests: a page that asks for an exact amount and turns into "✓ Paid" by itself. Free. A request is one address, one coin (or USDT/USDC on that network), an amount and an optional note ("Invoice #12"), at bitaddy.com/r/. BitAddy watches the address for up to 30 days. The request counts as paid when a confirmed payment of AT LEAST the amount arrives after the request was made (whatever was already in the address is ignored). The maker gets a private cancel link (rq-...), stored here only as a scrambled fingerprint. No account. """ import json, re, secrets, threading, time from decimal import Decimal, InvalidOperation from html import escape B = None S = None SCHEMA = """ CREATE TABLE IF NOT EXISTS ba_payreq(id INTEGER PRIMARY KEY, code TEXT UNIQUE NOT NULL, token TEXT UNIQUE NOT NULL, asset TEXT NOT NULL, address TEXT NOT NULL, amount TEXT NOT NULL, base TEXT NOT NULL, note TEXT, created INTEGER NOT NULL, expires INTEGER NOT NULL, height INTEGER, status TEXT NOT NULL DEFAULT 'pending', tx TEXT, paid_at INTEGER, paid_amount TEXT); CREATE TABLE IF NOT EXISTS ba_payreq_seen(req_id INTEGER NOT NULL, uid TEXT NOT NULL, PRIMARY KEY(req_id, uid)); """ DAYS = 30 CODE_RE = re.compile(r"^[A-Za-z0-9]{8}$") LOOK = {} LOCK = threading.Lock() TICK = {"last": 0} def init(bitaddy_module, core): global B, S B, S = bitaddy_module, core def now(): return int(time.time()) def site(): return (S.CFG.get("SITE_ORIGIN") or "https://" + S.CFG["SITE_DOMAIN"]).rstrip("/") def assets_on(chain): return [a for a, x in B.pay.ASSETS.items() if x["chain"] == chain] def to_base(amount, asset): d = B.pay.ASSETS[asset]["dec"] q = Decimal(amount) * (Decimal(10) ** d) if q != q.to_integral_value(): raise ValueError("%s allows at most %d decimals." % (B.pay.symbol(asset), d)) return int(q) def public(r): a = B.pay.ASSETS[r["asset"]] return {"code": r["code"], "url": "%s/r/%s" % (site(), r["code"]), "asset": r["asset"], "symbol": B.pay.symbol(r["asset"]), "asset_name": a["name"], "coin": a["chain"], "address": r["address"], "address_ending": r["address"][-6:], "amount": r["amount"], "note": r["note"] or "", "status": r["status"] if not (r["status"] == "pending" and r["expires"] < now()) else "expired", "created": r["created"], "expires": r["expires"], "paid_at": r["paid_at"], "paid_amount": r["paid_amount"], "transaction": r["tx"], "transaction_page": B.pay.explorer(r["asset"], r["tx"]) if r["tx"] else None, "usually_confirmed_in": a["wait"]} def get(c, code): r = c.execute("SELECT * FROM ba_payreq WHERE code=?", (str(code or ""),)).fetchone() return dict(r) if r else None def by_token(c, token): m = re.search(r"rq-[A-Za-z0-9_\-]{20,40}", str(token or "")) if not m: return None r = c.execute("SELECT * FROM ba_payreq WHERE token=?", (S.tok_hash(m.group(0)),)).fetchone() return dict(r) if r else None # ------------------------------------------------------------------ making one def create(h, b): """-> (public dict, cancel token). Raises ValueError with a plain reason.""" B.limit(h, "payreq", 30) addr_in = str(b.get("address") or "").strip() asset = str(b.get("asset") or b.get("coin") or "").upper().strip() if not asset: d = B.coins.detect(addr_in) if len(d) != 1: raise ValueError("Pick which coin this address is for." if d else "That doesn't look like a crypto address we know.") asset = d[0] if asset not in B.pay.ASSETS: raise ValueError("Unknown coin. Use one of: " + ", ".join(B.pay.ASSETS) + ".") chain = B.pay.ASSETS[asset]["chain"] addr, why = B.coins.check(chain, addr_in) if not addr: raise ValueError(why) if B.blocked("address", addr): raise ValueError("That address can't be used on BitAddy.") amount = str(b.get("amount") or "").strip().replace(",", ".") try: ok = B.AMOUNT_RE.match(amount) and Decimal(amount) > 0 except InvalidOperation: ok = False if not ok: raise ValueError("Give the amount as a plain number, like 25 or 0.05.") amount = format(Decimal(amount).normalize(), "f") base = to_base(amount, asset) note = B.clean_text(" ".join(str(b.get("note") or "").split()), 80) height = B.pay.start_height(asset) try: # everything already in the address is old: only a payment after this moment can pay the request uids = set(B.pay.known(asset, addr)) | {t["uid"] for t in B.pay.incoming(asset, addr, height, set())} except Exception: raise ValueError("%s payments can't be checked right now. Please try again in a few minutes." % B.pay.ASSETS[asset]["name"]) token = "rq-" + secrets.token_urlsafe(18) with B.db() as c: for _ in range(20): code = "".join(secrets.choice(B.CODE_ALPHABET) for _ in range(8)) if not c.execute("SELECT 1 FROM ba_payreq WHERE code=?", (code,)).fetchone(): break cur = c.execute("INSERT INTO ba_payreq(code,token,asset,address,amount,base,note,created,expires,height) VALUES(?,?,?,?,?,?,?,?,?,?)", (code, S.tok_hash(token), asset, addr, amount, str(base), note, now(), now() + DAYS * 86400, height)) for u in uids: c.execute("INSERT OR IGNORE INTO ba_payreq_seen(req_id,uid) VALUES(?,?)", (cur.lastrowid, u)) r = get(c, code) return public(r), token # ------------------------------------------------------------------ watching (from the console's half-minute tick) def check_all(force=False): if not LOCK.acquire(False): return try: with B.db() as c: c.execute("UPDATE ba_payreq SET status='expired' WHERE status='pending' AND expires) def render(r): d = public(r) st = d["status"] if st == "paid": box = '' % ( escape(d["code"]), B.alerts.day(d["paid_at"]), escape(d["paid_amount"] or ""), escape(d["symbol"]), (' · see the payment ↗' % escape(d["transaction_page"])) if d["transaction_page"] else "") elif st == "pending": box = ('
Waiting for payment · this page updates by itself ' '(usually %s after sending)
' % (escape(d["code"]), escape(d["usually_confirmed_in"]))) else: box = '
%s · don\'t pay this request
' % ( escape(d["code"]), st, "This request was cancelled" if st == "cancelled" else "This request has expired") coin = {"coin": d["coin"], "address": d["address"], "label": d["asset_name"] if d["asset"] != d["coin"] else "", "verified": False} # the amount goes into the page's QR code only for the coin itself: a QR for a token would ask the wallet for the network's own coin block = B.coin_block(coin, 0, d["amount"] if (st == "pending" and d["asset"] == d["coin"]) else None) block = block.replace('', "") # the request already says how much if d["asset"] != d["coin"]: # a token: say clearly what to send, the QR holds only the address block = block.replace('
Send %s %s on the %s network

%s

%s %s

Payment request%s

%s%s%s

Marked paid when a payment of at least %s %s reaches this address after the request was made. Always check the address ending in your wallet before you send.

Make your own payment request · BitAddy

""" % ( escape(d["symbol"][:1]), escape(d["amount"]), escape(d["symbol"]), (" · " + escape(d["note"])) if d["note"] else "", box, B.WARN, block if st != "cancelled" else "", escape(d["amount"]), escape(d["symbol"])) return B.page_html("Pay %s %s · BitAddy" % (d["amount"], d["symbol"]), body, noindex=True) def route(h, p, q): if not p.startswith("r/"): return False code = p[2:] with B.db() as c: r = get(c, code) if CODE_RE.match(code) else None if not r: st, html = B.render_msg("Nothing here", "There's no payment request at this address.") h.send(st, html, "text/html; charset=utf-8") else: h.send(200, render(r), "text/html; charset=utf-8", cache="no-cache") return True