File size: 8,449 Bytes
3e28e27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""SQLite persistence (stdlib). One file, WAL mode, safe for a single-process API."""
from __future__ import annotations

import json
import os
import sqlite3
import threading
import time
import uuid
from contextlib import contextmanager
from typing import Any, Iterator, Optional


def _pick_data_dir() -> str:
    """Prefer the configured data dir; fall back to /tmp if it isn't writable (hosts without storage)."""
    for candidate in (os.environ.get("QRYPTO_DATA_DIR"), "/data", "/tmp", "."):
        if not candidate:
            continue
        try:
            os.makedirs(candidate, exist_ok=True)
            probe = os.path.join(candidate, ".write-probe")
            with open(probe, "w") as fh:
                fh.write("1")
            os.remove(probe)
            return candidate
        except OSError:
            continue
    return "."


DB_PATH = os.environ.get("QRYPTO_DB") or os.path.join(_pick_data_dir(), "qrypto.db")

SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
  id TEXT PRIMARY KEY, email TEXT UNIQUE NOT NULL, pw_hash TEXT NOT NULL,
  tier TEXT NOT NULL DEFAULT 'free', created_at REAL NOT NULL,
  accepted_risk_at REAL, is_admin INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS exchange_keys (
  user_id TEXT NOT NULL, exchange TEXT NOT NULL, label TEXT,
  enc_key TEXT NOT NULL, enc_secret TEXT NOT NULL, created_at REAL NOT NULL,
  PRIMARY KEY (user_id, exchange)
);
CREATE TABLE IF NOT EXISTS bots (
  id TEXT PRIMARY KEY, user_id TEXT NOT NULL, name TEXT NOT NULL, strategy TEXT NOT NULL,
  params TEXT NOT NULL, symbol TEXT NOT NULL, timeframe TEXT NOT NULL, mode TEXT NOT NULL,
  exchange TEXT, status TEXT NOT NULL DEFAULT 'stopped', state TEXT, created_at REAL NOT NULL,
  updated_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS bot_events (
  id INTEGER PRIMARY KEY AUTOINCREMENT, bot_id TEXT NOT NULL, at REAL NOT NULL, payload TEXT NOT NULL
);
CREATE INDEX IF NOT EXISTS ix_events_bot ON bot_events(bot_id, at);
CREATE TABLE IF NOT EXISTS api_tokens (
  token TEXT PRIMARY KEY, user_id TEXT NOT NULL, label TEXT, created_at REAL NOT NULL
);
"""

_lock = threading.RLock()


def _connect() -> sqlite3.Connection:
    os.makedirs(os.path.dirname(os.path.abspath(DB_PATH)), exist_ok=True)
    c = sqlite3.connect(DB_PATH, check_same_thread=False)
    c.row_factory = sqlite3.Row
    c.execute("PRAGMA journal_mode=WAL")
    return c


_conn: Optional[sqlite3.Connection] = None


def conn() -> sqlite3.Connection:
    global _conn
    if _conn is None:
        _conn = _connect()
        _conn.executescript(SCHEMA)
    return _conn


@contextmanager
def tx() -> Iterator[sqlite3.Connection]:
    with _lock:
        c = conn()
        try:
            yield c
            c.commit()
        except Exception:
            c.rollback()
            raise


def row_to_dict(r: sqlite3.Row | None) -> Optional[dict[str, Any]]:
    return dict(r) if r is not None else None


def new_id() -> str:
    return uuid.uuid4().hex


def now() -> float:
    return time.time()


# --- users ---------------------------------------------------------------
def create_user(email: str, pw_hash: str, accepted_risk: bool, is_admin: bool = False) -> dict:
    uid = new_id()
    with tx() as c:
        c.execute("INSERT INTO users(id,email,pw_hash,tier,created_at,accepted_risk_at,is_admin) VALUES(?,?,?,?,?,?,?)",
                  (uid, email.lower(), pw_hash, "free", now(), now() if accepted_risk else None, int(is_admin)))
    return get_user(uid)


def get_user(uid: str) -> Optional[dict]:
    return row_to_dict(conn().execute("SELECT * FROM users WHERE id=?", (uid,)).fetchone())


def get_user_by_email(email: str) -> Optional[dict]:
    return row_to_dict(conn().execute("SELECT * FROM users WHERE email=?", (email.lower(),)).fetchone())


def set_tier(uid: str, tier: str) -> None:
    with tx() as c:
        c.execute("UPDATE users SET tier=? WHERE id=?", (tier, uid))


def count_users() -> int:
    return conn().execute("SELECT COUNT(*) FROM users").fetchone()[0]


# --- exchange keys ---------------------------------------------------------
def put_exchange_key(uid: str, exchange: str, enc_key: str, enc_secret: str, label: str = "") -> None:
    with tx() as c:
        c.execute("INSERT OR REPLACE INTO exchange_keys(user_id,exchange,label,enc_key,enc_secret,created_at) VALUES(?,?,?,?,?,?)",
                  (uid, exchange, label, enc_key, enc_secret, now()))


def get_exchange_key(uid: str, exchange: str) -> Optional[dict]:
    return row_to_dict(conn().execute("SELECT * FROM exchange_keys WHERE user_id=? AND exchange=?", (uid, exchange)).fetchone())


def list_exchange_keys(uid: str) -> list[dict]:
    rows = conn().execute("SELECT exchange,label,created_at FROM exchange_keys WHERE user_id=?", (uid,)).fetchall()
    return [dict(r) for r in rows]


def delete_exchange_key(uid: str, exchange: str) -> None:
    with tx() as c:
        c.execute("DELETE FROM exchange_keys WHERE user_id=? AND exchange=?", (uid, exchange))


# --- bots ----------------------------------------------------------------
def create_bot(uid: str, name: str, strategy: str, params: dict, symbol: str, timeframe: str, mode: str,
               exchange: Optional[str], state: Optional[dict] = None) -> dict:
    bid = new_id()
    with tx() as c:
        c.execute("""INSERT INTO bots(id,user_id,name,strategy,params,symbol,timeframe,mode,exchange,status,state,created_at,updated_at)
                     VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",
                  (bid, uid, name, strategy, json.dumps(params), symbol, timeframe, mode, exchange, "stopped",
                   json.dumps(state or {}), now(), now()))
    return get_bot(bid)


