Files
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

1031 lines
56 KiB
Python

from __future__ import annotations
import hashlib
import json
import logging
import re
import sqlite3
import time
import uuid
from contextlib import contextmanager
log = logging.getLogger("bounty-store")
SOURCE = "bounty_store:v1"
TRANSFER_SOURCE = "economy_transfer:v1"
DEFAULT_TTL = 7 * 86400
DEFAULT_CLAIM_TTL = 48 * 3600
MAX_TTL = 90 * 86400
MAX_CLAIM_TTL = 30 * 86400
MAX_INT = (1 << 63) - 1
ACTIVE_ATTEMPTS = ("claimed", "submitted", "disputed")
REVIEW_ATTEMPTS = ("submitted", "disputed")
EARNED_TYPES = frozenset(("firstweek", "ttt-win", "wquest", "subbonus", "referral"))
EARNED_ACHIEVEMENTS = frozenset((
"first_bty", "first_duel", "rich100", "rich1000", "msgs1k", "streak7", "streak30", "ref5",
))
_WAL_WARNED = False
class EconomyError(Exception):
def __init__(self, status, code, message):
self.status = int(status)
self.code = str(code)
self.message = str(message)
super().__init__(self.message)
def as_dict(self):
return {"ok": False, "status": self.status, "code": self.code, "message": self.message}
BountyError = EconomyError
def _fail(code, message, status=409):
raise EconomyError(status, code, message)
def _integer(value, name, low=1, high=MAX_INT):
if isinstance(value, bool) or not (
isinstance(value, int) or isinstance(value, str) and re.fullmatch(r"[0-9]+", value)
):
_fail("invalid_parameter", "Некорректный параметр: %s" % name, 400)
value = int(value)
if not low <= value <= high:
_fail("invalid_parameter", "Параметр вне допустимого диапазона: %s" % name, 400)
return value
def _now(value):
return int(time.time()) if value is None else _integer(value, "now")
def _text(value, name, limit, required=True):
if not isinstance(value, str) or len(value) > limit:
_fail("invalid_parameter", "Некорректный параметр: %s" % name, 400)
value = value.strip()
if required and not value:
_fail("invalid_parameter", "Поле %s не может быть пустым" % name, 400)
return value
@contextmanager
def _transaction(bot_db, gw_db):
con = None
try:
con = sqlite3.connect(str(gw_db), timeout=30, isolation_level=None)
con.row_factory = sqlite3.Row
con.execute("PRAGMA busy_timeout=30000")
con.execute("ATTACH DATABASE ? AS ledger", (str(bot_db),))
con.execute("BEGIN IMMEDIATE")
yield con
con.commit()
except EconomyError:
if con is not None:
con.rollback()
raise
except sqlite3.Error as exc:
if con is not None:
con.rollback()
log.warning("bounty transaction rolled back (%s)", type(exc).__name__)
raise EconomyError(503, "storage_unavailable", "Операция не выполнена: хранилище недоступно") from exc
finally:
if con is not None:
con.close()
def _columns(con, schema, table):
# Only fixed internal identifiers are passed here, never user strings.
return {row[1] for row in con.execute("PRAGMA %s.table_info(%s)" % (schema, table))}
def ensure_schema(bot_db, gw_db, now=None):
"""Additive, idempotent migration. Ambiguous historical rows stay untouched/held."""
current = _now(now)
global _WAL_WARNED
with _transaction(bot_db, gw_db) as con:
if not _WAL_WARNED:
modes = [str(con.execute("PRAGMA %s.journal_mode" % schema).fetchone()[0]).lower()
for schema in ("main", "ledger")]
if "wal" in modes:
log.warning("bounty WAL: power failure during attached COMMIT is not cross-file atomic")
_WAL_WARNED = True
con.execute("""CREATE TABLE IF NOT EXISTS ledger.econ_tx(
id INTEGER PRIMARY KEY AUTOINCREMENT, src INTEGER NOT NULL, dst INTEGER NOT NULL,
units INTEGER NOT NULL, type TEXT NOT NULL, ts INTEGER NOT NULL)""")
ledger_cols = _columns(con, "ledger", "econ_tx")
for name, ddl in (("ref", "TEXT"), ("wallet_id", "INTEGER"), ("bounty_id", "INTEGER"),
("bounty_worker", "INTEGER"), ("bounty_source", "TEXT")):
if name not in ledger_cols:
con.execute("ALTER TABLE ledger.econ_tx ADD COLUMN %s %s" % (name, ddl))
con.execute("CREATE UNIQUE INDEX IF NOT EXISTS ledger.ux_econ_tx_ref ON econ_tx(type,ref)")
con.execute("CREATE INDEX IF NOT EXISTS ledger.ix_bounty_econ_src ON econ_tx(src)")
con.execute("CREATE INDEX IF NOT EXISTS ledger.ix_bounty_econ_dst ON econ_tx(dst)")
con.execute("""CREATE TABLE IF NOT EXISTS ledger.bounties(
id INTEGER PRIMARY KEY AUTOINCREMENT, creator INTEGER, text TEXT, reward INTEGER,
status TEXT DEFAULT 'open', claimer INTEGER DEFAULT 0, created INTEGER)""")
cols = _columns(con, "ledger", "bounties")
migrations = (
("unit_reward", "INTEGER"), ("capacity", "INTEGER NOT NULL DEFAULT 1"),
("expires_at", "INTEGER"), ("claim_ttl", "INTEGER"),
("escrow_remaining", "INTEGER"), ("funded_units", "INTEGER"),
("paid_units", "INTEGER NOT NULL DEFAULT 0"),
("fee_units", "INTEGER NOT NULL DEFAULT 0"),
("refunded_units", "INTEGER NOT NULL DEFAULT 0"),
("refund_pending", "INTEGER NOT NULL DEFAULT 0"), ("refund_reason", "TEXT"),
("closed_reason", "TEXT"), ("store_version", "INTEGER NOT NULL DEFAULT 0"),
("legacy_review", "INTEGER NOT NULL DEFAULT 1"),
)
for name, ddl in migrations:
if name not in cols:
con.execute("ALTER TABLE ledger.bounties ADD COLUMN %s %s" % (name, ddl))
con.execute("""UPDATE ledger.bounties SET unit_reward=reward,
legacy_review=CASE WHEN status IN ('open','claimed','submitted','disputed') THEN 1 ELSE 0 END
WHERE store_version=0 AND unit_reward IS NULL""")
con.execute("""CREATE TABLE IF NOT EXISTS ledger.bounty_attempts(
bid INTEGER NOT NULL, worker INTEGER NOT NULL, status TEXT NOT NULL,
claimed_at INTEGER NOT NULL, deadline INTEGER, submitted_at INTEGER,
proof TEXT NOT NULL DEFAULT '', dispute_proof TEXT NOT NULL DEFAULT '',
closed_at INTEGER, payout_ref TEXT, payout_units INTEGER NOT NULL DEFAULT 0,
fee_units INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(bid,worker))""")
con.execute("CREATE INDEX IF NOT EXISTS ledger.ix_bounty_attempt_deadline ON bounty_attempts(status,deadline)")
con.execute("""CREATE TABLE IF NOT EXISTS ledger.bounty_operations(
ref TEXT PRIMARY KEY, bid INTEGER NOT NULL, actor INTEGER NOT NULL,
kind TEXT NOT NULL, units INTEGER NOT NULL, gross INTEGER NOT NULL,
fee INTEGER NOT NULL DEFAULT 0, slots INTEGER NOT NULL DEFAULT 0,
worker INTEGER NOT NULL DEFAULT 0, token_id INTEGER NOT NULL,
created INTEGER NOT NULL, digest TEXT NOT NULL, source TEXT NOT NULL,
funding_proof TEXT, ledger_id INTEGER NOT NULL)""")
con.execute("CREATE INDEX IF NOT EXISTS ledger.ix_bounty_operations_bid ON bounty_operations(bid)")
con.execute("""CREATE TABLE IF NOT EXISTS ledger.economy_transfers(
ref TEXT PRIMARY KEY, src INTEGER NOT NULL, dst INTEGER NOT NULL,
units INTEGER NOT NULL, net INTEGER NOT NULL, fee INTEGER NOT NULL,
created INTEGER NOT NULL, src_token_id INTEGER NOT NULL, dst_token_id INTEGER NOT NULL,
out_ledger_id INTEGER NOT NULL, in_ledger_id INTEGER NOT NULL, fee_ledger_id INTEGER NOT NULL,
digest TEXT NOT NULL, funding_proof TEXT NOT NULL, source TEXT NOT NULL)""")
con.execute("CREATE INDEX IF NOT EXISTS ledger.ix_economy_transfers_dst ON economy_transfers(dst)")
con.execute("""INSERT OR IGNORE INTO ledger.bounty_attempts(bid,worker,status,claimed_at)
SELECT id,claimer,'legacy_review',COALESCE(created,?) FROM ledger.bounties
WHERE store_version=0 AND legacy_review=1 AND claimer>0""", (current,))
return {"ok": True, "schema_version": 1}
def _user(con, uid, allow_blocked=False):
cols = _columns(con, "ledger", "users")
# A missing ban column is not permission to proceed with money.
if not {"tg_id", "token_name", "banned", "api_blocked"}.issubset(cols):
_fail("eligibility_unavailable", "Не удалось проверить ограничения аккаунта", 503)
admin = ",COALESCE(admin,0) AS admin" if "admin" in cols else ",0 AS admin"
saved_key = ",api_key" if "api_key" in cols else ",NULL AS api_key"
row = con.execute("SELECT tg_id,token_name,COALESCE(banned,0) AS banned,"
"COALESCE(api_blocked,0) AS api_blocked" + admin + saved_key +
" FROM ledger.users WHERE tg_id=?", (uid,)).fetchone()
if row is None:
_fail("user_not_found", "Аккаунт не найден", 404)
if not allow_blocked and _blocked(row):
_fail("blocked", "Операция недоступна: аккаунт заблокирован", 403)
return row
def _blocked(user):
return bool(user["banned"] or user["api_blocked"])
def _owns_name(uid, name):
return name in ("tg%d" % uid, "pm%d" % uid, "sol%d" % uid) or bool(
isinstance(name, str) and re.fullmatch(r"tg%d-k[1-9][0-9]*" % uid, name)
)
def _name_scope(uid, column):
main = "tg%d" % uid
return ("(%s IN (?,?,?) OR (%s>=? AND %s<?))" % (column, column, column),
(main, "pm%d" % uid, "sol%d" % uid, main + "-k", main + "-l"))
def _wallet(con, user, debit=False, required=True, now=None):
"""Resolve one canonical cash wallet, never a richer duplicate/fallback."""
uid = int(user["tg_id"])
canonical = "tg%d" % uid
mapped = user["token_name"]
current = _now(now)
row = None
if mapped is None or mapped == "" or mapped == canonical:
cols = _columns(con, "main", "tokens")
rows = con.execute("SELECT * FROM tokens WHERE name=? AND deleted_at IS NULL",
(canonical,)).fetchall()
saved = user["api_key"]
has_saved = saved is not None and saved != ""
if has_saved:
if not isinstance(saved, str) or not saved.strip() or "key" not in cols:
rows = []
else:
raw = saved.strip()
raw = raw[3:] if raw.startswith("sk-") else raw
rows = [r for r in rows if isinstance(r["key"], str) and r["key"] == raw]
if not raw:
rows = []
# Resolve identity before checking operational status. A disabled saved
# token never permits switching to an enabled duplicate.
if len(rows) == 1:
candidate = rows[0]
status_ok = candidate["status"] == 1 if debit else candidate["status"] in (1, 2)
expiry_ok = "expired_time" not in cols or (
type(candidate["expired_time"]) is int
and (candidate["expired_time"] == -1 or candidate["expired_time"] > current))
finite = "unlimited_quota" not in cols or (
type(candidate["unlimited_quota"]) is int and candidate["unlimited_quota"] == 0)
balance_ok = type(candidate["remain_quota"]) is int and 0 <= candidate["remain_quota"] <= MAX_INT
if status_ok and expiry_ok and finite and balance_ok:
row = candidate
if row is None and required:
_fail("wallet_unavailable", "Нет однозначно подтверждённого кошелька; средства не перемещены")
return row
def _bounty(con, bid, writable=True):
row = con.execute("SELECT * FROM ledger.bounties WHERE id=?", (bid,)).fetchone()
if row is None:
_fail("bounty_not_found", "Баунти не найдено", 404)
if writable and (int(row["store_version"] or 0) != 1 or row["legacy_review"]):
_fail("legacy_review", "Историческое эскроу удерживается до проверки происхождения средств")
return row
def _assert_owner(user, bounty, admin_ok=False):
if int(user["tg_id"]) != int(bounty["creator"]) and not (admin_ok and user["admin"]):
_fail("forbidden", "Только заказчик может выполнить это действие", 403)
def _attempts(con, bid):
return con.execute("SELECT * FROM ledger.bounty_attempts WHERE bid=? ORDER BY claimed_at,worker",
(bid,)).fetchall()
def _count(con, bid, statuses):
return int(con.execute("SELECT COUNT(*) FROM ledger.bounty_attempts WHERE bid=? AND status IN (" +
",".join("?" for _ in statuses) + ")", (bid,) + tuple(statuses)).fetchone()[0])
def _proof_valid(raw, actor, gross):
try:
proof = json.loads(raw)
fields = ("earned", "bounty_in", "outgoing", "consumed", "wallet_balance", "transferable")
if not (isinstance(proof, dict) and proof.get("version") == 1 and proof.get("uid") == actor
and all(type(proof.get(k)) is int and proof[k] >= 0 for k in fields)):
return False
transferred = proof.get("transfer_in", 0) # Existing v1 bounty proofs predate /pay.
if type(transferred) is not int or transferred < 0:
return False
headroom = proof["earned"] + proof["bounty_in"] + transferred - proof["outgoing"] - proof["consumed"]
return (headroom >= gross and proof["wallet_balance"] >= gross and proof["transferable"] >= gross
and proof["transferable"] <= min(proof["wallet_balance"], headroom))
except (TypeError, ValueError):
return False
def _matching_ledger(con, operation, type_, src, dst, units, worker, ref=None):
ref = operation["ref"] if ref is None else ref
row = con.execute("SELECT * FROM ledger.econ_tx WHERE type=? AND ref=?", (type_, ref)).fetchone()
if row is None:
return False
return (row["src"] == src and row["dst"] == dst and row["units"] == units
and row["bounty_id"] == operation["bid"] and row["bounty_worker"] == worker
and row["bounty_source"] == SOURCE and row["ts"] == operation["created"]
and (type_ == "bounty:fee" or
row["id"] == operation["ledger_id"] and row["wallet_id"] == operation["token_id"]))
def _finance_valid(con, bounty):
"""Never infer a payout/refund entitlement from a type/ref label alone."""
try:
if bounty["store_version"] != 1 or bounty["legacy_review"]:
return False
reward, capacity, creator = bounty["unit_reward"], bounty["capacity"], bounty["creator"]
if type(reward) is not int or reward <= 0 or type(capacity) is not int or not 1 <= capacity <= 100:
return False
ops = con.execute("SELECT * FROM ledger.bounty_operations WHERE bid=?", (bounty["id"],)).fetchall()
funded = paid = fees = refunded = slots = creates = refunds = 0
paid_workers = set()
for op in ops:
if (op["source"] != SOURCE or op["actor"] != creator or not op["digest"]
or not all(type(op[k]) is int and op[k] >= 0 for k in
("units", "gross", "fee", "slots", "worker", "token_id", "created", "ledger_id"))
or op["token_id"] == 0 or op["ledger_id"] == 0):
return False
token = con.execute("SELECT name FROM tokens WHERE id=?", (op["token_id"],)).fetchone()
recipient = op["worker"] if op["kind"] == "payout" else creator
if token is None or not _owns_name(recipient, token["name"]):
return False
if op["kind"] in ("create", "topup"):
if (not 1 <= op["slots"] <= 100 or op["gross"] != reward * op["slots"]
or op["units"] != op["gross"] or op["fee"] != 0 or op["worker"] != 0
or not _proof_valid(op["funding_proof"], creator, op["gross"])
or not _matching_ledger(con, op, "bounty:escrow", creator, 0, op["gross"], 0)):
return False
creates += op["kind"] == "create"
slots += op["slots"]
funded += op["gross"]
elif op["kind"] == "payout":
worker = op["worker"]
attempt = con.execute("SELECT * FROM ledger.bounty_attempts WHERE bid=? AND worker=?",
(bounty["id"], worker)).fetchone()
net = reward * 95 // 100
if (worker <= 0 or worker == creator or worker in paid_workers or op["slots"] != 1
or op["gross"] != reward or op["units"] != net or op["fee"] != reward - net
or op["ref"] != "bounty:v1:%d:payout:%d" % (bounty["id"], worker)
or attempt is None or attempt["status"] != "paid"
or attempt["payout_ref"] != op["ref"] or attempt["payout_units"] != net
or attempt["fee_units"] != op["fee"] or attempt["closed_at"] != op["created"]
or not _matching_ledger(con, op, "bounty:payout", 0, worker, net, worker)
or not _matching_ledger(con, op, "bounty:fee", 0, 0, op["fee"], worker,
ref=op["ref"] + ":fee")):
return False
paid_workers.add(worker)
paid += reward
fees += op["fee"]
elif op["kind"] == "refund":
if (op["units"] <= 0 or op["gross"] != op["units"] or op["fee"] != 0
or op["worker"] != 0 or op["units"] % reward
or op["slots"] != op["units"] // reward or not bounty["closed_reason"]
or op["ref"] != "bounty:v1:%d:refund" % bounty["id"]
or not _matching_ledger(con, op, "bounty:refund", 0, creator, op["units"], 0)):
return False
refunds += 1
refunded += op["units"]
else:
return False
active = _count(con, bounty["id"], ACTIVE_ATTEMPTS)
paid_count = _count(con, bounty["id"], ("paid",))
return (creates == 1 and refunds <= 1 and slots == capacity and funded == reward * capacity
and funded == bounty["funded_units"] and paid == bounty["paid_units"]
and fees == bounty["fee_units"] and refunded == bounty["refunded_units"]
and paid_count == len(paid_workers)
and type(bounty["escrow_remaining"]) is int
and bounty["escrow_remaining"] == funded - paid - refunded >= active * reward
and 0 <= bounty["refund_pending"] <= bounty["escrow_remaining"])
except (TypeError, ValueError, OverflowError):
return False
def _assert_finance(con, bounty):
if not _finance_valid(con, bounty):
_fail("escrow_unverified", "Эскроу удерживается: требуется проверка финансовых записей")
def _earned_type(type_):
return type_ in EARNED_TYPES or type_ in {"achv:" + key for key in EARNED_ACHIEVEMENTS}
def _usage(con, uid):
scope, params = _name_scope(uid, "name")
token_cols = _columns(con, "main", "tokens")
has_counter = "used_quota" in token_cols
fields = "id,name" + (",used_quota" if has_counter else "")
tokens = [r for r in con.execute("SELECT " + fields + " FROM tokens WHERE " + scope, params)
if _owns_name(uid, r["name"])]
counters = {}
if has_counter:
for row in tokens:
if type(row["used_quota"]) is not int or row["used_quota"] < 0:
return None, {token["id"] for token in tokens}
counters[row["name"]] = counters.get(row["name"], 0) + row["used_quota"]
log_cols = _columns(con, "main", "logs")
has_logs = {"token_name", "quota", "type"}.issubset(log_cols)
logged = {}
if has_logs:
scope, params = _name_scope(uid, "token_name")
rows = con.execute("SELECT token_name,"
"SUM(CASE WHEN quota>0 THEN quota ELSE 0 END) AS used,"
"SUM(CASE WHEN typeof(quota)!='integer' THEN 1 ELSE 0 END) AS invalid "
"FROM logs WHERE type=2 AND " + scope + " GROUP BY token_name", params)
for row in rows:
if _owns_name(uid, row["token_name"]):
if row["invalid"] or type(row["used"]) is not int:
return None, {token["id"] for token in tokens}
logged[row["token_name"]] = row["used"]
if not has_counter and not has_logs:
return None, {row["id"] for row in tokens}
# Compare each exact identity separately: max(total counters,total logs)
consumed = sum(max(counters.get(name, 0), logged.get(name, 0))
for name in counters.keys() | logged.keys())
return consumed, {row["id"] for row in tokens}
def _transfer_valid(con, receipt):
"""Trust only atomic v1 transfer receipts and their exact three ledger rows."""
try:
fields = ("src", "dst", "units", "net", "fee", "created", "src_token_id", "dst_token_id",
"out_ledger_id", "in_ledger_id", "fee_ledger_id")
if (receipt["source"] != TRANSFER_SOURCE
or not all(type(receipt[key]) is int and 0 <= receipt[key] <= MAX_INT for key in fields)):
return False
src, dst, units = receipt["src"], receipt["dst"], receipt["units"]
if (min(src, dst, units, receipt["created"], receipt["src_token_id"], receipt["dst_token_id"]) <= 0
or src == dst or receipt["src_token_id"] == receipt["dst_token_id"]
or receipt["net"] != units * 95 // 100 or receipt["fee"] != units - receipt["net"]
or receipt["digest"] != _digest({"src": src, "dst": dst, "units": units})
or not re.fullmatch(r"bounty:v1:transfer:%d:(?:[0-9a-f]{32}|[0-9a-f]{64})" % src, receipt["ref"])
or not _proof_valid(receipt["funding_proof"], src, units)):
return False
for uid, token_id in ((src, receipt["src_token_id"]), (dst, receipt["dst_token_id"])):
token = con.execute("SELECT name FROM tokens WHERE id=?", (token_id,)).fetchone()
if token is None or token["name"] != "tg%d" % uid:
return False
expected = (
("out_ledger_id", "pay:out", src, 0, units),
("in_ledger_id", "pay:in", 0, dst, receipt["net"]),
("fee_ledger_id", "pay:fee", 0, 0, receipt["fee"]),
)
if len({receipt[field] for field, *_ in expected}) != 3:
return False
for field, type_, sender, recipient, amount in expected:
row = con.execute("SELECT * FROM ledger.econ_tx WHERE id=?", (receipt[field],)).fetchone()
if (row is None or row["src"] != sender or row["dst"] != recipient or row["units"] != amount
or row["type"] != type_ or row["ref"] != receipt["ref"] or row["ts"] != receipt["created"]
or row["wallet_id"] is not None or row["bounty_id"] is not None
or row["bounty_worker"] is not None or row["bounty_source"] is not None):
return False
return True
except (TypeError, ValueError, OverflowError):
return False
def _funding(con, user, now=None):
uid = int(user["tg_id"])
wallet = _wallet(con, user, debit=True, required=False, now=now)
readable = wallet or _wallet(con, user, required=False, now=now)
balance = int(readable["remain_quota"]) if readable is not None else 0
usage, token_ids = _usage(con, uid)
earned = bounty_in = transfer_in = 0
checked = {}
payout_cols = _columns(con, "main", "econ_payouts")
receipts_available = {"ref", "token_id", "units", "created"}.issubset(payout_cols)
rows = con.execute("SELECT * FROM ledger.econ_tx WHERE dst=? AND src=0 AND units>0 "
"AND ref IS NOT NULL AND ref!='' ORDER BY id", (uid,)).fetchall()
for row in rows:
if type(row["units"]) is not int or not isinstance(row["ref"], str) or not row["ref"].strip():
continue
type_ = row["type"]
two_phase = type_ == "quest" or bool(isinstance(type_, str) and re.fullmatch(r"streak:[1-9][0-9]*", type_))
if two_phase:
if not receipts_available or row["wallet_id"] not in token_ids:
continue
receipt = con.execute("SELECT * FROM econ_payouts WHERE ref=?", (row["ref"],)).fetchone()
# token_id=0 is only a legacy migration marker, NOT a credit receipt.
if (receipt is not None and receipt["token_id"] == row["wallet_id"]
and receipt["token_id"] > 0 and receipt["units"] == row["units"]
and type(receipt["created"]) is int and receipt["created"] > 0):
earned += row["units"]
elif _earned_type(type_):
# These allowlisted awards use econ_guard's attached, atomic mint.
if row["wallet_id"] is None or row["wallet_id"] in token_ids:
earned += row["units"]
elif type_ in ("bounty:payout", "bounty:refund") and row["bounty_source"] == SOURCE:
bid = row["bounty_id"]
if bid not in checked:
b = con.execute("SELECT * FROM ledger.bounties WHERE id=?", (bid,)).fetchone()
checked[bid] = b is not None and _finance_valid(con, b)
if not checked[bid]:
continue
op = con.execute("SELECT * FROM ledger.bounty_operations WHERE ref=?", (row["ref"],)).fetchone()
expected = "payout" if type_ == "bounty:payout" else "refund"
if op is not None and op["kind"] == expected and op["ledger_id"] == row["id"]:
bounty_in += row["units"]
elif type_ == "pay:in":
receipt = con.execute("SELECT * FROM ledger.economy_transfers WHERE ref=?", (row["ref"],)).fetchone()
if (receipt is not None and receipt["dst"] == uid and receipt["in_ledger_id"] == row["id"]
and _transfer_valid(con, receipt)):
transfer_in += row["units"]
outgoing = 0
for row in con.execute("SELECT units FROM ledger.econ_tx WHERE src=?", (uid,)):
if type(row["units"]) is not int or row["units"] < 0:
usage = None
continue
outgoing += row["units"]
headroom = max(0, earned + bounty_in + transfer_in - outgoing - (usage or 0)) if usage is not None else 0
transferable = min(balance, headroom) if wallet is not None and not _blocked(user) else 0
if _blocked(user):
code = "blocked"
elif usage is None or earned + bounty_in + transfer_in == 0:
code = "funding_unverified"
elif wallet is None:
code = "wallet_unavailable"
elif transferable == 0:
code = "insufficient_transferable"
else:
code = None
return {"balance": balance, "wallet_balance": balance, "transferable": transferable,
"transferable_balance": transferable, "earned": earned, "bounty_in": bounty_in,
"transfer_in": transfer_in, "outgoing": outgoing, "consumed": usage, "funding_code": code,
"funding_policy": "settled_earned_and_verified_bounty_pay_less_lifetime_consumption_and_outgoing"}
def _reserve(con, user, units, bid, ref, kind, slots, digest, current):
funding = _funding(con, user, now=current)
if funding["transferable"] < units:
code = funding["funding_code"] or "insufficient_transferable"
if code == "funding_unverified":
_fail(code, "Нет подтверждённого источника переводимых средств; API-квота не считается деньгами")
_fail(code, "Недостаточно подтверждённых переводимых средств; API-квота не списана")
wallet = _wallet(con, user, debit=True, now=current)
proof = {k: funding[k] for k in ("earned", "bounty_in", "transfer_in", "outgoing", "wallet_balance", "consumed", "transferable")}
proof.update(version=1, uid=int(user["tg_id"]))
ledger_id = _ledger(con, int(user["tg_id"]), 0, units, "bounty:escrow", ref,
int(wallet["id"]), bid, 0, current)
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota-? WHERE id=? AND remain_quota>=? "
"AND status=1 AND deleted_at IS NULL", (units, wallet["id"], units))
if cur.rowcount != 1:
_fail("wallet_unavailable", "Списание не выполнено; баланс или доступность кошелька изменились")
_operation(con, ref, bid, int(user["tg_id"]), kind, units, units, 0, slots, 0,
int(wallet["id"]), current, digest, ledger_id,
json.dumps(proof, sort_keys=True, separators=(",", ":")))
def _ledger(con, src, dst, units, type_, ref, wallet_id, bid, worker, current):
return int(con.execute("INSERT INTO ledger.econ_tx(src,dst,units,type,ts,ref,wallet_id,"
"bounty_id,bounty_worker,bounty_source) VALUES(?,?,?,?,?,?,?,?,?,?)",
(src, dst, units, type_, current, ref, wallet_id, bid, worker, SOURCE)).lastrowid)
def _operation(con, ref, bid, actor, kind, units, gross, fee, slots, worker, token_id,
current, digest, ledger_id, funding_proof=None):
con.execute("INSERT INTO ledger.bounty_operations(ref,bid,actor,kind,units,gross,fee,slots,worker,"
"token_id,created,digest,source,funding_proof,ledger_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(ref, bid, actor, kind, units, gross, fee, slots, worker, token_id, current,
digest, SOURCE, funding_proof, ledger_id))
def _credit(con, wallet_id, units):
cur = con.execute("UPDATE tokens SET remain_quota=remain_quota+? WHERE id=? AND status IN (1,2) "
"AND deleted_at IS NULL AND remain_quota>=0 AND remain_quota<=?",
(units, wallet_id, MAX_INT - units))
if cur.rowcount != 1:
_fail("wallet_unavailable", "Зачисление не выполнено; средства остаются в эскроу")
def _digest(payload):
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
separators=(",", ":")).encode("utf-8")).hexdigest()
def _request_ref(kind, uid, request_id):
if request_id is None:
key = uuid.uuid4().hex
else:
request_id = _text(request_id, "request_id", 128)
if any(ord(c) < 32 or ord(c) == 127 for c in request_id):
_fail("invalid_parameter", "Некорректный request_id", 400)
key = hashlib.sha256(request_id.encode("utf-8")).hexdigest()
return "bounty:v1:%s:%d:%s" % (kind, uid, key)
def _replay(con, ref, digest, actor, kind):
op = con.execute("SELECT * FROM ledger.bounty_operations WHERE ref=?", (ref,)).fetchone()
if op is None:
return None
if op["digest"] != digest or op["actor"] != actor or op["kind"] != kind or op["source"] != SOURCE:
_fail("request_conflict", "request_id уже использован для другой операции")
bounty = _bounty(con, op["bid"])
_assert_finance(con, bounty)
return bounty
def _refresh(con, bid):
bounty = _bounty(con, bid)
disputed = _count(con, bid, ("disputed",))
submitted = _count(con, bid, ("submitted",))
claimed = _count(con, bid, ("claimed",))
remaining = bounty["escrow_remaining"] // bounty["unit_reward"]
if bounty["refund_pending"]:
status = "refund_held"
elif remaining == 0 and bounty["paid_units"] == bounty["funded_units"]:
status = "done"
elif bounty["closed_reason"]:
status = "disputed" if disputed else "submitted" if submitted else bounty["closed_reason"]
elif remaining > disputed + submitted + claimed:
status = "open"
else:
status = "disputed" if disputed else "submitted" if submitted else "claimed"
first = con.execute("SELECT worker FROM ledger.bounty_attempts WHERE bid=? AND status IN "
"('claimed','submitted','disputed') ORDER BY claimed_at,worker LIMIT 1", (bid,)).fetchone()
con.execute("UPDATE ledger.bounties SET status=?,claimer=? WHERE id=?",
(status, int(first[0]) if first else 0, bid))
return _bounty(con, bid)
def _refund(con, bid, current):
bounty = _bounty(con, bid)
held = _count(con, bid, REVIEW_ATTEMPTS) * bounty["unit_reward"]
refundable = bounty["escrow_remaining"] - held
if refundable < 0:
_fail("escrow_unverified", "Эскроу удерживается: несогласованный резерв")
con.execute("UPDATE ledger.bounties SET refund_pending=?,refund_reason=NULL WHERE id=?", (refundable, bid))
if not refundable:
return _refresh(con, bid)
creator = _user(con, int(bounty["creator"]), allow_blocked=True)
if _blocked(creator):
con.execute("UPDATE ledger.bounties SET refund_reason='blocked' WHERE id=?", (bid,))
return _refresh(con, bid)
wallet = _wallet(con, creator, required=False, now=current)
if wallet is None:
con.execute("UPDATE ledger.bounties SET refund_reason='wallet_unavailable' WHERE id=?", (bid,))
return _refresh(con, bid)
ref = "bounty:v1:%d:refund" % bid
ledger_id = _ledger(con, 0, int(bounty["creator"]), refundable, "bounty:refund", ref,
wallet["id"], bid, 0, current)
_credit(con, wallet["id"], refundable)
_operation(con, ref, bid, int(bounty["creator"]), "refund", refundable, refundable, 0,
refundable // bounty["unit_reward"], 0, wallet["id"], current,
_digest({"bid": bid, "kind": "refund", "units": refundable}), ledger_id)
con.execute("UPDATE ledger.bounties SET escrow_remaining=escrow_remaining-?,"
"refunded_units=refunded_units+?,refund_pending=0,refund_reason=NULL WHERE id=?",
(refundable, refundable, bid))
return _refresh(con, bid)
def _close(con, bid, reason, current):
bounty = _bounty(con, bid)
if not bounty["closed_reason"]:
con.execute("UPDATE ledger.bounties SET closed_reason=? WHERE id=?", (reason, bid))
con.execute("UPDATE ledger.bounty_attempts SET status=?,closed_at=? WHERE bid=? AND status='claimed'",
("expired" if reason == "expired" else "cancelled", current, bid))
return _refund(con, bid, current)
def _advance(con, bid, current):
bounty = _bounty(con, bid)
_assert_finance(con, bounty)
con.execute("UPDATE ledger.bounty_attempts SET status='expired',closed_at=? "
"WHERE bid=? AND status='claimed' AND deadline<=?", (current, bid, current))
if bounty["closed_reason"]:
if bounty["refund_pending"]:
_refund(con, bid, current)
elif bounty["expires_at"] <= current:
_close(con, bid, "expired", current)
return _refresh(con, bid)
def _view(con, bounty, viewer):
bid = int(bounty["id"])
legacy = int(bounty["store_version"] or 0) != 1
assignments = []
for attempt in _attempts(con, bid):
item = {"worker": int(attempt["worker"]), "uid": int(attempt["worker"]),
"status": attempt["status"], "claimed_at": attempt["claimed_at"],
"deadline": attempt["deadline"], "submitted_at": attempt["submitted_at"],
"payout_units": attempt["payout_units"], "fee_units": attempt["fee_units"]}
if int(viewer["tg_id"]) in (int(bounty["creator"]), int(attempt["worker"])) or viewer["admin"]:
item.update(proof=attempt["proof"], dispute_proof=attempt["dispute_proof"])
assignments.append(item)
completed = sum(item["status"] == "paid" for item in assignments)
active = sum(item["status"] in ACTIVE_ATTEMPTS for item in assignments)
integrity_review = not legacy and not _finance_valid(con, bounty)
remaining = (bounty["escrow_remaining"] // bounty["unit_reward"]) if not legacy and not integrity_review else 0
available = max(0, remaining - active) if not legacy and not integrity_review and not bounty["closed_reason"] else 0
return {"ok": True, "id": bid, "bid": bid, "creator": bounty["creator"], "text": bounty["text"],
"reward": bounty["unit_reward"] or bounty["reward"],
"unit_reward": bounty["unit_reward"] or bounty["reward"], "capacity": bounty["capacity"],
"remaining": remaining, "available": available, "available_slots": available,
"completed": completed, "active": active, "created": bounty["created"],
"status": "legacy_review" if bounty["legacy_review"] else "escrow_review" if integrity_review else bounty["status"],
"legacy_review": bool(bounty["legacy_review"]), "legacy_status": bounty["status"] if legacy else None,
"integrity_review": integrity_review,
"legacy_nominal_escrow": bounty["reward"] if legacy and bounty["legacy_review"] else 0,
"escrow_remaining": bounty["escrow_remaining"], "funded_units": bounty["funded_units"],
"paid_units": bounty["paid_units"], "fee_units": bounty["fee_units"],
"refunded_units": bounty["refunded_units"], "refund_pending": bounty["refund_pending"],
"refund_reason": bounty["refund_reason"], "closed_reason": bounty["closed_reason"],
"expires_at": bounty["expires_at"], "claim_ttl": bounty["claim_ttl"],
"assignments": assignments, "review_pending": sum(a["status"] in REVIEW_ATTEMPTS for a in assignments)}
def _result(con, bid, user, replayed=False, operation_units=0, now=None, **extra):
result = _view(con, _bounty(con, bid, writable=False), user)
result.update(_funding(con, user, now=now))
result.update(replayed=bool(replayed), operation_units=operation_units)
result.update(extra)
return result
def transfer(bot_db, gw_db, src, dst, units, request_id=None, now=None):
"""Transfer only proved entitlement; old pay:in never establishes provenance."""
src, dst = _integer(src, "src"), _integer(dst, "dst")
units, current = _integer(units, "units"), _now(now)
if src == dst:
_fail("self_transfer", "Нельзя переводить средства самому себе", 400)
ref = _request_ref("transfer", src, request_id)
digest = _digest({"src": src, "dst": dst, "units": units})
net, fee = units * 95 // 100, units - units * 95 // 100
with _transaction(bot_db, gw_db) as con:
sender, recipient = _user(con, src), _user(con, dst)
existing = con.execute("SELECT * FROM ledger.economy_transfers WHERE ref=?", (ref,)).fetchone()
if existing is not None:
if existing["digest"] != digest or existing["src"] != src or existing["dst"] != dst:
_fail("request_conflict", "request_id уже использован для другого перевода")
if not _transfer_valid(con, existing):
_fail("transfer_unverified", "Перевод удерживается до проверки финансовых записей")
return {"ok": True, "sent_units": 0, "fee_units": 0, "gross_units": 0, "replayed": True,
"original_sent_units": existing["net"], "original_fee_units": existing["fee"], "ref": ref}
source_wallet = _wallet(con, sender, debit=True, now=current)
target_wallet = _wallet(con, recipient, now=current)
funding = _funding(con, sender, now=current)
if funding["transferable"] < units:
code = funding["funding_code"] or "insufficient_transferable"
message = ("Нет подтверждённого источника переводимых средств; API-квота не считается деньгами"
if code == "funding_unverified" else
"Недостаточно подтверждённых переводимых средств; перевод не выполнен")
_fail(code, message)
proof = {key: funding[key] for key in
("earned", "bounty_in", "transfer_in", "outgoing", "wallet_balance", "consumed", "transferable")}
proof.update(version=1, uid=src)
ledger_ids = []
for sender_uid, recipient_uid, amount, type_ in (
(src, 0, units, "pay:out"), (0, dst, net, "pay:in"), (0, 0, fee, "pay:fee"),
):
# Deliberately NULL wallet_id: quest reconciliation must never mint /pay.
ledger_ids.append(int(con.execute(
"INSERT INTO ledger.econ_tx(src,dst,units,type,ts,ref) VALUES(?,?,?,?,?,?)",
(sender_uid, recipient_uid, amount, type_, current, ref)).lastrowid))
debited = con.execute("UPDATE tokens SET remain_quota=remain_quota-? WHERE id=? "
"AND remain_quota>=? AND status=1 AND deleted_at IS NULL",
(units, source_wallet["id"], units))
if debited.rowcount != 1:
_fail("wallet_unavailable", "Списание не выполнено: кошелёк недоступен")
_credit(con, target_wallet["id"], net)
con.execute("INSERT INTO ledger.economy_transfers(ref,src,dst,units,net,fee,created,src_token_id,"
"dst_token_id,out_ledger_id,in_ledger_id,fee_ledger_id,digest,funding_proof,source) "
"VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(ref, src, dst, units, net, fee, current, source_wallet["id"], target_wallet["id"],
*ledger_ids, digest, json.dumps(proof, sort_keys=True, separators=(",", ":")), TRANSFER_SOURCE))
receipt = con.execute("SELECT * FROM ledger.economy_transfers WHERE ref=?", (ref,)).fetchone()
if not _transfer_valid(con, receipt):
_fail("transfer_unverified", "Перевод не выполнен: финансовые записи не согласованы")
return {"ok": True, "sent_units": net, "fee_units": fee, "gross_units": units,
"replayed": False, "ref": ref}
def create(bot_db, gw_db, uid, text, reward, slots=1, ttl=DEFAULT_TTL,
claim_ttl=DEFAULT_CLAIM_TTL, request_id=None, now=None):
uid = _integer(uid, "uid")
text = _text(text, "text", 2000)
reward = _integer(reward, "reward")
slots = _integer(slots, "slots", 1, 100)
ttl = _integer(ttl, "ttl", 1, MAX_TTL)
claim_ttl = _integer(claim_ttl, "claim_ttl", 1, MAX_CLAIM_TTL)
units = reward * slots
current = _now(now)
if units > MAX_INT or current > MAX_INT - ttl:
_fail("invalid_parameter", "Сумма или срок слишком велики", 400)
ref = _request_ref("create", uid, request_id)
digest = _digest({"uid": uid, "text": text, "reward": reward, "slots": slots,
"ttl": ttl, "claim_ttl": claim_ttl})
with _transaction(bot_db, gw_db) as con:
user = _user(con, uid)
previous = _replay(con, ref, digest, uid, "create")
if previous is not None:
return _result(con, previous["id"], user, replayed=True, now=current)
bid = int(con.execute("INSERT INTO ledger.bounties(creator,text,reward,status,claimer,created,"
"unit_reward,capacity,expires_at,claim_ttl,escrow_remaining,funded_units,"
"store_version,legacy_review) VALUES(?,?,?,'open',0,?,?,?,?,?,?,?,1,0)",
(uid, text, reward, current, reward, slots, current + ttl, claim_ttl,
units, units)).lastrowid)
_reserve(con, user, units, bid, ref, "create", slots, digest, current)
_assert_finance(con, _bounty(con, bid))
return _result(con, bid, user, operation_units=units, now=current)
def claim(bot_db, gw_db, uid, bid, now=None):
uid, bid, current = _integer(uid, "uid"), _integer(bid, "bid"), _now(now)
with _transaction(bot_db, gw_db) as con:
user = _user(con, uid)
bounty = _advance(con, bid, current)
_user(con, int(bounty["creator"]))
if uid == bounty["creator"]:
_fail("creator_cannot_claim", "Нельзя взять собственное баунти", 403)
previous = con.execute("SELECT * FROM ledger.bounty_attempts WHERE bid=? AND worker=?", (bid, uid)).fetchone()
if previous is not None:
if previous["status"] in ACTIVE_ATTEMPTS and not bounty["closed_reason"]:
return _result(con, bid, user, replayed=True, now=current)
_fail("worker_already_attempted", "Повторная попытка этого исполнителя для данного баунти запрещена")
if bounty["closed_reason"] or bounty["expires_at"] <= current:
_fail("bounty_closed", "Баунти закрыто или истекло")
available = bounty["escrow_remaining"] // bounty["unit_reward"] - _count(con, bid, ACTIVE_ATTEMPTS)
if available <= 0:
_fail("no_capacity", "Все места уже заняты")
deadline = min(bounty["expires_at"], current + bounty["claim_ttl"])
con.execute("INSERT INTO ledger.bounty_attempts(bid,worker,status,claimed_at,deadline) "
"VALUES(?,?,'claimed',?,?)", (bid, uid, current, deadline))
_refresh(con, bid)
return _result(con, bid, user, now=current)
def submit(bot_db, gw_db, uid, bid, proof, now=None):
uid, bid, current = _integer(uid, "uid"), _integer(bid, "bid"), _now(now)
proof = _text(proof, "proof", 4000)
with _transaction(bot_db, gw_db) as con:
user = _user(con, uid)
bounty = _advance(con, bid, current)
_user(con, int(bounty["creator"]))
attempt = con.execute("SELECT * FROM ledger.bounty_attempts WHERE bid=? AND worker=?", (bid, uid)).fetchone()
if attempt is None:
_fail("not_assigned", "Баунти не взято этим исполнителем", 403)
if attempt["status"] in REVIEW_ATTEMPTS and attempt["proof"] == proof:
return _result(con, bid, user, replayed=True, now=current)
if attempt["status"] != "claimed" or bounty["closed_reason"] or attempt["deadline"] <= current:
_fail("attempt_closed", "Попытка закрыта или срок сдачи истёк")
con.execute("UPDATE ledger.bounty_attempts SET status='submitted',proof=?,submitted_at=? "
"WHERE bid=? AND worker=? AND status='claimed'", (proof, current, bid, uid))
_refresh(con, bid)
return _result(con, bid, user, now=current)
def _select_attempt(con, bid, worker, include_paid=False):
if worker is not None:
worker = _integer(worker, "worker")
attempt = con.execute("SELECT * FROM ledger.bounty_attempts WHERE bid=? AND worker=?", (bid, worker)).fetchone()
if attempt is None:
_fail("not_assigned", "Исполнитель не найден", 404)
return attempt
statuses = REVIEW_ATTEMPTS + (("paid",) if include_paid else ())
rows = con.execute("SELECT * FROM ledger.bounty_attempts WHERE bid=? AND status IN (" +
",".join("?" for _ in statuses) + ") ORDER BY worker", (bid,) + statuses).fetchall()
if not rows:
_fail("not_submitted", "Нет сданной работы для проверки")
if len(rows) != 1:
_fail("worker_required", "Укажи исполнителя: у баунти несколько работ", 400)
return rows[0]
def approve(bot_db, gw_db, uid, bid, worker=None, now=None):
uid, bid, current = _integer(uid, "uid"), _integer(bid, "bid"), _now(now)
with _transaction(bot_db, gw_db) as con:
user = _user(con, uid)
bounty = _advance(con, bid, current)
_assert_owner(user, bounty, admin_ok=True)
creator = _user(con, int(bounty["creator"]))
attempt = _select_attempt(con, bid, worker, include_paid=True)
recipient = _user(con, int(attempt["worker"]))
if attempt["status"] == "paid":
return _result(con, bid, user, replayed=True, worker=attempt["worker"], payout_units=0, fee=0, now=current)
if attempt["status"] not in REVIEW_ATTEMPTS:
_fail("not_submitted", "Можно оплатить только сданную работу")
wallet = _wallet(con, recipient, now=current)
reward = int(bounty["unit_reward"])
net, fee = reward * 95 // 100, reward - reward * 95 // 100
if bounty["escrow_remaining"] - bounty["refund_pending"] < reward:
_fail("escrow_unverified", "Для выплаты нет подтверждённого резерва")
ref = "bounty:v1:%d:payout:%d" % (bid, attempt["worker"])
ledger_id = _ledger(con, 0, int(attempt["worker"]), net, "bounty:payout", ref,
wallet["id"], bid, int(attempt["worker"]), current)
_ledger(con, 0, 0, fee, "bounty:fee", ref + ":fee", None, bid, int(attempt["worker"]), current)
_credit(con, wallet["id"], net)
_operation(con, ref, bid, int(creator["tg_id"]), "payout", net, reward, fee, 1,
int(attempt["worker"]), wallet["id"], current,
_digest({"bid": bid, "worker": int(attempt["worker"]), "kind": "payout"}), ledger_id)
con.execute("UPDATE ledger.bounty_attempts SET status='paid',closed_at=?,payout_ref=?,"
"payout_units=?,fee_units=? WHERE bid=? AND worker=?",
(current, ref, net, fee, bid, attempt["worker"]))
con.execute("UPDATE ledger.bounties SET escrow_remaining=escrow_remaining-?,paid_units=paid_units+?,"
"fee_units=fee_units+? WHERE id=?", (reward, reward, fee, bid))
_refresh(con, bid)
_assert_finance(con, _bounty(con, bid))
return _result(con, bid, user, operation_units=net, worker=int(attempt["worker"]), payout_units=net, fee=fee, now=current)
def dispute(bot_db, gw_db, uid, bid, proof="", worker=None, now=None):
"""Hold submitted work for explicit owner/admin review; never auto-resolve."""
uid, bid, current = _integer(uid, "uid"), _integer(bid, "bid"), _now(now)
proof = _text(proof, "proof", 4000, required=False)
with _transaction(bot_db, gw_db) as con:
user = _user(con, uid)
bounty = _advance(con, bid, current)
_user(con, int(bounty["creator"]))
if uid == bounty["creator"] or user["admin"]:
attempt = _select_attempt(con, bid, worker)
else:
if worker is not None and _integer(worker, "worker") != uid:
_fail("forbidden", "Нельзя оспорить чужую работу", 403)
attempt = _select_attempt(con, bid, uid)
_user(con, int(attempt["worker"]))
if attempt["status"] not in REVIEW_ATTEMPTS:
_fail("not_submitted", "Можно оспорить только сданную работу")
replayed = attempt["status"] == "disputed" and attempt["dispute_proof"] == proof
con.execute("UPDATE ledger.bounty_attempts SET status='disputed',dispute_proof=? WHERE bid=? AND worker=?",
(proof, bid, attempt["worker"]))
_refresh(con, bid)
return _result(con, bid, user, replayed=replayed, worker=int(attempt["worker"]), now=current)
def cancel(bot_db, gw_db, uid, bid, now=None):
uid, bid, current = _integer(uid, "uid"), _integer(bid, "bid"), _now(now)
with _transaction(bot_db, gw_db) as con:
# Cancellation may record the intent to close while blocked, but never
# reports a successful refund. expire/cancel can retry after unblock.
user = _user(con, uid, allow_blocked=True)
bounty = _bounty(con, bid)
_assert_owner(user, bounty)
_assert_finance(con, bounty)
was_closed = bool(bounty["closed_reason"])
refunded_before = bounty["refunded_units"]
if not bounty["closed_reason"] and bounty["expires_at"] <= current:
_close(con, bid, "expired", current)
else:
_close(con, bid, "cancelled", current)
refunded_now = _bounty(con, bid)["refunded_units"] - refunded_before
result = _result(con, bid, user, replayed=was_closed and not refunded_now,
operation_units=refunded_now, refund_units=refunded_now, now=current)
if result["refund_pending"]:
result.update(ok=False, code=result["refund_reason"] or "refund_held",
message="Возврат удерживается в эскроу до снятия ограничений/проверки кошелька")
return result
def topup(bot_db, gw_db, uid, bid, slots, request_id=None, now=None):
uid, bid, current = _integer(uid, "uid"), _integer(bid, "bid"), _now(now)
slots = _integer(slots, "slots", 1, 100)
ref = _request_ref("topup", uid, request_id)
digest = _digest({"uid": uid, "bid": bid, "slots": slots})
with _transaction(bot_db, gw_db) as con:
user = _user(con, uid)
bounty = _bounty(con, bid)
_assert_owner(user, bounty)
previous = _replay(con, ref, digest, uid, "topup")
if previous is not None:
return _result(con, bid, user, replayed=True, now=current)
bounty = _advance(con, bid, current)
if bounty["closed_reason"] or bounty["expires_at"] <= current:
_fail("bounty_closed", "Закрытое или истёкшее баунти нельзя пополнить")
if bounty["capacity"] + slots > 100:
_fail("capacity_limit", "Не более 100 оплаченных мест на одно баунти", 400)
units = bounty["unit_reward"] * slots
if bounty["funded_units"] > MAX_INT - units:
_fail("invalid_parameter", "Сумма слишком велика", 400)
_reserve(con, user, units, bid, ref, "topup", slots, digest, current)
con.execute("UPDATE ledger.bounties SET capacity=capacity+?,funded_units=funded_units+?,"
"escrow_remaining=escrow_remaining+? WHERE id=?", (slots, units, units, bid))
_refresh(con, bid)
_assert_finance(con, _bounty(con, bid))
return _result(con, bid, user, operation_units=units, now=current)
def _expire_all(con, current):
changed = []
held = []
review = []
rows = con.execute("SELECT id FROM ledger.bounties WHERE store_version=1 AND legacy_review=0 "
"AND (closed_reason IS NULL OR refund_pending>0) ORDER BY id").fetchall()
for row in rows:
before = _bounty(con, row["id"])
if not _finance_valid(con, before):
review.append(int(row["id"]))
continue
expired_before = _count(con, row["id"], ("expired",))
after = _advance(con, row["id"], current)
if (before["escrow_remaining"] != after["escrow_remaining"]
or before["closed_reason"] != after["closed_reason"]
or before["refund_pending"] != after["refund_pending"]
or expired_before != _count(con, row["id"], ("expired",))):
changed.append(int(row["id"]))
if after["refund_pending"]:
held.append(int(row["id"]))
return {"ok": True, "changed": changed, "held": held, "integrity_review": review,
"legacy_review": [int(row[0]) for row in con.execute(
"SELECT id FROM ledger.bounties WHERE legacy_review=1 ORDER BY id")]}
def expire(bot_db, gw_db, now=None):
current = _now(now)
with _transaction(bot_db, gw_db) as con:
return _expire_all(con, current)
def get(bot_db, gw_db, uid, bid, now=None):
"""Detail by ID, including legacy/integrity holds and older paginated rows."""
uid, bid, current = _integer(uid, "uid"), _integer(bid, "bid"), _now(now)
with _transaction(bot_db, gw_db) as con:
user = _user(con, uid, allow_blocked=True)
bounty = _bounty(con, bid, writable=False)
if bounty["store_version"] == 1 and not bounty["legacy_review"] and _finance_valid(con, bounty):
_advance(con, bid, current)
return _result(con, bid, user, now=current)
def snapshot(bot_db, gw_db, uid, page=0, per_page=8, now=None):
uid, current = _integer(uid, "uid"), _now(now)
page = _integer(page, "page", 0, MAX_INT)
per_page = _integer(per_page, "per_page", 1, 50)
with _transaction(bot_db, gw_db) as con:
user = _user(con, uid, allow_blocked=True)
expiry = _expire_all(con, current)
total = int(con.execute("SELECT COUNT(*) FROM ledger.bounties").fetchone()[0])
pages = (total + per_page - 1) // per_page
page = min(page, max(0, pages - 1))
rows = con.execute("SELECT * FROM ledger.bounties ORDER BY id DESC LIMIT ? OFFSET ?",
(per_page, page * per_page)).fetchall()
items = [_view(con, row, user) for row in rows]
result = {"ok": True, "items": items, "bounties": items, "total": total, "pages": pages,
"page": page, "per_page": per_page, "expiry": expiry}
result.update(_funding(con, user, now=current))
return result