Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
783 lines
34 KiB
Python
783 lines
34 KiB
Python
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import sqlite3
|
|
import time
|
|
from typing import Any, Dict, Optional, Tuple
|
|
|
|
log = logging.getLogger("econ_guard")
|
|
|
|
# Одноразовые награды: код извлекается из типа леджера.
|
|
ONE_TIME_TYPES = ("firstweek",)
|
|
ONE_TIME_PREFIXES = ("achv:", "streak:")
|
|
|
|
Wallet = Tuple[int, int]
|
|
_WAL_WARNING_EMITTED = False
|
|
REF_NEW_ID_MIN = 9_000_000_000
|
|
REF_INVITER_UNITS = 25_000_000
|
|
REF_INVITEE_UNITS = 10_000_000
|
|
|
|
|
|
def _warn_wal_commit_window(con: sqlite3.Connection) -> None:
|
|
global _WAL_WARNING_EMITTED
|
|
if _WAL_WARNING_EMITTED:
|
|
return
|
|
modes = (con.execute("PRAGMA main.journal_mode").fetchone()[0],
|
|
con.execute("PRAGMA ledger.journal_mode").fetchone()[0])
|
|
if "wal" in modes:
|
|
_WAL_WARNING_EMITTED = True
|
|
log.warning("[ECONGUARD] WAL: ordinary SQL errors roll back both writes; "
|
|
"power failure during COMMIT is not atomic across database files")
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# схема
|
|
# --------------------------------------------------------------------------- #
|
|
def ensure_schema(bot_db: str) -> None:
|
|
con = sqlite3.connect(bot_db, timeout=30)
|
|
try:
|
|
con.execute("PRAGMA busy_timeout=30000")
|
|
cols = {r[1] for r in con.execute("PRAGMA table_info(econ_tx)")}
|
|
if "ref" not in cols:
|
|
con.execute("ALTER TABLE econ_tx ADD COLUMN ref TEXT")
|
|
# NULL в unique-индексе SQLite различимы -> исторические строки не мешают.
|
|
con.execute("CREATE UNIQUE INDEX IF NOT EXISTS ux_econ_tx_ref ON econ_tx(type, ref)")
|
|
con.execute("CREATE INDEX IF NOT EXISTS ix_econ_tx_dst_type_ts ON econ_tx(dst, type, ts)")
|
|
con.execute("""CREATE TABLE IF NOT EXISTS econ_grants(
|
|
uid INTEGER NOT NULL, code TEXT NOT NULL, units INTEGER NOT NULL,
|
|
ts INTEGER NOT NULL, PRIMARY KEY(uid, code))""")
|
|
con.execute("CREATE TABLE IF NOT EXISTS kv(k TEXT PRIMARY KEY, v TEXT)")
|
|
con.execute("""CREATE TABLE IF NOT EXISTS referral_awards(
|
|
invited_uid INTEGER PRIMARY KEY, inviter_uid INTEGER NOT NULL,
|
|
awarded_at INTEGER NOT NULL, verified_at INTEGER NOT NULL,
|
|
inviter_units INTEGER NOT NULL, invitee_units INTEGER NOT NULL)""")
|
|
con.execute("CREATE INDEX IF NOT EXISTS ix_referral_awards_inviter_time "
|
|
"ON referral_awards(inviter_uid,awarded_at)")
|
|
con.commit()
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
def _con(path: str, timeout: int = 25) -> sqlite3.Connection:
|
|
con = sqlite3.connect(path, timeout=timeout)
|
|
con.execute("PRAGMA busy_timeout=%d" % (timeout * 1000))
|
|
return con
|
|
|
|
|
|
def account_eligible_con(con: sqlite3.Connection, uid: int, schema: str = "main") -> bool:
|
|
"""Check canonical account flags on the caller's transaction; read errors never authorize."""
|
|
if schema not in ("main", "ledger"):
|
|
raise ValueError("invalid account schema")
|
|
row = con.execute("SELECT COALESCE(banned,0),COALESCE(api_blocked,0) "
|
|
"FROM %s.users WHERE tg_id=?" % schema, (int(uid),)).fetchone()
|
|
return bool(row is not None and not row[0] and not row[1])
|
|
|
|
|
|
def account_eligible(bot_db: str, uid: int) -> bool:
|
|
"""Fail closed for missing accounts, either ban flag, or unreadable account state."""
|
|
try:
|
|
con = _con(bot_db, 15)
|
|
try:
|
|
return account_eligible_con(con, uid)
|
|
finally:
|
|
con.close()
|
|
except sqlite3.Error:
|
|
log.exception("[ECONGUARD] account eligibility read failed uid=%s", uid)
|
|
return False
|
|
|
|
|
|
def _account_name(name: str, uid: int, main_name: Optional[str] = None) -> bool:
|
|
name = str(name or "")
|
|
main = "tg%d" % int(uid)
|
|
if name in (main, "pm%d" % int(uid), "sol%d" % int(uid)):
|
|
return True
|
|
prefix = main + "-k"
|
|
if name.startswith(prefix):
|
|
suffix = name[len(prefix):]
|
|
return bool(suffix and suffix[0] != "0" and suffix.isascii() and suffix.isdigit())
|
|
if name == main_name and not name.startswith(("tg", "pm", "sol")):
|
|
return True
|
|
return False
|
|
|
|
|
|
def _wallet_owned_con(con: sqlite3.Connection, uid: int, token_id: int,
|
|
schema: str = "ledger") -> bool:
|
|
if schema not in ("main", "ledger"):
|
|
raise ValueError("invalid account schema")
|
|
user = con.execute("SELECT token_name FROM %s.users WHERE tg_id=?" % schema,
|
|
(int(uid),)).fetchone()
|
|
token = con.execute("SELECT name FROM tokens WHERE id=? AND deleted_at IS NULL",
|
|
(int(token_id),)).fetchone()
|
|
return bool(user and token and _account_name(token[0], uid, user[0]))
|
|
|
|
|
|
def _resolve_wallet_con(con: sqlite3.Connection, uid: int) -> Optional[Wallet]:
|
|
if not account_eligible_con(con, uid, "ledger"):
|
|
return None
|
|
user = con.execute("SELECT token_name FROM ledger.users WHERE tg_id=?", (int(uid),)).fetchone()
|
|
names = []
|
|
if user and user[0] and _account_name(user[0], uid, user[0]):
|
|
names.append(user[0])
|
|
default = "tg%d" % int(uid)
|
|
if default not in names:
|
|
names.append(default)
|
|
for name in names:
|
|
row = con.execute("SELECT id,remain_quota FROM tokens WHERE name=? "
|
|
"AND status IN (1,2) AND deleted_at IS NULL "
|
|
"ORDER BY remain_quota DESC,id LIMIT 1", (name,)).fetchone()
|
|
if row:
|
|
return int(row[0]), int(row[1])
|
|
return None
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# леджер
|
|
# --------------------------------------------------------------------------- #
|
|
def ledger(bot_db: str, src: int, dst: int, units: int, type_: str,
|
|
ref: Optional[str] = None) -> int:
|
|
"""Записать строку леджера.
|
|
|
|
Возвращает rowid (>0), 0 - дубль по UNIQUE(type, ref), -1 - ошибка БД.
|
|
"""
|
|
con = _con(bot_db)
|
|
try:
|
|
cur = con.execute("INSERT INTO econ_tx (src,dst,units,type,ts,ref) VALUES (?,?,?,?,?,?)",
|
|
(int(src), int(dst), int(units), type_, int(time.time()), ref))
|
|
con.commit()
|
|
return int(cur.lastrowid or 0)
|
|
except sqlite3.IntegrityError:
|
|
con.rollback()
|
|
return 0
|
|
except Exception:
|
|
log.exception("[ECONGUARD] ledger insert failed type=%s ref=%s", type_, ref)
|
|
try:
|
|
con.rollback()
|
|
except Exception:
|
|
pass
|
|
return -1
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
def undo_ledger(bot_db: str, rowid: int) -> None:
|
|
"""Компенсация: убрать строку леджера, если деньги не двигались."""
|
|
if not rowid or rowid <= 0:
|
|
return
|
|
con = _con(bot_db)
|
|
try:
|
|
con.execute("DELETE FROM econ_tx WHERE id=?", (int(rowid),))
|
|
con.commit()
|
|
except Exception:
|
|
log.exception("[ECONGUARD] ledger undo failed id=%s", rowid)
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# --------------------------------------------------------------------------- #
|
|
def resolve_wallet(gw_db: str, bot_db: str, uid: int) -> Optional[Wallet]:
|
|
"""Resolve an eligible account's live wallet in a gateway-first attached snapshot."""
|
|
con = None
|
|
try:
|
|
con = _con(gw_db, 15)
|
|
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
|
con.execute("BEGIN")
|
|
# Establish the gateway read lock before reading attached account state.
|
|
con.execute("SELECT id FROM tokens LIMIT 1").fetchone()
|
|
wallet = _resolve_wallet_con(con, uid)
|
|
con.commit()
|
|
return wallet
|
|
except sqlite3.Error:
|
|
if con is not None:
|
|
con.rollback()
|
|
log.exception("[ECONGUARD] resolve_wallet failed uid=%s", uid)
|
|
return None
|
|
finally:
|
|
if con is not None:
|
|
con.close()
|
|
|
|
|
|
def credit(gw_db: str, token_id: int, units: int) -> int:
|
|
units = int(units)
|
|
if units <= 0:
|
|
return 0
|
|
con = _con(gw_db)
|
|
try:
|
|
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota+? "
|
|
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL", # [FIX-2410] кап-пауза держит деньги
|
|
(units, int(token_id)))
|
|
con.commit()
|
|
return units if cur.rowcount == 1 else 0
|
|
except Exception:
|
|
log.exception("[ECONGUARD] credit failed token=%s units=%s", token_id, units)
|
|
try:
|
|
con.rollback()
|
|
except Exception:
|
|
pass
|
|
return 0
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
def debit(gw_db: str, token_id: int, units: int) -> int:
|
|
units = int(units)
|
|
if units <= 0:
|
|
return 0
|
|
con = _con(gw_db)
|
|
try:
|
|
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota-? "
|
|
"WHERE id=? AND remain_quota>=? AND status=1 AND deleted_at IS NULL", # [FIX-2410] пауза запрещает списание
|
|
(units, int(token_id), units))
|
|
con.commit()
|
|
return units if cur.rowcount == 1 else 0
|
|
except Exception:
|
|
log.exception("[ECONGUARD] debit failed token=%s units=%s", token_id, units)
|
|
try:
|
|
con.rollback()
|
|
except Exception:
|
|
pass
|
|
return 0
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# mint / burn
|
|
# --------------------------------------------------------------------------- #
|
|
def mint(gw_db: str, bot_db: str, uid: int, units: int, type_: str,
|
|
ref: Optional[str] = None, wallet: Optional[Wallet] = None) -> int:
|
|
"""Казна -> пользователь: леджер и кредит в одной транзакции.
|
|
|
|
UNIQUE(type, ref) блокирует дубли; обычная ошибка SQLite или недоступный
|
|
кошелёк откатывает обе записи. WAL не гарантирует power-failure atomicity.
|
|
Возвращает реально зачислено, 0 — операция не применена.
|
|
"""
|
|
units = int(units)
|
|
if units <= 0:
|
|
return 0
|
|
con = None
|
|
try:
|
|
# Do not trust a pre-resolved or explicit wallet across the account boundary.
|
|
con = sqlite3.connect(gw_db, timeout=25)
|
|
con.execute("PRAGMA busy_timeout=25000")
|
|
# [FIX-2410] Один attached-транзакционный путь вместо credit/undo-компенсации:
|
|
# обычные ошибки БД откатывают и леджер, и изменение кошелька.
|
|
# Acquire gateway before bot.db, in the same order as mk_daemon.
|
|
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
|
_warn_wal_commit_window(con)
|
|
con.execute("BEGIN IMMEDIATE")
|
|
if not account_eligible_con(con, uid, "ledger"):
|
|
con.rollback()
|
|
return 0
|
|
w = wallet if wallet is not None else _resolve_wallet_con(con, uid)
|
|
if not w or not _wallet_owned_con(con, uid, int(w[0])):
|
|
con.rollback()
|
|
return 0
|
|
con.execute("INSERT INTO ledger.econ_tx (src,dst,units,type,ts,ref) VALUES (?,?,?,?,?,?)",
|
|
(0, int(uid), units, type_, int(time.time()), ref))
|
|
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota+? "
|
|
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL",
|
|
(units, int(w[0])))
|
|
if cur.rowcount != 1:
|
|
con.rollback()
|
|
log.warning("[ECONGUARD] mint rolled back, wallet unavailable uid=%s type=%s ref=%s",
|
|
uid, type_, ref)
|
|
return 0
|
|
con.commit()
|
|
return units
|
|
except Exception as exc:
|
|
if con is not None:
|
|
try:
|
|
con.rollback()
|
|
except sqlite3.Error:
|
|
log.exception("[ECONGUARD] mint rollback failed uid=%s type=%s ref=%s",
|
|
uid, type_, ref)
|
|
if isinstance(exc, sqlite3.IntegrityError):
|
|
log.warning("[ECONGUARD] mint transaction rejected by constraint uid=%s type=%s ref=%s",
|
|
uid, type_, ref)
|
|
else:
|
|
log.exception("[ECONGUARD] mint transaction failed uid=%s type=%s ref=%s",
|
|
uid, type_, ref)
|
|
return 0
|
|
finally:
|
|
if con is not None:
|
|
con.close()
|
|
|
|
|
|
def burn(gw_db: str, bot_db: str, uid: int, units: int, type_: str,
|
|
ref: Optional[str] = None, wallet: Optional[Wallet] = None) -> int:
|
|
units = int(units)
|
|
if units <= 0:
|
|
return 0
|
|
con = None
|
|
try:
|
|
# Recheck flags and explicit wallet ownership after both database locks are held.
|
|
con = sqlite3.connect(gw_db, timeout=25)
|
|
con.execute("PRAGMA busy_timeout=25000")
|
|
# [FIX-2410] UNIQUE проверяется вставкой под BEGIN IMMEDIATE, без ledger_seen
|
|
# и отдельного refund: ошибки откатывают леджер и дебет вместе.
|
|
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
|
_warn_wal_commit_window(con)
|
|
con.execute("BEGIN IMMEDIATE")
|
|
if not account_eligible_con(con, uid, "ledger"):
|
|
con.rollback()
|
|
return 0
|
|
w = wallet if wallet is not None else _resolve_wallet_con(con, uid)
|
|
if not w or not _wallet_owned_con(con, uid, int(w[0])):
|
|
con.rollback()
|
|
return 0
|
|
con.execute("INSERT INTO ledger.econ_tx (src,dst,units,type,ts,ref) VALUES (?,?,?,?,?,?)",
|
|
(int(uid), 0, units, type_, int(time.time()), ref))
|
|
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota-? "
|
|
"WHERE id=? AND remain_quota>=? AND status=1 AND deleted_at IS NULL",
|
|
(units, int(w[0]), units))
|
|
if cur.rowcount != 1:
|
|
con.rollback()
|
|
log.warning("[ECONGUARD] burn rolled back (insufficient/locked) uid=%s type=%s ref=%s",
|
|
uid, type_, ref)
|
|
return 0
|
|
con.commit()
|
|
return units
|
|
except Exception as exc:
|
|
if con is not None:
|
|
try:
|
|
con.rollback()
|
|
except sqlite3.Error:
|
|
log.exception("[ECONGUARD] burn rollback failed uid=%s type=%s ref=%s",
|
|
uid, type_, ref)
|
|
if isinstance(exc, sqlite3.IntegrityError):
|
|
log.warning("[ECONGUARD] burn transaction rejected by constraint uid=%s type=%s ref=%s",
|
|
uid, type_, ref)
|
|
else:
|
|
log.exception("[ECONGUARD] burn transaction failed uid=%s type=%s ref=%s",
|
|
uid, type_, ref)
|
|
return 0
|
|
finally:
|
|
if con is not None:
|
|
con.close()
|
|
|
|
|
|
def refill_weekly(bot_db: str, gw_db: str, uid: int, target: int, week_start: int,
|
|
level: int, now: Optional[int] = None) -> int:
|
|
uid, target, week_start, level = int(uid), int(target), int(week_start), int(level)
|
|
current = int(time.time() if now is None else now)
|
|
if uid <= 0 or target < 0 or week_start <= 0 or current < week_start:
|
|
return 0
|
|
con = None
|
|
try:
|
|
con = _con(gw_db)
|
|
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
|
_warn_wal_commit_window(con)
|
|
con.execute("BEGIN IMMEDIATE")
|
|
if not account_eligible_con(con, uid, "ledger"):
|
|
con.rollback()
|
|
return 0
|
|
columns = {row[1] for row in con.execute("PRAGMA ledger.table_info(users)")}
|
|
fields = ("token_name", "api_key", "created", "last_loyalty", "last_bonus_lvl",
|
|
"key_locked", "chat_key_locked")
|
|
user = con.execute("SELECT %s FROM ledger.users WHERE tg_id=?" % ",".join(fields),
|
|
(uid,)).fetchone()
|
|
info = dict(zip(fields, user))
|
|
if (int(info["last_loyalty"] or 0) >= week_start
|
|
or info["key_locked"] or info["chat_key_locked"]
|
|
or not info["created"] or current - int(info["created"]) < 86400):
|
|
con.rollback()
|
|
return 0
|
|
cap_paused = False
|
|
if "cap_paused" in columns:
|
|
cap_paused = bool(con.execute("SELECT cap_paused FROM ledger.users WHERE tg_id=?",
|
|
(uid,)).fetchone()[0])
|
|
main_name = str(info["token_name"] or "")
|
|
if main_name.startswith("tg%d-k" % uid) and _account_name(main_name, uid):
|
|
main_name = "tg%d" % uid
|
|
if not main_name or not _account_name(main_name, uid, main_name):
|
|
con.rollback()
|
|
return 0
|
|
saved = str(info["api_key"] or "").strip()
|
|
has_saved_key = bool(saved)
|
|
if saved.startswith("sk-"):
|
|
saved = saved[3:]
|
|
sql = ("SELECT id,remain_quota,status,unlimited_quota,expired_time FROM tokens "
|
|
"WHERE name=? AND deleted_at IS NULL")
|
|
params = [main_name]
|
|
if has_saved_key:
|
|
sql += " AND key=?"
|
|
params.append(saved)
|
|
wallets = con.execute(sql, params).fetchall()
|
|
if len(wallets) != 1:
|
|
con.rollback()
|
|
return 0
|
|
token_id, balance, status, unlimited, expires = wallets[0]
|
|
if (status not in (1, 2, 4) or (status == 2 and not cap_paused)
|
|
or unlimited or expires is None
|
|
or not (int(expires) == -1 or int(expires) >= current)):
|
|
con.rollback()
|
|
return 0
|
|
prefix = "tg%d-k" % uid
|
|
rows = con.execute("SELECT name,remain_quota,unlimited_quota FROM tokens "
|
|
"WHERE name IN (?,?,?,?) OR (name>=? AND name<?)",
|
|
(main_name, "tg%d" % uid, "pm%d" % uid, "sol%d" % uid,
|
|
prefix, "tg%d-l" % uid)).fetchall()
|
|
# account-wide total exceed every rank target, so the weekly floor credited 0.
|
|
total = sum(max(0, int(quota or 0)) for name, quota, unlimited in rows
|
|
if not unlimited and _account_name(name, uid, main_name))
|
|
delta = max(0, target - total)
|
|
con.execute("INSERT INTO ledger.econ_tx(src,dst,units,type,ts,ref) VALUES(?,?,?,?,?,?)",
|
|
(0, uid, delta, "loyalty:weekly", current, "weekly:%d:%d" % (uid, week_start)))
|
|
credited = con.execute(
|
|
"UPDATE tokens SET remain_quota=COALESCE(remain_quota,0)+?, "
|
|
"status=CASE WHEN status=4 AND ?=0 AND COALESCE(remain_quota,0)+?>0 THEN 1 ELSE status END "
|
|
"WHERE id=? AND deleted_at IS NULL AND status IN (1,2,4)",
|
|
(delta, int(cap_paused), delta, int(token_id)))
|
|
receipt = con.execute(
|
|
"UPDATE ledger.users SET last_loyalty=?,last_bonus_lvl=MAX(COALESCE(last_bonus_lvl,0),?) "
|
|
"WHERE tg_id=? AND COALESCE(last_loyalty,0)<? "
|
|
"AND COALESCE(banned,0)=0 AND COALESCE(api_blocked,0)=0",
|
|
(current, max(1, min(4, level)), uid, week_start))
|
|
if credited.rowcount != 1 or receipt.rowcount != 1:
|
|
con.rollback()
|
|
return 0
|
|
con.commit()
|
|
return delta
|
|
except Exception:
|
|
if con is not None:
|
|
con.rollback()
|
|
log.exception("[ECONGUARD] weekly refill failed uid=%s week=%s", uid, week_start)
|
|
return 0
|
|
finally:
|
|
if con is not None:
|
|
con.close()
|
|
|
|
|
|
def _referral_wallet_con(con: sqlite3.Connection, uid: int) -> Optional[Wallet]:
|
|
user = con.execute("SELECT token_name,api_key FROM ledger.users WHERE tg_id=?",
|
|
(int(uid),)).fetchone()
|
|
if not user or not user[0] or not user[1]:
|
|
return None
|
|
name, saved = str(user[0]), str(user[1]).strip()
|
|
if name.startswith("tg%d-k" % int(uid)) and _account_name(name, uid):
|
|
name = "tg%d" % int(uid)
|
|
if saved.startswith("sk-"):
|
|
saved = saved[3:]
|
|
if not saved or not _account_name(name, uid, name):
|
|
return None
|
|
rows = con.execute("SELECT id,remain_quota FROM tokens WHERE name=? AND key=? "
|
|
"AND status IN (1,2) AND deleted_at IS NULL", (name, saved)).fetchall()
|
|
if len(rows) != 1:
|
|
return None
|
|
return int(rows[0][0]), int(rows[0][1] or 0)
|
|
|
|
|
|
def award_referral(bot_db: str, gw_db: str, uid: int, verified_at: int,
|
|
now: Optional[int] = None) -> Dict[str, Any]:
|
|
result = {"status": "pending", "inviter": 0, "inviter_units": 0, "invitee_units": 0}
|
|
try:
|
|
uid, verified = int(uid), int(verified_at)
|
|
if isinstance(verified_at, bool) or verified_at != verified:
|
|
return result
|
|
current = int(time.time() if now is None else now)
|
|
except (TypeError, ValueError, OverflowError):
|
|
return result
|
|
if uid <= 0:
|
|
return result
|
|
con = None
|
|
try:
|
|
con = _con(gw_db)
|
|
con.execute("ATTACH DATABASE ? AS ledger", (bot_db,))
|
|
_warn_wal_commit_window(con)
|
|
con.execute("BEGIN IMMEDIATE")
|
|
if now is None:
|
|
current = int(time.time())
|
|
user = con.execute("SELECT referred_by,ref_time,ref_awarded FROM ledger.users WHERE tg_id=?",
|
|
(uid,)).fetchone()
|
|
if not user:
|
|
con.rollback()
|
|
return result
|
|
inviter = int(user[0] or 0)
|
|
result["inviter"] = inviter
|
|
if verified <= 0 or not 0 <= current - verified <= 30 or inviter <= 0 or inviter == uid:
|
|
con.rollback()
|
|
return result
|
|
referrer = con.execute("SELECT referred_by FROM ledger.users WHERE tg_id=?",
|
|
(inviter,)).fetchone()
|
|
if not referrer or int(referrer[0] or 0) == uid:
|
|
con.rollback()
|
|
return result
|
|
if not (account_eligible_con(con, uid, "ledger")
|
|
and account_eligible_con(con, inviter, "ledger")):
|
|
con.rollback()
|
|
result["status"] = "blocked"
|
|
return result
|
|
existing = con.execute(
|
|
"SELECT inviter_uid,inviter_units,invitee_units FROM ledger.referral_awards WHERE invited_uid=?",
|
|
(uid,)).fetchone()
|
|
if existing or user[2]:
|
|
con.rollback()
|
|
result["status"] = "already"
|
|
if existing:
|
|
result.update(inviter=int(existing[0]), inviter_units=int(existing[1]),
|
|
invitee_units=int(existing[2]))
|
|
return result
|
|
ref_time = int(user[1] or 0)
|
|
if ref_time <= 0 or current - ref_time < 86400:
|
|
con.rollback()
|
|
return result
|
|
invitee_wallet = _referral_wallet_con(con, uid)
|
|
inviter_wallet = _referral_wallet_con(con, inviter)
|
|
if not invitee_wallet or not inviter_wallet:
|
|
con.rollback()
|
|
result["status"] = "no_wallet"
|
|
return result
|
|
# Mandatory invitee evidence: one successful (type=2) consumption log on the
|
|
# exact stored main wallet, from referral time up to now. INDEXED BY is not
|
|
# optional: unhinted SQLite prefers idx_logs_top24 and scans every user's
|
|
# logs while this transaction already holds the writer lock. Read errors
|
|
# (missing table/index/column) hit the except below: nothing is awarded.
|
|
api_used = con.execute(
|
|
"SELECT 1 FROM logs INDEXED BY idx_logs_token_id "
|
|
"WHERE token_id=? AND type=2 AND created_at>=? AND created_at<=? "
|
|
"AND (COALESCE(quota,0)>0 OR COALESCE(prompt_tokens,0)>0 "
|
|
"OR COALESCE(completion_tokens,0)>0) LIMIT 1",
|
|
(int(invitee_wallet[0]), ref_time, current)).fetchone()
|
|
if not api_used:
|
|
con.rollback()
|
|
result["status"] = "no_api_request"
|
|
return result
|
|
awarded = con.execute(
|
|
"SELECT COUNT(*) FROM ledger.referral_awards WHERE inviter_uid=? AND awarded_at>?",
|
|
(inviter, current - 86400)).fetchone()[0]
|
|
if int(awarded) >= 10:
|
|
con.rollback()
|
|
result["status"] = "cap"
|
|
return result
|
|
inviter_units = REF_INVITER_UNITS // 2 if uid >= REF_NEW_ID_MIN else REF_INVITER_UNITS
|
|
claimed = con.execute(
|
|
"UPDATE ledger.users SET ref_awarded=1 WHERE tg_id=? AND referred_by=? "
|
|
"AND COALESCE(ref_awarded,0)=0 AND COALESCE(banned,0)=0 AND COALESCE(api_blocked,0)=0",
|
|
(uid, inviter))
|
|
if claimed.rowcount != 1:
|
|
con.rollback()
|
|
return result
|
|
con.execute("INSERT INTO ledger.referral_awards"
|
|
"(invited_uid,inviter_uid,awarded_at,verified_at,inviter_units,invitee_units) "
|
|
"VALUES(?,?,?,?,?,?)",
|
|
(uid, inviter, current, verified, inviter_units, REF_INVITEE_UNITS))
|
|
for recipient, wallet, units, role in (
|
|
(inviter, inviter_wallet, inviter_units, "inviter"),
|
|
(uid, invitee_wallet, REF_INVITEE_UNITS, "invitee")):
|
|
con.execute("INSERT INTO ledger.econ_tx(src,dst,units,type,ts,ref) VALUES(?,?,?,?,?,?)",
|
|
(0, recipient, units, "referral", current, "referral:%d:%s" % (uid, role)))
|
|
credited = con.execute("UPDATE tokens SET remain_quota=COALESCE(remain_quota,0)+? "
|
|
"WHERE id=? AND status IN (1,2) AND deleted_at IS NULL",
|
|
(units, wallet[0]))
|
|
if credited.rowcount != 1:
|
|
con.rollback()
|
|
result["status"] = "no_wallet"
|
|
return result
|
|
immunity = con.execute(
|
|
"UPDATE ledger.users SET ref_credit=MAX(COALESCE(ref_credit,0),?) WHERE tg_id=? "
|
|
"AND COALESCE(banned,0)=0 AND COALESCE(api_blocked,0)=0",
|
|
(current + 14 * 86400, inviter))
|
|
if immunity.rowcount != 1:
|
|
con.rollback()
|
|
return result
|
|
con.commit()
|
|
result.update(status="awarded", inviter_units=inviter_units, invitee_units=REF_INVITEE_UNITS)
|
|
return result
|
|
except (sqlite3.Error, TypeError, ValueError, OverflowError):
|
|
if con is not None:
|
|
con.rollback()
|
|
log.exception("[ECONGUARD] referral award failed uid=%s", uid)
|
|
return result
|
|
finally:
|
|
if con is not None:
|
|
con.close()
|
|
|
|
|
|
def ledger_seen(bot_db: str, type_: str, ref: str) -> bool:
|
|
"""Уже есть строка леджера с таким (type, ref)?"""
|
|
con = _con(bot_db, 15)
|
|
try:
|
|
row = con.execute("SELECT 1 FROM econ_tx WHERE type=? AND ref=? LIMIT 1", (type_, ref)).fetchone()
|
|
return bool(row)
|
|
except Exception:
|
|
log.exception("[ECONGUARD] ledger_seen failed type=%s ref=%s", type_, ref)
|
|
return False
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# заявки (claim-first)
|
|
# --------------------------------------------------------------------------- #
|
|
def claim(bot_db: str, sql: str, params: tuple = ()) -> bool:
|
|
"""Атомарная заявка на смену состояния. True = мы первые.
|
|
|
|
Пример: ``claim(bot_db, "UPDATE duels SET status='done' WHERE id=? AND status='pending'", (did,))``
|
|
"""
|
|
con = _con(bot_db)
|
|
try:
|
|
cur = con.execute(sql, params)
|
|
con.commit()
|
|
return cur.rowcount > 0
|
|
except Exception:
|
|
log.exception("[ECONGUARD] claim failed sql=%s", sql)
|
|
try:
|
|
con.rollback()
|
|
except Exception:
|
|
pass
|
|
return False
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
def grant_once(bot_db: str, gw_db: str, uid: int, code: str, units: int,
|
|
type_: Optional[str] = None) -> int:
|
|
units = int(units)
|
|
if units <= 0:
|
|
return 0
|
|
con = _con(bot_db)
|
|
try:
|
|
cur = con.execute("INSERT OR IGNORE INTO econ_grants(uid,code,units,ts) VALUES (?,?,?,?)",
|
|
(int(uid), code, units, int(time.time())))
|
|
con.commit()
|
|
claimed = cur.rowcount > 0
|
|
except Exception:
|
|
log.exception("[ECONGUARD] grant claim failed uid=%s code=%s", uid, code)
|
|
return 0
|
|
finally:
|
|
con.close()
|
|
if not claimed:
|
|
return 0
|
|
got = mint(gw_db, bot_db, uid, units, type_ or ("achv:%s" % code),
|
|
ref="grant:%s:%s" % (code, uid))
|
|
if got <= 0:
|
|
release_grant(bot_db, uid, code)
|
|
log.warning("[ECONGUARD] grant released after failed payout uid=%s code=%s", uid, code)
|
|
return got
|
|
|
|
|
|
def release_grant(bot_db: str, uid: int, code: str) -> None:
|
|
con = _con(bot_db, 15)
|
|
try:
|
|
con.execute("DELETE FROM econ_grants WHERE uid=? AND code=?", (int(uid), code))
|
|
con.commit()
|
|
except Exception:
|
|
log.exception("[ECONGUARD] release_grant failed uid=%s code=%s", uid, code)
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
def cooldown_take(bot_db: str, key: str, seconds: int, now: Optional[int] = None) -> bool:
|
|
"""Атомарный кулдаун: True = взяли (прошлый истёк или не существовал)."""
|
|
now = int(now if now is not None else time.time())
|
|
seconds = int(seconds)
|
|
con = _con(bot_db)
|
|
try:
|
|
cur = con.execute(
|
|
"INSERT INTO kv(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v "
|
|
"WHERE CAST(kv.v AS INTEGER) <= ?", (key, str(now), now - seconds))
|
|
con.commit()
|
|
return cur.rowcount > 0
|
|
except Exception:
|
|
log.exception("[ECONGUARD] cooldown_take failed key=%s", key)
|
|
return False
|
|
finally:
|
|
con.close()
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# бэкфилл и аудит
|
|
# --------------------------------------------------------------------------- #
|
|
def grant_code(type_: str) -> Optional[str]:
|
|
"""Код одноразовой награды из типа леджера ('achv:rich100' -> 'rich100')."""
|
|
for p in ONE_TIME_PREFIXES:
|
|
if type_.startswith(p):
|
|
return type_[len(p):]
|
|
return type_ if type_ in ONE_TIME_TYPES else None
|
|
|
|
|
|
def backfill_grants(bot_db: str) -> Dict[str, int]:
|
|
"""Отметить уже выданные одноразовые награды, чтобы фикс не выдал их повторно."""
|
|
con = _con(bot_db)
|
|
inserted = scanned = 0
|
|
try:
|
|
rows = con.execute(
|
|
"SELECT DISTINCT dst, type, MAX(units) FROM econ_tx WHERE src=0 AND ("
|
|
"type LIKE 'achv:%' OR type LIKE 'streak:%' OR type='firstweek') GROUP BY dst, type").fetchall()
|
|
for uid, type_, units in rows:
|
|
code = grant_code(type_)
|
|
if not code:
|
|
continue
|
|
scanned += 1
|
|
cur = con.execute("INSERT OR IGNORE INTO econ_grants(uid,code,units,ts) VALUES (?,?,?,?)",
|
|
(int(uid), code, int(units or 0), int(time.time())))
|
|
inserted += cur.rowcount
|
|
con.commit()
|
|
finally:
|
|
con.close()
|
|
return {"scanned": scanned, "inserted": inserted}
|
|
|
|
|
|
def audit(bot_db: str, gw_db: Optional[str] = None, days: int = 7,
|
|
top: int = 10) -> Dict[str, Any]:
|
|
"""Сводка целостности: дубли начислений, повторные одноразовые, битые заявки.
|
|
|
|
Ничего не меняет - только читает.
|
|
"""
|
|
since = int(time.time()) - int(days) * 86400
|
|
out: Dict[str, Any] = {"days": days, "since": since}
|
|
con = _con(bot_db, 20)
|
|
con.row_factory = sqlite3.Row
|
|
try:
|
|
has_ref = "ref" in {r[1] for r in con.execute("PRAGMA table_info(econ_tx)")}
|
|
out["schema_ref"] = has_ref
|
|
out["ledger_rows_window"] = con.execute(
|
|
"SELECT COUNT(*) FROM econ_tx WHERE ts>=?", (since,)).fetchone()[0]
|
|
# 1) Повтор одноразовых наград (achv/streak/firstweek) - всегда баг.
|
|
out["one_time_repeats"] = [
|
|
dict(r) for r in con.execute(
|
|
"SELECT dst AS uid, type, COUNT(*) AS n, SUM(units) AS units FROM econ_tx "
|
|
"WHERE src=0 AND (type LIKE 'achv:%' OR type LIKE 'streak:%' OR type='firstweek') "
|
|
"GROUP BY dst, type HAVING COUNT(*)>1 ORDER BY n DESC LIMIT ?", (top,))]
|
|
# 2) Начисления одному uid одним типом в одну секунду - признак гонки.
|
|
out["same_second_mints"] = [
|
|
dict(r) for r in con.execute(
|
|
"SELECT dst AS uid, type, ts, COUNT(*) AS n, SUM(units) AS units FROM econ_tx "
|
|
"WHERE src=0 AND dst!=0 AND ts>=? GROUP BY dst, type, ts HAVING COUNT(*)>1 "
|
|
"ORDER BY n DESC LIMIT ?", (since, top))]
|
|
# 3) Дубли по идемпотентному ref (после деплоя их быть не должно).
|
|
out["duplicate_refs"] = [] if not has_ref else [
|
|
dict(r) for r in con.execute(
|
|
"SELECT type, ref, COUNT(*) AS n FROM econ_tx WHERE ref IS NOT NULL "
|
|
"GROUP BY type, ref HAVING COUNT(*)>1 ORDER BY n DESC LIMIT ?", (top,))]
|
|
# 4) Дуэли: несколько выплат на одну дуэль (по ref, если заполнен).
|
|
if has_ref:
|
|
out["duel_multi_payout"] = [
|
|
dict(r) for r in con.execute(
|
|
"SELECT ref, COUNT(*) AS n, SUM(units) AS units FROM econ_tx "
|
|
"WHERE type LIKE 'duel:%' AND ref IS NOT NULL GROUP BY ref HAVING COUNT(*)>1 "
|
|
"ORDER BY n DESC LIMIT ?", (top,))]
|
|
out["grants_without_payout"] = con.execute(
|
|
"SELECT COUNT(*) FROM econ_grants g WHERE NOT EXISTS ("
|
|
"SELECT 1 FROM econ_tx t WHERE t.dst=g.uid AND t.src=0 AND ("
|
|
"t.type='achv:'||g.code OR t.type='streak:'||g.code OR t.type=g.code))").fetchone()[0]
|
|
out["grants_total"] = con.execute("SELECT COUNT(*) FROM econ_grants").fetchone()[0]
|
|
out["mints_total_units_window"] = con.execute(
|
|
"SELECT COALESCE(SUM(units),0) FROM econ_tx WHERE src=0 AND ts>=?", (since,)).fetchone()[0]
|
|
out["burns_total_units_window"] = con.execute(
|
|
"SELECT COALESCE(SUM(units),0) FROM econ_tx WHERE dst=0 AND src!=0 AND ts>=?", (since,)).fetchone()[0]
|
|
stranded = [r[0] for r in con.execute(
|
|
"SELECT DISTINCT dst FROM econ_tx WHERE src=0 AND ts>=? LIMIT 500", (since,))]
|
|
finally:
|
|
con.close()
|
|
if gw_db and stranded:
|
|
missing = []
|
|
for uid in stranded:
|
|
if resolve_wallet(gw_db, bot_db, uid) is None:
|
|
missing.append(uid)
|
|
out["wallet_missing_uids"] = missing[:top]
|
|
out["wallet_missing_count"] = len(missing)
|
|
return out
|