def get_bot(bid: str) -> Optional[dict]:
    b = row_to_dict(conn().execute("SELECT * FROM bots WHERE id=?", (bid,)).fetchone())
    if b:
        b["params"] = json.loads(b["params"] or "{}")
        b["state"] = json.loads(b["state"] or "{}")
    return b


def list_bots(uid: str) -> list[dict]:
    rows = conn().execute("SELECT id FROM bots WHERE user_id=? ORDER BY created_at", (uid,)).fetchall()
    return [get_bot(r["id"]) for r in rows]


def list_running_bots() -> list[dict]:
    rows = conn().execute("SELECT id FROM bots WHERE status='running'").fetchall()
    return [get_bot(r["id"]) for r in rows]


# Columns update_bot may write. The UPDATE statement is built by joining these names, so an
# allowlist is what keeps that from ever becoming an injection point, whatever a caller passes.
_BOT_COLUMNS = {"name", "strategy", "params", "symbol", "timeframe", "mode", "exchange", "status", "state"}


def update_bot(bid: str, **fields: Any) -> None:
    unknown = set(fields) - _BOT_COLUMNS
    if unknown:
        raise ValueError(f"not updatable bot columns: {sorted(unknown)}")
    if "params" in fields:
        fields["params"] = json.dumps(fields["params"])
    if "state" in fields:
        fields["state"] = json.dumps(fields["state"])
    fields["updated_at"] = now()
    cols = ", ".join(f"{k}=?" for k in fields)
    with tx() as c:
        c.execute(f"UPDATE bots SET {cols} WHERE id=?", (*fields.values(), bid))


def delete_bot(bid: str) -> None:
    with tx() as c:
        c.execute("DELETE FROM bots WHERE id=?", (bid,))
        c.execute("DELETE FROM bot_events WHERE bot_id=?", (bid,))


def add_event(bid: str, payload: dict) -> None:
    with tx() as c:
        c.execute("INSERT INTO bot_events(bot_id,at,payload) VALUES(?,?,?)", (bid, now(), json.dumps(payload)))
        c.execute("DELETE FROM bot_events WHERE bot_id=? AND id NOT IN (SELECT id FROM bot_events WHERE bot_id=? ORDER BY id DESC LIMIT 500)", (bid, bid))


def list_events(bid: str, limit: int = 100) -> list[dict]:
    rows = conn().execute("SELECT at,payload FROM bot_events WHERE bot_id=? ORDER BY id DESC LIMIT ?", (bid, limit)).fetchall()
    return [{"at": r["at"], **json.loads(r["payload"])} for r in rows]


# --- api tokens (enterprise) -------------------------------------------------
def create_api_token(uid: str, label: str) -> str:
    token = "tb_" + uuid.uuid4().hex + uuid.uuid4().hex[:16]
    with tx() as c:
        c.execute("INSERT INTO api_tokens(token,user_id,label,created_at) VALUES(?,?,?,?)", (token, uid, label, now()))
    return token


def user_for_api_token(token: str) -> Optional[dict]:
    r = conn().execute("SELECT user_id FROM api_tokens WHERE token=?", (token,)).fetchone()
    return get_user(r["user_id"]) if r else None