diff --git a/dashboard/mining_dashboard/client/xmrig_proxy_client.py b/dashboard/mining_dashboard/client/xmrig_proxy_client.py index 7cb323b83..189d7ddb8 100644 --- a/dashboard/mining_dashboard/client/xmrig_proxy_client.py +++ b/dashboard/mining_dashboard/client/xmrig_proxy_client.py @@ -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. diff --git a/dashboard/mining_dashboard/service/control_service.py b/dashboard/mining_dashboard/service/control_service.py index 3541897b6..410cd1a05 100644 --- a/dashboard/mining_dashboard/service/control_service.py +++ b/dashboard/mining_dashboard/service/control_service.py @@ -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") @@ -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) @@ -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) diff --git a/dashboard/mining_dashboard/service/data_service.py b/dashboard/mining_dashboard/service/data_service.py index 74c7264e4..9e9451f4b 100644 --- a/dashboard/mining_dashboard/service/data_service.py +++ b/dashboard/mining_dashboard/service/data_service.py @@ -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") @@ -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 @@ -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) diff --git a/dashboard/mining_dashboard/service/data_setup.py b/dashboard/mining_dashboard/service/data_setup.py index d014456cd..93ca20ea2 100644 --- a/dashboard/mining_dashboard/service/data_setup.py +++ b/dashboard/mining_dashboard/service/data_setup.py @@ -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") @@ -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 diff --git a/dashboard/mining_dashboard/service/workers/worker_identity.py b/dashboard/mining_dashboard/service/workers/worker_identity.py new file mode 100644 index 000000000..1a3647009 --- /dev/null +++ b/dashboard/mining_dashboard/service/workers/worker_identity.py @@ -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 diff --git a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py new file mode 100644 index 000000000..d828206fe --- /dev/null +++ b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py @@ -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) diff --git a/dashboard/tests/client/test_xmrig_proxy_client.py b/dashboard/tests/client/test_xmrig_proxy_client.py index a7393d070..e0d4fa477 100644 --- a/dashboard/tests/client/test_xmrig_proxy_client.py +++ b/dashboard/tests/client/test_xmrig_proxy_client.py @@ -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": []} diff --git a/dashboard/tests/service/workers/test_worker_identity.py b/dashboard/tests/service/workers/test_worker_identity.py new file mode 100644 index 000000000..4644f0b51 --- /dev/null +++ b/dashboard/tests/service/workers/test_worker_identity.py @@ -0,0 +1,327 @@ +import asyncio +import json +from unittest.mock import MagicMock + +import pytest + +from mining_dashboard.client import xmrig_client +from mining_dashboard.service import control_service +from mining_dashboard.service.data_helpers import _merge_direct_stats +from mining_dashboard.service.data_service import DataService +from mining_dashboard.service.storage_service import StateManager +from mining_dashboard.service.workers import worker_identity, worker_identity_poll +from mining_dashboard.service.workers.worker_identity import ( + IDENTITY_WINDOW_S, + RigIdentityTracker, +) + +RIG = "a" * 32 +NEW_RIG = "b" * 32 +HINTS_A = {"mac": "aa:aa", "board_uuid": None, "cpu_model": "A72"} +HINTS_B = {"mac": "bb:bb", "board_uuid": None, "cpu_model": "A72"} +MINERS_FORMAT = ["id", "ip", "tx", "rx", "state", "diff", "user", "password", "rig_id", "agent"] + + +def _row(ip, name="rig1"): + return {"name": name, "ip": ip, "status": "online", "uptime": 5} + + +def _reply(hints=None, rig_id=RIG): + return { + "api_ok": True, + "rigforge": {"rig_id": rig_id, "identity": hints, "version": "v1.19.0"}, + } + + +def _miner(ip, rig_id=RIG, user=""): + return [1, ip, 0, 0, 4, 1000000, user, "x", rig_id, "xmrig/6.26.0"] + + +def _miners(*connections): + return {"format": MINERS_FORMAT, "miners": [list(c) for c in connections]} + + +@pytest.fixture +def svc(monkeypatch): + sm = StateManager(db_path=":memory:") + monkeypatch.setattr(xmrig_client, "WORKER_ENDPOINTS", []) + monkeypatch.setattr(worker_identity, "_faulted_names", frozenset()) + yield DataService(sm, MagicMock(), MagicMock()) + sm.close() + + +def _poll(svc, rows, replies, now, miners=None): + asyncio.run(worker_identity_poll.observe_poll(svc, rows, replies, miners, now=now)) + merged = _merge_direct_stats([dict(r) for r in rows], replies, "3333") + return worker_identity.mark_duplicates(svc, merged, now=now) + + +class TestTracker: + def test_two_sources_within_the_window_raise_the_fault(self): + t = RigIdentityTracker() + t.observe(RIG, "10.0.0.1", None, None, 100) + assert not t.faulted(RIG, 100) + t.observe(RIG, "10.0.0.2", None, None, 101) + assert t.faulted(RIG, 101) + + def test_fault_decays_when_one_source_goes_quiet(self): + t = RigIdentityTracker() + t.observe(RIG, "10.0.0.1", None, None, 100) + t.observe(RIG, "10.0.0.2", None, None, 100) + later = 100 + IDENTITY_WINDOW_S + 1 + t.observe(RIG, "10.0.0.1", None, None, later) + assert not t.faulted(RIG, later) + + def test_a_credential_change_clears_the_fault(self): + t = RigIdentityTracker() + t.observe(RIG, "10.0.0.1", None, "old", 100) + t.observe(RIG, "10.0.0.2", None, "old", 100) + assert t.faulted(RIG, 100) + t.observe(RIG, "10.0.0.1", None, "new", 101) + assert not t.faulted(RIG, 101) + + def test_one_source_with_changing_hints_is_moved_not_a_fault(self): + t = RigIdentityTracker() + assert t.observe(RIG, "10.0.0.1", (("mac", "aa"),), None, 100) is False + assert t.observe(RIG, "10.0.0.1", (("mac", "bb"),), None, 101) is True + assert not t.faulted(RIG, 101) + + def test_a_fingerprint_change_after_the_window_is_moved(self): + t = RigIdentityTracker() + t.observe(RIG, "10.0.0.1", (("mac", "aa"),), None, 100) + t.sweep(100 + IDENTITY_WINDOW_S + 500) + assert t.observe(RIG, "10.0.0.1", (("mac", "bb"),), None, 100 + IDENTITY_WINDOW_S + 500) + + def test_remembered_fingerprints_are_bounded(self, monkeypatch): + monkeypatch.setattr(worker_identity, "_MAX_REMEMBERED", 4) + t = RigIdentityTracker() + for i in range(20): + t.observe(f"{i:032x}", "10.0.0.1", (("mac", "aa"),), None, 100 + i) + assert len(t._fingerprints) == 4 + + def test_the_moved_clock_map_is_bounded(self, monkeypatch): + monkeypatch.setattr(worker_identity, "_MAX_REMEMBERED", 4) + t = RigIdentityTracker() + for i in range(20): + rig = f"{i:032x}" + t.observe(rig, "10.0.0.1", (("mac", "aa"),), None, 100) + t.observe(rig, "10.0.0.1", (("mac", "bb"),), None, 101) + assert len(t._moved_at) == 4 + + +class TestPoll: + def test_two_simulated_sources_raise_and_decay(self, svc): + rows = [_row("10.0.0.1"), _row("10.0.0.2")] + replies = [_reply(), _reply()] + marked = _poll(svc, rows, replies, 1000) + assert all(w["duplicate_identity"] for w in marked) + assert worker_identity._faulted_names == {"rig1"} + quiet = 1000 + IDENTITY_WINDOW_S + 1 + marked = _poll(svc, rows[:1], replies[:1], quiet) + assert not marked[0]["duplicate_identity"] + assert worker_identity._faulted_names == frozenset() + + def test_an_offline_or_unanswered_row_is_not_a_source(self, svc): + rows = [_row("10.0.0.1"), dict(_row("10.0.0.2"), status="offline")] + marked = _poll(svc, rows, [_reply(), _reply()], 1000) + assert not any(w["duplicate_identity"] for w in marked) + marked = _poll(svc, [_row("10.0.0.3")], [{"api_ok": False}], 1001) + assert not marked[0]["duplicate_identity"] + + def test_a_merged_clone_row_raises_from_its_connections(self, svc): + miners = _miners(_miner("10.0.0.1"), _miner("10.0.0.2")) + marked = _poll(svc, [_row("10.0.0.2")], [_reply()], 1000, miners=miners) + assert marked[0]["duplicate_identity"] + assert worker_identity._faulted_names == {"rig1"} + + def test_two_connections_from_one_machine_are_not_a_fault(self, svc): + miners = _miners(_miner("10.0.0.1"), _miner("10.0.0.1")) + marked = _poll(svc, [_row("10.0.0.1")], [_reply()], 1000, miners=miners) + assert not marked[0]["duplicate_identity"] + + def test_a_row_ip_with_a_port_is_the_same_source_as_the_bare_ip(self, svc): + miners = _miners(_miner("10.0.0.1")) + marked = _poll(svc, [_row("10.0.0.1:54321")], [_reply()], 1000, miners=miners) + assert not marked[0]["duplicate_identity"] + + def test_the_same_machine_with_two_ephemeral_ports_is_not_a_fault(self, svc): + miners = _miners(_miner("10.0.0.1:5555"), _miner("10.0.0.1:6666")) + marked = _poll(svc, [_row("10.0.0.1")], [_reply()], 1000, miners=miners) + assert not marked[0]["duplicate_identity"] + + def test_the_fault_survives_a_failed_miners_fetch(self, svc, monkeypatch): + miners = _miners(_miner("10.0.0.1"), _miner("10.0.0.2")) + marked = _poll(svc, [_row("10.0.0.2")], [_reply()], 1000, miners=miners) + assert marked[0]["duplicate_identity"] + svc.proxy_client.get_miners.side_effect = RuntimeError("proxy down") + marked = _poll(svc, [_row("10.0.0.2")], [_reply()], 1001) + svc.proxy_client.get_miners.assert_called_once() + assert marked[0]["duplicate_identity"] + + def test_a_default_clone_pair_with_no_stratum_rig_id_raises_from_the_login(self, svc): + miners = _miners( + _miner("10.0.0.1", rig_id=None, user="rig1"), + _miner("10.0.0.2", rig_id=None, user="rig1"), + ) + marked = _poll(svc, [_row("10.0.0.2", name="rig1")], [_reply()], 1000, miners=miners) + assert marked[0]["duplicate_identity"] + assert worker_identity._faulted_names == {"rig1"} + + def test_a_login_suffix_still_maps_to_the_worker(self, svc): + miners = _miners( + _miner("10.0.0.1", rig_id=None, user="rig1+5000"), + _miner("10.0.0.2", rig_id=None, user="rig1+5000"), + ) + marked = _poll(svc, [_row("10.0.0.2", name="rig1")], [_reply()], 1000, miners=miners) + assert marked[0]["duplicate_identity"] + + def test_rows_that_differ_only_by_a_login_suffix_stay_separate(self, svc): + rows = [_row("10.0.0.1", name="rig1+5000"), _row("10.0.0.2", name="rig1+6000")] + replies = [_reply(), _reply(rig_id=NEW_RIG)] + miners = _miners( + _miner("10.0.0.1", rig_id=None, user="rig1+5000"), + _miner("10.0.0.2", rig_id=None, user="rig1+6000"), + ) + marked = _poll(svc, rows, replies, 1000, miners=miners) + assert not any(w["duplicate_identity"] for w in marked) + + def test_connections_under_another_login_are_not_attributed(self, svc): + miners = _miners( + _miner("10.0.0.1", rig_id=None, user="rig2"), + _miner("10.0.0.2", rig_id=None, user="rig2"), + ) + marked = _poll(svc, [_row("10.0.0.2", name="rig1")], [_reply()], 1000, miners=miners) + assert not marked[0]["duplicate_identity"] + + def test_no_miners_fetch_without_a_feed_id(self, svc): + marked = _poll(svc, [_row("10.0.0.1")], [{"api_ok": False}], 1000) + svc.proxy_client.get_miners.assert_not_called() + assert not marked[0]["duplicate_identity"] + + def test_the_fault_decays_when_one_copy_stops_answering(self, svc): + miners = _miners(_miner("10.0.0.1"), _miner("10.0.0.2")) + marked = _poll(svc, [_row("10.0.0.1")], [_reply()], 1000, miners=miners) + assert marked[0]["duplicate_identity"] + later = 1000 + IDENTITY_WINDOW_S + 1 + quiet = _miners(_miner("10.0.0.1")) + marked = _poll(svc, [_row("10.0.0.1")], [_reply()], later, miners=quiet) + assert not marked[0]["duplicate_identity"] + + def test_connections_of_unknown_ids_are_not_tracked(self, svc): + miners = _miners(_miner("10.0.0.1", rig_id=NEW_RIG), _miner("10.0.0.2", rig_id=NEW_RIG)) + marked = _poll(svc, [_row("10.0.0.1")], [_reply()], 1000, miners=miners) + assert not marked[0]["duplicate_identity"] + assert not svc._identity.faulted(NEW_RIG, 1000) + + def test_rekeying_one_copy_clears_the_fault(self, svc, monkeypatch): + monkeypatch.setattr( + xmrig_client, + "WORKER_ENDPOINTS", + [{"name": "rig1", "host": "10.0.0.1", "rig_id": RIG, "read_token": "t1"}], + ) + miners = _miners(_miner("10.0.0.1"), _miner("10.0.0.2")) + merged = _poll(svc, [_row("10.0.0.2")], [_reply()], 1000, miners=miners) + assert merged[0]["duplicate_identity"] + monkeypatch.setattr( + xmrig_client, + "WORKER_ENDPOINTS", + [{"name": "rig1", "host": "10.0.0.1", "rig_id": NEW_RIG, "read_token": "t2"}], + ) + rows = [_row("10.0.0.1", name=RIG), _row("10.0.0.2", name=NEW_RIG)] + miners = _miners(_miner("10.0.0.1"), _miner("10.0.0.2", rig_id=NEW_RIG)) + marked = _poll(svc, rows, [_reply(), _reply(rig_id=NEW_RIG)], 1001, miners=miners) + assert all(w["status"] == "online" for w in marked) + assert not any(w["duplicate_identity"] for w in marked) + assert worker_identity._faulted_names == frozenset() + + def test_same_id_different_hints_from_one_source_is_an_info_event(self, svc): + _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_A)], 1000) + marked = _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_B)], 1001) + assert not marked[0]["duplicate_identity"] + events = svc.state_manager.get_audit_events() + assert [(e["source"], e["action"], e["status"]) for e in events] == [ + ("rig-identity", "moved-hardware", "info") + ] + _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_B)], 1002) + assert len(svc.state_manager.get_audit_events()) == 1 + + def test_a_stick_moved_after_a_quiet_gap_is_still_an_info_event(self, svc): + _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_A)], 1000) + later = 1000 + IDENTITY_WINDOW_S + 30 + _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_B)], later) + _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_B)], later + 30) + events = svc.state_manager.get_audit_events() + assert [(e["source"], e["action"], e["status"]) for e in events] == [ + ("rig-identity", "moved-hardware", "info") + ] + + def test_a_second_move_after_the_rate_limit_and_a_gap_is_recorded(self, svc): + _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_A)], 1000) + _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_B)], 1001) + _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_A)], 1001 + 3700) + assert len(svc.state_manager.get_audit_events()) == 2 + + def test_moved_hardware_events_are_rate_limited_per_rig_id(self, svc): + flips = [HINTS_A, HINTS_B] * 4 + for i, hints in enumerate(flips): + _poll(svc, [_row("10.0.0.1")], [_reply(hints)], 1000 + i) + assert len(svc.state_manager.get_audit_events()) == 1 + + +class TestControlStamp: + @pytest.fixture + def spool(self, tmp_path, monkeypatch): + (tmp_path / "requests").mkdir() + (tmp_path / "results").mkdir() + monkeypatch.setattr( + control_service.config, "CONTROL_REQUESTS_DIR", str(tmp_path / "requests") + ) + monkeypatch.setattr( + control_service.config, "CONTROL_RESULTS_DIR", str(tmp_path / "results") + ) + return tmp_path / "requests" + + def _spooled(self, spool, rid): + return json.loads((spool / f"{rid}.json").read_text()) + + def test_verbs_carry_the_fault_only_while_it_is_set(self, spool, monkeypatch): + monkeypatch.setattr(worker_identity, "_faulted_names", frozenset({"rig1"})) + for submit in ( + lambda w: control_service.submit_worker_apply(w, {"DONATION": 1}, "admin"), + lambda w: control_service.submit_worker_upgrade(w, "v1.11.2", "admin"), + ): + assert self._spooled(spool, submit("rig1"))["duplicate_identity"] is True + assert "duplicate_identity" not in self._spooled(spool, submit("rig2")) + monkeypatch.setattr(worker_identity, "_faulted_names", frozenset()) + rid = control_service.submit_worker_apply("rig1", {"DONATION": 1}, "admin") + assert "duplicate_identity" not in self._spooled(spool, rid) + + +class TestParseProxyMiners: + def _payload(self, *rows): + return {"format": MINERS_FORMAT, "miners": [list(r) for r in rows]} + + def test_real_proxy_row_shape_yields_id_and_ip_per_connection(self): + payload = self._payload( + [3, "10.0.0.2", 12, 9, 4, 1000000, "4Awallet", "x", RIG, "xmrig/6.26.0"], + [4, "10.0.0.1", 6, 4, 4, 900000, "4Awallet", "x", None, "xmrig/6.26.0"], + [5, "10.0.0.2", 0, 0, 4, 1, "4Awallet", "x", RIG, "xmrig/6.26.0"], + ) + assert worker_identity_poll._parse_proxy_miners(payload) == [ + (RIG, "10.0.0.2"), + ("4Awallet", "10.0.0.1"), + (RIG, "10.0.0.2"), + ] + + def test_rows_without_key_or_ip_are_dropped(self): + payload = self._payload( + [1, "10.0.0.3", 0, 0, 1, 1, "", "", None, ""], + [2, "", 0, 0, 1, 1, "4Awallet", "", None, ""], + [3, "10.0.0.4", 0, 0, 1, 1, "z" * 129, "", None, ""], + ) + assert worker_identity_poll._parse_proxy_miners(payload) == [] + + def test_malformed_payloads_parse_to_no_sources(self): + assert worker_identity_poll._parse_proxy_miners(None) == [] + assert worker_identity_poll._parse_proxy_miners({"miners": "nope"}) == [] + assert worker_identity_poll._parse_proxy_miners({"miners": ["x", [1, "10.0.0.5"]]}) == [] diff --git a/docs/dev/file-budget.tsv b/docs/dev/file-budget.tsv index 17f1a7548..3188eb08a 100644 --- a/docs/dev/file-budget.tsv +++ b/docs/dev/file-budget.tsv @@ -53,7 +53,6 @@ lib/pithead/28-parse-and-validate-config.sh 464 lib/pithead/33-render-env.sh 481 lib/pithead/36-quadlet-units.sh 418 lib/pithead/48-os-update-verbs.sh 404 -lib/pithead/49-control-request-loop.sh 402 scripts/build-pithead-selftest.sh 416 scripts/watch/scheduled-run-watch.sh 416 scripts/watch/trivyignore-watch.sh 599 diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index 4e9ac8876..a18f4d30d 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -406,6 +406,7 @@ it — the worker-API **auth model is the #315 none/name/token matrix**, not the | The same socket carries the three blocks that drive Worker Inspect: the rig's effective writable `config` (#1235), its `config_meta` provenance (#1345), and the mirrored `control` outcome (#579) — including the fresh-rig `control: null` shape and a non-terminal status, both of which must reconcile nothing | real client vs fake worker API | 2 ✅ (`fakes/test_contract.py`) | | Our fake cannot drift from what a real worker emits (#1412): its `rigforge` key set is compared both ways against a vendored copy of RigForge's own `tests/contract/v1/feed.json`, that copy is pinned to the baked `RIGFORGE_REF` so a pin bump without a re-vendor reds here — and because that ref line is hand-edited text, the vendored bytes are separately byte-compared against RigForge's own copy at the baked ref, so editing `PROVENANCE` alone can no longer green a stale fixture, and a producer the check cannot reach fails in CI rather than skipping (#1426) — and every status word in `control-status.json` must be classified terminal or known-non-terminal, on a vocabulary asserted non-empty so an emptied fixture cannot pass having checked nothing | vendored producer fixtures | 2 ✅ (`fakes/contract/v1/` + `test_contract.py` + `test_contract_freshness.py`) | | The control-status vocabulary's third site (#1422): `dashboard`'s two Python constants are guarded against each other by name, but the `pithead` script's own `control_worker_apply`/`control_worker_upgrade` poll loops carry the same words as literal `case` arms nowhere cross-checked — a word RigForge adds and neither arm matches falls through to "keep polling" and times out as a normal-looking `accepted`, the rigforge#320 noop/throttled history repeating unseen. The two arms are shell literals, so a grep needs no rig: their union must equal the terminal words in the same vendored `control-status.json` the tier-2 guard above anchors to | `pithead` source | 1 ✅ (`tests/stack/control/test-control-status-vocabulary.sh`) | +| Duplicate rig identity (#4182): one rig id answering from two machine addresses — two connections on one merged proxy row, or two online rows with one feed id, matched to the proxy's connections by worker name — raises a fault that decays when one source goes quiet and clears on a token change, while two connections from one address never raise it; one source with changed display hints, even after a gap longer than the window, is an info event, not a fault; `worker-apply` and `worker-upgrade` refuse a faulted worker before any dial | two simulated sources on the pinned proxy's own `/1/workers` and `/1/miners` payload shapes / real in-memory `StateManager` / stub `curl` that records dials | 1 ✅ (`dashboard/tests/service/workers/test_worker_identity.py`, `tests/stack/control/test-control-status-vocabulary.sh`) | | Dashboard parses proxy `/workers` rows → worker list + hashrate aggregation; offline drop-off window | metrics / `worker_presence` | 1 ✅ | | `p2pool.stratum_password` renders `--access-password` (set) / omits it (default-off); the live daemon argv matches the configured mode and rendered password | `pithead` render + proxy entrypoint | 1 ✅ (`tests/stack`, `selftest-miner-connection.sh`: off, auto, literal and rejected mismatches) · 4 ▶ (live PID 1 argv, including flags appended by the entrypoint; miner login accept/reject remains #3078) | | Setup password opt-in, preserved literal/auto credentials, hand-off and Connect a miner identity, explicit absence, TLS fingerprint and no-store responses | Wizard/API/frontend units, host carry self-test and installed-identity verdict controls using real config/env reads (missing reads fail); provision (off), install (auto + TLS), live TLS scenario | 1 ✅ · 4 ▶ (new identity assertions awaiting branch proof) | diff --git a/docs/workers.md b/docs/workers.md index 15fd34d75..a25c5c989 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -427,6 +427,32 @@ no `control` block at all (plain xmrig, or a rig that has never taken a control- parses to nothing — a slow-terminal outcome on those rigs stays `accepted` until the rig reports a status the dashboard recognizes. +#### A cloned, moved or dead stick + +The rig id identifies a stick, so the dashboard can tell three look-alike situations apart. It +reads the id from each connected row's feed on every poll, counts the same id once per stratum +connection the proxy reports under that worker's name (its stratum `rig-id` when set, else its +login), and remembers which machine addresses answered with it. The feed's `rig_id` and the +stratum `rig-id` are separate settings and need not match. Two different rigs that share one pool +login and set no stratum `rig-id` reach the proxy as one worker and look exactly like a clone, so +give each rig its own pool `user` or `rig-id`. + +| Situation | What you see | What to do | +| --- | --- | --- | +| **Clone** — two machines boot from copies of one stick, so both carry the same name, token and rig id | The proxy lists both machines as one worker row whose IP is whichever copy spoke last; presence alone hides the second copy. Within three poll intervals (90 seconds at the default `UPDATE_INTERVAL`) the id answers from two machine addresses. The worker carries a **duplicate identity** fault, and Worker Inspect's apply and upgrade refuse before anything is sent to either rig: *shares its rig id with another machine … re-key one copy*. | Re-key one copy: give it a new rig id and access token, then adopt it again. The fault clears as soon as the old id answers from one machine only, and the re-key itself clears it at once. | +| **Moved stick** — the same stick in different hardware | One IP keeps answering with the same id while the display hints (MAC prefix, board UUID, CPU model) change. It is recorded as an info event, `rig-identity` / `moved-hardware`, in the Security panel's event log, at most once an hour per rig id, however long the stick was off between the two answers. Nothing is blocked. | Nothing: the record, history and token follow the id. | +| **Dead stick** — the machine is gone or off | The row goes offline and stops answering. No fault is raised by the dead stick alone; a replacement booted from a copy counts as a clone only while the original's last answer is still inside the window. | Adopt the replacement; remove the dead entry once the replacement is live. | + +A clone shares the token, so rotating the token on one rig (the Remove rig action, tracked in +issue #4016) reaches only the copy that answers the rotation; the other copy keeps the old token until it +is re-keyed, which is why the fault stays up until one copy is re-keyed. The fault state is held in +memory: a dashboard restart forgets it and raises it again within the window if both copies still +answer. A stick whose DHCP address changes can raise the fault for up to one window while the old +address is still inside the window, then it clears on its own; two stratum connections from the +same address — a miner running several stratum threads — never raise it. The id authenticates +nothing, so any machine on the LAN that connects as a worker and serves the same id raises the +fault too, and it stays until that machine stops answering. + #### RigForge new-release badge When `dashboard.check_for_updates` is on, the dashboard also compares each rig's reported RigForge diff --git a/lib/pithead/46-control-worker-ops.sh b/lib/pithead/46-control-worker-ops.sh index 64050b791..a6a330d7f 100644 --- a/lib/pithead/46-control-worker-ops.sh +++ b/lib/pithead/46-control-worker-ops.sh @@ -51,6 +51,11 @@ resolve_worker_target() { # _wa_reject "$RESOLVE_WORKER_ERR" return 0 fi + if duplicate_identity_refusal "$file" "$worker"; then + _wa_reject "$DUPLICATE_IDENTITY_ERR" + return 0 + fi # Changes must be a non-empty object whose keys are ALL writable via the rig's control path (the # rig re-validates; this is the host-side gate — mirrors rigforge WRITABLE, #185/#236). changes=$(jq -c '.changes // {}' "$file") @@ -223,6 +232,10 @@ control_worker_upgrade() { # _wu_reject "$RESOLVE_WORKER_ERR" return 0 fi + if duplicate_identity_refusal "$file" "$worker"; then + _wu_reject "$DUPLICATE_IDENTITY_ERR" + return 0 + fi local host="$RESOLVED_HOST" cport="$RESOLVED_CPORT" token="$RESOLVED_TOKEN" proposed=$(jq -r '.version // ""' "$file") if ! printf '%s' "$proposed" | grep -qE '^v[0-9]+\.[0-9]+\.[0-9]+$'; then diff --git a/lib/pithead/49-control-request-loop.sh b/lib/pithead/49-control-request-loop.sh index 628a5ddd2..89ccd278e 100644 --- a/lib/pithead/49-control-request-loop.sh +++ b/lib/pithead/49-control-request-loop.sh @@ -76,11 +76,7 @@ control_process_request() { # control_audit "$cdir/audit/control.log" "$id" "" "invalid" "rejected" return 0 fi - # `container` and `lines` ride the read-only diagnostics verbs (#943). They widen this closed - # schema for EVERY action, exactly as `worker`/`changes` already do — the check is a shape - # guard, and the value guard is per-verb: control_diag_logs takes the container name only if it - # matches a member of its own fixed allowlist, and clamps the count host-side. - if [ "$(jq -r '(.action == "tor-history") as $history | [keys[] | select(. != "id" and . != "action" and . != "config" and . != "actor" and . != "version" and . != "worker" and . != "changes" and . != "confirm" and . != "approval" and . != "container" and . != "lines" and . != "chain" and . != "appliance" and . != "hours" and . != "since" and . != "until" and (($history == false) or (. != "outage" and . != "observed_at")))] | length' "$file")" != "0" ]; then + if [ "$(jq -r '(.action == "tor-history") as $history | [keys[] | select(. != "id" and . != "action" and . != "config" and . != "actor" and . != "version" and . != "worker" and . != "changes" and . != "confirm" and . != "approval" and . != "container" and . != "lines" and . != "chain" and . != "appliance" and . != "duplicate_identity" and . != "hours" and . != "since" and . != "until" and (($history == false) or (. != "outage" and . != "observed_at")))] | length' "$file")" != "0" ]; then control_write_result "$cdir/results" "$id" "$(jq -n '{status:"rejected",error:"unexpected keys in request",ts:(now|floor)}')" control_audit "$cdir/audit/control.log" "$id" "" "invalid" "rejected" return 0 diff --git a/tests/stack/control/test-control-status-vocabulary.sh b/tests/stack/control/test-control-status-vocabulary.sh index 5053b71be..72eeffb50 100644 --- a/tests/stack/control/test-control-status-vocabulary.sh +++ b/tests/stack/control/test-control-status-vocabulary.sh @@ -46,3 +46,42 @@ assert_contains "control_worker_apply's terminal case arm was actually found" "$ assert_contains "control_worker_upgrade's terminal case arm was actually found" "$_csv_upgrade_arms" "applied" assert_eq "control_worker_apply + control_worker_upgrade terminal arms union to exactly the fixture's terminal words" \ "$_csv_union_arms" "$_csv_fixture_terminal" + +echo "== control channel: a duplicate-identity rig is refused before any dial (#4182) ==" +DI="$SANDBOX/ctrl4182" +mkdir -p "$DI/staged" "$DI/results" "$DI/audit" "$DI/bin" +cat >"$DI/config.json" <<'JSON' +{ "workers": { "list": [ + { "name": "rig1", "host": "10.0.0.9", "control_port": 8082, "token": "tok-rig1" } +] } } +JSON +cat >"$DI/bin/curl" <>"$DI/dials.log" +exit 7 +STUB +chmod +x "$DI/bin/curl" +di_run() { + printf '%s\n' "$1" >"$DI/req.json" + PATH="$DI/bin:$PATH" PITHEAD_CONFIG_FILE="$DI/config.json" \ + run_sourced_e "$SANDBOX" control_process_request "$DI/req.json" "$DI" >/dev/null 2>&1 +} +di_err() { jq -r '.error // ""' "$DI/results/$1.json"; } +da1="41820000-0001-4001-8001-000000000001" +da2="41820000-0002-4002-8002-000000000002" +du1="41820000-0003-4003-8003-000000000003" +du2="41820000-0004-4004-8004-000000000004" +export CONTROL_WA_BUDGET=5 CONTROL_WU_BUDGET=1 +di_run "{\"id\":\"$da1\",\"action\":\"worker-apply\",\"actor\":\"admin\",\"worker\":\"rig1\",\"changes\":{\"DONATION\":2},\"duplicate_identity\":true}" +di_run "{\"id\":\"$du1\",\"action\":\"worker-upgrade\",\"actor\":\"admin\",\"worker\":\"rig1\",\"version\":\"v1.11.2\",\"duplicate_identity\":true}" +assert_eq "worker-apply of a duplicate-identity rig is rejected" "$(jq -r '.status' "$DI/results/$da1.json")" "rejected" +assert_contains "the apply refusal names the duplicate identity" "$(di_err "$da1")" "shares its rig id" +assert_contains "the apply refusal gives the cure" "$(di_err "$da1")" "re-key one copy" +assert_contains "worker-upgrade of a duplicate-identity rig is refused with the cure" "$(di_err "$du1")" "re-key one copy" +assert_eq "neither refusal dialed the rig, with the dial budget open" "$(cat "$DI/dials.log" 2>/dev/null)" "" +di_run "{\"id\":\"$da2\",\"action\":\"worker-apply\",\"actor\":\"admin\",\"worker\":\"rig1\",\"changes\":{\"DONATION\":2}}" +assert_not_contains "the same apply without the fault is not refused for identity" "$(di_err "$da2")" "shares its rig id" +assert_contains "the same apply without the fault dials the rig" "$(cat "$DI/dials.log" 2>/dev/null)" "dialed" +CONTROL_WU_BUDGET=0 di_run "{\"id\":\"$du2\",\"action\":\"worker-upgrade\",\"actor\":\"admin\",\"worker\":\"rig1\",\"version\":\"v1.11.2\"}" +assert_contains "the same upgrade without the fault gets past the identity gate" "$(di_err "$du2")" "already in this cycle" +unset CONTROL_WA_BUDGET CONTROL_WU_BUDGET