-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
645 lines (556 loc) · 21.3 KB
/
Copy pathdatabase.py
File metadata and controls
645 lines (556 loc) · 21.3 KB
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
"""
NerdMiners_Public_Pool_Stats Bot - SQLite Database Module.
Handles all persistent data storage including bot state, worker registry,
hashrate history, session tracking, and hall of fame.
"""
import json
import sqlite3
from datetime import datetime, timedelta, timezone
from pathlib import Path
SCRIPT_DIR = Path(__file__).parent
DB_FILE = SCRIPT_DIR / "DB.db"
def _get_connection() -> sqlite3.Connection:
"""Get a database connection with row factory enabled."""
conn = sqlite3.connect(str(DB_FILE))
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA foreign_keys=ON")
return conn
def init_db() -> None:
"""Create all tables if they don't exist."""
conn = _get_connection()
try:
conn.executescript("""
CREATE TABLE IF NOT EXISTS bot_state (
key TEXT PRIMARY KEY,
value TEXT
);
CREATE TABLE IF NOT EXISTS workers (
internal_id TEXT PRIMARY KEY,
api_name TEXT NOT NULL,
first_seen TEXT NOT NULL,
last_session_id TEXT,
last_hashrate REAL DEFAULT 0,
last_start_time TEXT,
last_best_diff REAL DEFAULT 0,
last_seen TEXT,
active INTEGER NOT NULL DEFAULT 1
);
CREATE TABLE IF NOT EXISTS hashrate_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
worker_id TEXT NOT NULL,
hashrate REAL NOT NULL,
timestamp TEXT NOT NULL,
FOREIGN KEY (worker_id) REFERENCES workers(internal_id)
);
CREATE INDEX IF NOT EXISTS idx_hashrate_worker_time
ON hashrate_history(worker_id, timestamp);
CREATE TABLE IF NOT EXISTS sessions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
worker_id TEXT NOT NULL,
session_id TEXT,
start_time TEXT NOT NULL,
end_time TEXT,
best_difficulty REAL DEFAULT 0,
FOREIGN KEY (worker_id) REFERENCES workers(internal_id)
);
CREATE INDEX IF NOT EXISTS idx_sessions_worker
ON sessions(worker_id);
CREATE TABLE IF NOT EXISTS hall_of_fame (
id INTEGER PRIMARY KEY AUTOINCREMENT,
worker_id TEXT NOT NULL,
difficulty REAL NOT NULL,
achieved_at TEXT NOT NULL,
session_id TEXT,
FOREIGN KEY (worker_id) REFERENCES workers(internal_id)
);
CREATE TABLE IF NOT EXISTS pool_blocks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
block_data TEXT NOT NULL,
detected_at TEXT NOT NULL
);
""")
# Migration: databases created before the "inactive workers" feature
# lack the active column.
columns = {row["name"] for row in conn.execute("PRAGMA table_info(workers)")}
if "active" not in columns:
conn.execute(
"ALTER TABLE workers ADD COLUMN active INTEGER NOT NULL DEFAULT 1"
)
conn.commit()
finally:
conn.close()
# ---------------------------------------------------------------------------
# Bot State
# ---------------------------------------------------------------------------
def get_state(key: str, default: str | None = None) -> str | None:
"""Get a value from bot_state."""
conn = _get_connection()
try:
row = conn.execute(
"SELECT value FROM bot_state WHERE key = ?", (key,)
).fetchone()
return row["value"] if row else default
finally:
conn.close()
def set_state(key: str, value: str) -> None:
"""Set a value in bot_state."""
conn = _get_connection()
try:
conn.execute(
"INSERT OR REPLACE INTO bot_state (key, value) VALUES (?, ?)",
(key, value),
)
conn.commit()
finally:
conn.close()
# ---------------------------------------------------------------------------
# Workers
# ---------------------------------------------------------------------------
def get_worker(internal_id: str) -> dict | None:
"""Get a worker by internal ID."""
conn = _get_connection()
try:
row = conn.execute(
"SELECT * FROM workers WHERE internal_id = ?", (internal_id,)
).fetchone()
return dict(row) if row else None
finally:
conn.close()
def get_all_workers() -> list[dict]:
"""Get all registered workers."""
conn = _get_connection()
try:
rows = conn.execute("SELECT * FROM workers").fetchall()
return [dict(r) for r in rows]
finally:
conn.close()
def get_active_workers() -> list[dict]:
"""Get all registered workers that are still actively tracked."""
conn = _get_connection()
try:
rows = conn.execute("SELECT * FROM workers WHERE active = 1").fetchall()
return [dict(r) for r in rows]
finally:
conn.close()
def set_worker_active(internal_id: str, active: bool) -> None:
"""Mark a worker as actively tracked or paused (history is preserved)."""
conn = _get_connection()
try:
conn.execute(
"UPDATE workers SET active = ? WHERE internal_id = ?",
(1 if active else 0, internal_id),
)
conn.commit()
finally:
conn.close()
def upsert_worker(
internal_id: str,
api_name: str,
session_id: str | None = None,
hashrate: float = 0,
start_time: str | None = None,
best_diff: float = 0,
last_seen: str | None = None,
) -> None:
"""Insert or update a worker record."""
now = datetime.now(timezone.utc).isoformat()
conn = _get_connection()
try:
existing = conn.execute(
"SELECT internal_id FROM workers WHERE internal_id = ?",
(internal_id,),
).fetchone()
if existing:
conn.execute(
"""UPDATE workers SET
last_session_id = ?,
last_hashrate = ?,
last_start_time = ?,
last_best_diff = ?,
last_seen = ?
WHERE internal_id = ?""",
(session_id, hashrate, start_time, best_diff, last_seen, internal_id),
)
else:
conn.execute(
"""INSERT INTO workers
(internal_id, api_name, first_seen, last_session_id,
last_hashrate, last_start_time, last_best_diff, last_seen)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
(internal_id, api_name, now, session_id, hashrate,
start_time, best_diff, last_seen),
)
conn.commit()
finally:
conn.close()
def resolve_worker_id(
api_name: str,
session_id: str,
hashrate: float,
all_api_workers: list[dict],
claimed_ids: set[str] | None = None,
) -> str:
"""
Map an API worker to an internal ID.
For unique API names (only one worker with that name in the current API
response, and never tracked under suffixed IDs), the internal_id equals
the api_name.
For duplicate API names (multiple workers with the same name, e.g. all
named "worker"), the bot assigns incremental IDs: worker_1, worker_2, etc.
Re-identification is attempted by matching session_id first, then by
similar hashrate (±50%). Once suffixed IDs exist for an api_name, workers
keep resolving against them even if only one is currently online.
``claimed_ids`` tracks IDs already assigned in the current batch to
prevent two API workers from resolving to the same internal ID.
"""
if claimed_ids is None:
claimed_ids = set()
# Count how many workers in the current API response share this api_name.
# Sanitise raw names the same way identify_workers() does so that
# None / non-string values map to the same api_name ("Unknown").
same_name_count = sum(
1 for w in all_api_workers
if (w.get("name") if isinstance(w.get("name"), str) else "Unknown") == api_name
)
conn = _get_connection()
try:
known = conn.execute(
"SELECT * FROM workers WHERE api_name = ? ORDER BY internal_id",
(api_name,),
).fetchall()
# Workers registered under suffixed IDs (assigned while several miners
# shared this api_name). If any exist, keep resolving against them even
# when the name is unique in the current batch — otherwise a miner
# would get a brand-new bare ID whenever its same-named siblings are
# temporarily offline, splitting its identity and history.
has_suffixed = any(r["internal_id"] != api_name for r in known)
# If this api_name is unique in the current batch and was never
# tracked under suffixed IDs, use it directly
if same_name_count <= 1 and not has_suffixed:
return api_name
# Try match by session_id (skip already-claimed IDs)
for row in known:
if row["last_session_id"] == session_id and row["internal_id"] not in claimed_ids:
return row["internal_id"]
# Try match by similar hashrate (±50%), skip already-claimed IDs
if hashrate > 0:
for row in known:
if row["internal_id"] in claimed_ids:
continue
saved_hr = row["last_hashrate"] or 0
if saved_hr > 0:
ratio = hashrate / saved_hr
if 0.5 <= ratio <= 1.5:
return row["internal_id"]
# No match found: assign new incremental ID (skip claimed ones)
max_suffix = 0
for row in known:
iid = row["internal_id"]
if "_" in iid:
try:
suffix = int(iid.rsplit("_", 1)[1])
max_suffix = max(max_suffix, suffix)
except ValueError:
pass
# Also check claimed_ids for the highest suffix
for cid in claimed_ids:
if cid.startswith(f"{api_name}_"):
try:
suffix = int(cid.rsplit("_", 1)[1])
max_suffix = max(max_suffix, suffix)
except ValueError:
pass
new_id = f"{api_name}_{max_suffix + 1}"
return new_id
finally:
conn.close()
# ---------------------------------------------------------------------------
# Hashrate History
# ---------------------------------------------------------------------------
def add_hashrate_sample(worker_id: str, hashrate: float) -> None:
"""Record a hashrate sample."""
now = datetime.now(timezone.utc).isoformat()
conn = _get_connection()
try:
conn.execute(
"INSERT INTO hashrate_history (worker_id, hashrate, timestamp) VALUES (?, ?, ?)",
(worker_id, hashrate, now),
)
conn.commit()
finally:
conn.close()
def get_avg_hashrate(worker_id: str, hours: int = 24) -> float | None:
"""Calculate average hashrate over the last N hours. Returns None if no data."""
# The cutoff must be built in Python: samples are stored as
# datetime.isoformat() ("...T...+00:00") and SQLite's datetime('now')
# uses a space separator, which breaks lexicographic comparison.
cutoff = (datetime.now(timezone.utc) - timedelta(hours=hours)).isoformat()
conn = _get_connection()
try:
row = conn.execute(
"""SELECT AVG(hashrate) as avg_hr, COUNT(*) as cnt
FROM hashrate_history
WHERE worker_id = ?
AND timestamp >= ?""",
(worker_id, cutoff),
).fetchone()
if row and row["cnt"] > 0:
return row["avg_hr"]
return None
finally:
conn.close()
# ---------------------------------------------------------------------------
# Sessions
# ---------------------------------------------------------------------------
def get_current_session(worker_id: str) -> dict | None:
"""Get the current (open) session for a worker."""
conn = _get_connection()
try:
row = conn.execute(
"""SELECT * FROM sessions
WHERE worker_id = ? AND end_time IS NULL
ORDER BY id DESC LIMIT 1""",
(worker_id,),
).fetchone()
return dict(row) if row else None
finally:
conn.close()
def close_session(worker_id: str, best_difficulty: float = 0) -> dict | None:
"""
Close the current open session for a worker.
Returns the closed session data or None if no open session.
"""
now = datetime.now(timezone.utc).isoformat()
conn = _get_connection()
try:
current = conn.execute(
"""SELECT * FROM sessions
WHERE worker_id = ? AND end_time IS NULL
ORDER BY id DESC LIMIT 1""",
(worker_id,),
).fetchone()
if current:
conn.execute(
"""UPDATE sessions SET end_time = ?, best_difficulty = ?
WHERE id = ?""",
(now, best_difficulty, current["id"]),
)
conn.commit()
return dict(current)
return None
finally:
conn.close()
def open_session(
worker_id: str, session_id: str, start_time: str
) -> None:
"""Open a new session for a worker."""
conn = _get_connection()
try:
conn.execute(
"""INSERT INTO sessions (worker_id, session_id, start_time)
VALUES (?, ?, ?)""",
(worker_id, session_id, start_time),
)
conn.commit()
finally:
conn.close()
def _parse_ts(value: str | None) -> datetime | None:
"""Parse a stored/API timestamp into an aware UTC datetime, or None."""
if not value:
return None
try:
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
except (ValueError, TypeError):
return None
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt
def get_uptime_percent(worker_id: str, days: int = 7) -> float | None:
"""Percentage of time the worker had an active session in the last N days.
For workers younger than the window, the window starts at first_seen so
the percentage stays fair. Returns None when there is not enough data.
"""
now = datetime.now(timezone.utc)
conn = _get_connection()
try:
worker = conn.execute(
"SELECT first_seen FROM workers WHERE internal_id = ?",
(worker_id,),
).fetchone()
first_seen = _parse_ts(worker["first_seen"]) if worker else None
if first_seen is None:
return None
window_start = max(now - timedelta(days=days), first_seen)
window_seconds = (now - window_start).total_seconds()
if window_seconds < 60:
return None # too little history to be meaningful
rows = conn.execute(
"SELECT start_time, end_time FROM sessions WHERE worker_id = ?",
(worker_id,),
).fetchall()
if not rows:
return None
up = 0.0
for r in rows:
start = _parse_ts(r["start_time"])
if start is None:
continue
end = _parse_ts(r["end_time"]) or now
start = max(start, window_start)
end = min(end, now)
if end > start:
up += (end - start).total_seconds()
return min(up / window_seconds * 100.0, 100.0)
finally:
conn.close()
def get_all_time_best(worker_id: str) -> float:
"""Get the best difficulty ever achieved by a worker across all sessions."""
conn = _get_connection()
try:
# Check closed sessions
row = conn.execute(
"SELECT MAX(best_difficulty) as best FROM sessions WHERE worker_id = ?",
(worker_id,),
).fetchone()
session_best = row["best"] if row and row["best"] else 0
# Also check current worker record (current session best)
worker = conn.execute(
"SELECT last_best_diff FROM workers WHERE internal_id = ?",
(worker_id,),
).fetchone()
current_best = worker["last_best_diff"] if worker and worker["last_best_diff"] else 0
# Also check hall of fame
hof_row = conn.execute(
"SELECT MAX(difficulty) as best FROM hall_of_fame WHERE worker_id = ?",
(worker_id,),
).fetchone()
hof_best = hof_row["best"] if hof_row and hof_row["best"] else 0
return max(session_best, current_best, hof_best)
finally:
conn.close()
# ---------------------------------------------------------------------------
# Hall of Fame
# ---------------------------------------------------------------------------
def update_hall_of_fame(
worker_id: str, difficulty: float, session_id: str | None = None
) -> bool:
"""
Try to add an entry to the Hall of Fame (top 10).
Returns True if the entry was added.
"""
now = datetime.now(timezone.utc).isoformat()
conn = _get_connection()
try:
# Check if this exact difficulty is already recorded for this worker
existing = conn.execute(
"""SELECT id FROM hall_of_fame
WHERE worker_id = ? AND difficulty = ?""",
(worker_id, difficulty),
).fetchone()
if existing:
return False
entries = conn.execute(
"SELECT * FROM hall_of_fame ORDER BY difficulty DESC"
).fetchall()
if len(entries) < 10:
conn.execute(
"""INSERT INTO hall_of_fame
(worker_id, difficulty, achieved_at, session_id)
VALUES (?, ?, ?, ?)""",
(worker_id, difficulty, now, session_id),
)
conn.commit()
return True
# Check if this beats the lowest entry
lowest = entries[-1]
if difficulty > lowest["difficulty"]:
conn.execute("DELETE FROM hall_of_fame WHERE id = ?", (lowest["id"],))
conn.execute(
"""INSERT INTO hall_of_fame
(worker_id, difficulty, achieved_at, session_id)
VALUES (?, ?, ?, ?)""",
(worker_id, difficulty, now, session_id),
)
conn.commit()
return True
return False
finally:
conn.close()
def get_hall_of_fame(limit: int = 10) -> list[dict]:
"""Get the Hall of Fame entries sorted by difficulty descending."""
conn = _get_connection()
try:
rows = conn.execute(
"SELECT * FROM hall_of_fame ORDER BY difficulty DESC LIMIT ?",
(limit,),
).fetchall()
return [dict(r) for r in rows]
finally:
conn.close()
# ---------------------------------------------------------------------------
# Pool Blocks
# ---------------------------------------------------------------------------
def get_known_pool_block_heights() -> set[int]:
"""Get all known pool block heights."""
conn = _get_connection()
try:
rows = conn.execute("SELECT block_data FROM pool_blocks").fetchall()
heights = set()
for r in rows:
try:
data = json.loads(r["block_data"])
if isinstance(data, dict) and "height" in data:
heights.add(data["height"])
except (json.JSONDecodeError, TypeError):
pass
return heights
finally:
conn.close()
def save_pool_block(block_data: dict) -> None:
"""Save a newly found pool block."""
now = datetime.now(timezone.utc).isoformat()
conn = _get_connection()
try:
conn.execute(
"INSERT INTO pool_blocks (block_data, detected_at) VALUES (?, ?)",
(json.dumps(block_data), now),
)
conn.commit()
finally:
conn.close()
# ---------------------------------------------------------------------------
# Maintenance
# ---------------------------------------------------------------------------
def delete_worker(internal_id: str) -> None:
"""Remove all traces of a worker from the database (workers, history, sessions, hall of fame, state)."""
conn = _get_connection()
try:
conn.execute("DELETE FROM hashrate_history WHERE worker_id = ?", (internal_id,))
conn.execute("DELETE FROM sessions WHERE worker_id = ?", (internal_id,))
conn.execute("DELETE FROM hall_of_fame WHERE worker_id = ?", (internal_id,))
conn.execute("DELETE FROM workers WHERE internal_id = ?", (internal_id,))
for key in (
f"low_hashrate_strikes_{internal_id}",
f"low_hashrate_alerted_at_{internal_id}",
f"disappeared_count_{internal_id}",
f"offline_alerted_{internal_id}",
):
conn.execute("DELETE FROM bot_state WHERE key = ?", (key,))
conn.commit()
finally:
conn.close()
def purge_old_data(days: int) -> int:
"""Delete hashrate history older than N days. Returns rows deleted."""
# Cutoff built in Python for the same reason as get_avg_hashrate().
cutoff = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
conn = _get_connection()
try:
cursor = conn.execute(
"DELETE FROM hashrate_history WHERE timestamp < ?",
(cutoff,),
)
conn.commit()
return cursor.rowcount
finally:
conn.close()