Skip to content
6 changes: 6 additions & 0 deletions dashboard/mining_dashboard/client/xmrig_proxy_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ def get_workers(self):
response.raise_for_status()
return response.json()

def get_miners(self):
url = f"{self.base_url}/1/miners"
response = bounded_request("GET", url, timeout=5, session=self.session)
response.raise_for_status()
return response.json()

def get_config(self):
"""
Get the current configuration of the proxy.
Expand Down
3 changes: 3 additions & 0 deletions dashboard/mining_dashboard/service/control_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

from mining_dashboard.config import config, documents
from mining_dashboard.service import audit_service, config_operations, request_spool
from mining_dashboard.service.workers import worker_identity

logger = logging.getLogger("ControlService")

Expand Down Expand Up @@ -348,6 +349,7 @@ def submit_worker_apply(worker, changes, actor="", intent_id=None):
"worker": worker,
"changes": changes,
}
worker_identity.stamp(request)
return request_spool.write(request)


Expand All @@ -362,6 +364,7 @@ def submit_worker_upgrade(worker, version, actor="", intent_id=None, appliance=F
}
if appliance:
request["appliance"] = True
worker_identity.stamp(request)
return request_spool.write(request)


Expand Down
7 changes: 3 additions & 4 deletions dashboard/mining_dashboard/service/data_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
)
from mining_dashboard.service.metrics import build_metrics, share_reject_pct
from mining_dashboard.service.notify.telegram_commands import format_daily_summary
from mining_dashboard.service.workers import worker_refresh
from mining_dashboard.service.workers import worker_identity, worker_identity_poll, worker_refresh

logger = logging.getLogger("DataService")

Expand Down Expand Up @@ -175,8 +175,8 @@ async def run(self):
# 3. Augment with Direct Worker Stats (Uptime, Hashrate) via Local API
worker_results = await self._prober.probe(worker_client, proxy_workers)

# Reconcile pending rig edits and flag out-of-band edits using this poll.
await self._reconcile_worker_config(proxy_workers, worker_results)
await worker_identity_poll.observe_poll(self, proxy_workers, worker_results)

# 3a-2. Out-of-band audit (#530): a config.json change not made through the
# control channel, plus mirroring the #33 log into the durable audit_events
Expand All @@ -191,9 +191,8 @@ async def run(self):
final_workers = _merge_direct_stats(
proxy_workers, worker_results, active_pool_port
)
# 3b. Track per-worker connection lifecycle: fill true uptime for online workers
# (#169) and drop stale offline rows past the fall-off window (#182).
final_workers = self._lifecycle.update(final_workers, time.time())
worker_identity.mark_duplicates(self, final_workers)

total_hr, total_h10 = _aggregate_hashrate(final_workers)

Expand Down
2 changes: 2 additions & 0 deletions dashboard/mining_dashboard/service/data_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from mining_dashboard.service.notify.alert_service import AlertService
from mining_dashboard.service.notify.healthchecks import HealthchecksClient
from mining_dashboard.service.worker_probe import WorkerProber
from mining_dashboard.service.workers.worker_identity import RigIdentityTracker
from mining_dashboard.service.xvb.price_feed import CoinGeckoClient, PriceFeed

logger = logging.getLogger("DataService")
Expand Down Expand Up @@ -84,6 +85,7 @@ def __init__(self, state_manager, proxy_client, xvb_client):
self._last_proxy_workers = []
self._last_proxy_workers_at = None
self._prober = WorkerProber()
self._identity = RigIdentityTracker()
# Share-health delta baseline (#116): the previous poll's cumulative proxy /summary
# totals; None until the first poll seeds it (and again after a counter reset).
self._last_share_totals = None
Expand Down
82 changes: 82 additions & 0 deletions dashboard/mining_dashboard/service/workers/worker_identity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import time
from collections import OrderedDict

from mining_dashboard.config import config

IDENTITY_WINDOW_POLLS = 3
IDENTITY_WINDOW_S = IDENTITY_WINDOW_POLLS * config.UPDATE_INTERVAL
_MAX_TRACKED_RIGS = 1024
_MAX_SOURCES_PER_RIG = 8
_MAX_REMEMBERED = 4096
MOVED_EVENT_INTERVAL_S = 3600

_faulted_names = frozenset()


def stamp(request):
if request.get("worker") in _faulted_names:
request["duplicate_identity"] = True
return request


class RigIdentityTracker:
def __init__(self, window_s=IDENTITY_WINDOW_S):
self._window_s = window_s
self._rigs = {}
self._fingerprints = OrderedDict()
self._moved_at = OrderedDict()

def _live(self, rec, now):
return {s: t for s, t in rec["sources"].items() if now - t <= self._window_s}

def sweep(self, now):
for rig_id in list(self._rigs):
rec = self._rigs[rig_id]
rec["sources"] = self._live(rec, now)
if not rec["sources"]:
del self._rigs[rig_id]

def _moved(self, rig_id, source, fingerprint, credential, now):
key = (rig_id, credential, source)
last = self._fingerprints.pop(key, None)
moved = bool(last and fingerprint and last != fingerprint)
moved = moved and now - self._moved_at.get(rig_id, float("-inf")) >= MOVED_EVENT_INTERVAL_S
if moved:
self._moved_at.pop(rig_id, None)
self._moved_at[rig_id] = now
while len(self._moved_at) > _MAX_REMEMBERED:
self._moved_at.popitem(last=False)
if fingerprint or last:
self._fingerprints[key] = fingerprint or last
while len(self._fingerprints) > _MAX_REMEMBERED:
self._fingerprints.popitem(last=False)
return moved

def observe(self, rig_id, source, fingerprint, credential, now):
moved = self._moved(rig_id, source, fingerprint, credential, now)
rec = self._rigs.get(rig_id)
if rec is None:
if len(self._rigs) >= _MAX_TRACKED_RIGS:
return moved
rec = self._rigs[rig_id] = {"credential": credential, "sources": {}}
if rec["credential"] != credential:
rec["credential"], rec["sources"] = credential, {}
rec["sources"] = self._live(rec, now)
if source not in rec["sources"] and len(rec["sources"]) >= _MAX_SOURCES_PER_RIG:
return moved
rec["sources"][source] = now
return moved

def faulted(self, rig_id, now):
rec = self._rigs.get(rig_id)
return bool(rec) and len(self._live(rec, now)) >= 2


def mark_duplicates(svc, workers, now=None):
global _faulted_names
now = time.time() if now is None else now
for w in workers:
rig_id = (w.get("rigforge") or {}).get("rig_id")
w["duplicate_identity"] = bool(rig_id) and svc._identity.faulted(rig_id, now)
_faulted_names = frozenset(w.get("name") for w in workers if w["duplicate_identity"])
return workers
110 changes: 110 additions & 0 deletions dashboard/mining_dashboard/service/workers/worker_identity_poll.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import asyncio
import hashlib
import logging
import time

from mining_dashboard.client import xmrig_client
from mining_dashboard.service import audit_service

logger = logging.getLogger(__name__)

_PX_MINER_IP = 1
_PX_MINER_USER = 6
_PX_MINER_RIG_ID = 8
_PX_MINER_MIN_FIELDS = 9
_PX_MINER_MAX_KEY = 128


def _parse_proxy_miners(miners_data):
if not isinstance(miners_data, dict):
return []
rows = miners_data.get("miners")
if not isinstance(rows, list):
return []
sources = []
for row in rows:
if not isinstance(row, list) or len(row) < _PX_MINER_MIN_FIELDS:
continue
ip = row[_PX_MINER_IP]
if not isinstance(ip, str) or not ip:
continue
key = next(
(
value
for value in (row[_PX_MINER_RIG_ID], row[_PX_MINER_USER])
if isinstance(value, str) and 0 < len(value) <= _PX_MINER_MAX_KEY
),
None,
)
if key is not None:
sources.append((key, ip))
return sources


def _source_key(ip):
if not isinstance(ip, str):
return ip
if ip.count(":") == 1:
head, _, tail = ip.rpartition(":")
if tail.isdigit():
return head
return ip


async def _fetch_miners(svc) -> dict | None:
try:
return await asyncio.to_thread(svc.proxy_client.get_miners)
except Exception as e:
logger.error(f"Proxy Miners Fetch Error: {e}")
return None


def _credential_key(name, rig_id):
entry = xmrig_client._worker_override(name.split("+")[0].strip(), None, rig_id) or {}
token = entry.get("read_token")
return hashlib.sha256(token.encode()).hexdigest()[:16] if token else None


def _fingerprint(rigforge):
hints = xmrig_client._feed_identity(rigforge.get("identity"))
return tuple(sorted(hints.items())) if hints else None


async def observe_poll(svc, workers, results, miners=None, now=None):
now = time.time() if now is None else now
tracker = svc._identity
tracker.sweep(now)
feed_ids = set()
feed_creds = {}
ids_by_name = {}
for w, extra in zip(workers, results, strict=False):
rf = (extra or {}).get("rigforge")
rig_id = xmrig_client._feed_rig_id(extra) if extra and extra.get("api_ok") else None
if not rig_id or w.get("status") != "online" or not isinstance(rf, dict):
continue
feed_ids.add(rig_id)
name = w.get("name") or ""
credential = _credential_key(name, rig_id)
feed_creds.setdefault(rig_id, credential)
ids_by_name.setdefault(name, rig_id)
moved = tracker.observe(rig_id, _source_key(w.get("ip")), _fingerprint(rf), credential, now)
if moved:
await svc._record_audit_event(
"rig-identity",
name,
"moved-hardware",
"info",
f"rig id {rig_id} reports different hardware hints from {w.get('ip')}",
event_id=audit_service.build_event_id(
"rig-moved", rig_id, w.get("ip"), repr(_fingerprint(rf))
),
)
if not feed_ids:
return
payload = miners if miners is not None else await _fetch_miners(svc)
for key, ip in _parse_proxy_miners(payload):
rig_id = key if key in feed_ids else ids_by_name.get(key)
if not rig_id:
rig_id = ids_by_name.get(key.split("+")[0].strip())
if rig_id:
tracker.observe(rig_id, _source_key(ip), None, feed_creds.get(rig_id), now)
6 changes: 6 additions & 0 deletions dashboard/tests/client/test_xmrig_proxy_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ def test_get_workers(client):
assert client.get_workers() == {"workers": []}


def test_get_miners(client):
client.session.get.return_value = _resp({"miners": []})
assert client.get_miners() == {"miners": []}
assert client.session.get.call_args[0][0].endswith("/1/miners")


def test_get_config(client):
client.session.get.return_value = _resp({"pools": []})
assert client.get_config() == {"pools": []}
Expand Down
Loading
Loading