From 6d8794f8756d538c719753b5ab47a58b186edfa8 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:09:53 -0600 Subject: [PATCH 1/8] coordinator: a duplicate rig id from two sources blocks control; moved hardware is an info event (#4182) Co-Authored-By: Claude Sonnet 5.5 --- .../service/control_service.py | 3 + .../mining_dashboard/service/data_service.py | 7 +- .../mining_dashboard/service/data_setup.py | 2 + .../service/workers/worker_identity.py | 62 ++++++++ .../service/workers/worker_identity_poll.py | 42 +++++ .../service/workers/test_worker_identity.py | 149 ++++++++++++++++++ docs/dev/testing-strategy.md | 1 + docs/workers.md | 19 +++ lib/pithead/46-control-worker-ops.sh | 13 ++ lib/pithead/49-control-request-loop.sh | 2 +- .../control/test-control-status-vocabulary.sh | 36 +++++ 11 files changed, 331 insertions(+), 5 deletions(-) create mode 100644 dashboard/mining_dashboard/service/workers/worker_identity.py create mode 100644 dashboard/mining_dashboard/service/workers/worker_identity_poll.py create mode 100644 dashboard/tests/service/workers/test_worker_identity.py diff --git a/dashboard/mining_dashboard/service/control_service.py b/dashboard/mining_dashboard/service/control_service.py index 3541897b6e..410cd1a05f 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 74c7264e4b..9e9451f4b1 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 d014456cd8..93ca20ea28 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 0000000000..d2f7f7f809 --- /dev/null +++ b/dashboard/mining_dashboard/service/workers/worker_identity.py @@ -0,0 +1,62 @@ +import time + +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 + +_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 = {} + + def _live(self, rec, now): + return {s: v for s, v in rec["sources"].items() if now - v[0] <= 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 observe(self, rig_id, source, fingerprint, credential, now): + rec = self._rigs.get(rig_id) + if rec is None: + if len(self._rigs) >= _MAX_TRACKED_RIGS: + return False + rec = self._rigs[rig_id] = {"credential": credential, "sources": {}} + if rec["credential"] != credential: + rec["credential"], rec["sources"] = credential, {} + rec["sources"] = self._live(rec, now) + prev = rec["sources"].get(source) + if prev is None and len(rec["sources"]) >= _MAX_SOURCES_PER_RIG: + return False + moved = bool(prev and prev[1] and fingerprint and prev[1] != fingerprint) + rec["sources"][source] = (now, fingerprint or (prev[1] if prev else None)) + 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 0000000000..240b60f5e2 --- /dev/null +++ b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py @@ -0,0 +1,42 @@ +import hashlib +import time + +from mining_dashboard.client import xmrig_client +from mining_dashboard.service import audit_service + + +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, now=None): + now = time.time() if now is None else now + tracker = svc._identity + tracker.sweep(now) + 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 + name = w.get("name") or "" + moved = tracker.observe( + rig_id, w.get("ip"), _fingerprint(rf), _credential_key(name, rig_id), now + ) + if moved and svc._rig_edit_within_cap(name, now)[0]: + 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)) + ), + ) 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 0000000000..dbfbba005c --- /dev/null +++ b/dashboard/tests/service/workers/test_worker_identity.py @@ -0,0 +1,149 @@ +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_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 +HINTS_A = {"mac": "aa:aa", "board_uuid": None, "cpu_model": "A72"} +HINTS_B = {"mac": "bb:bb", "board_uuid": None, "cpu_model": "A72"} + + +def _row(ip, name="rig1"): + return {"name": name, "ip": ip, "status": "online"} + + +def _reply(hints=None, rig_id=RIG): + return { + "api_ok": True, + "rigforge": {"rig_id": rig_id, "identity": hints, "version": "v1.19.0"}, + } + + +@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): + asyncio.run(worker_identity_poll.observe_poll(svc, rows, replies, now=now)) + marked = [dict(r, rigforge=r.get("rigforge") or {"rig_id": RIG}) for r in rows] + return worker_identity.mark_duplicates(svc, marked, 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) + + +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_rekeying_one_copy_clears_the_fault(self, svc, monkeypatch): + rows = [_row("10.0.0.1"), _row("10.0.0.2")] + replies = [_reply(), _reply()] + monkeypatch.setattr( + xmrig_client, "WORKER_ENDPOINTS", [{"name": "rig1", "rig_id": RIG, "read_token": "t1"}] + ) + assert _poll(svc, rows, replies, 1000)[0]["duplicate_identity"] + monkeypatch.setattr( + xmrig_client, "WORKER_ENDPOINTS", [{"name": "rig1", "rig_id": RIG, "read_token": "t2"}] + ) + marked = _poll(svc, rows[:1], replies[:1], 1001) + assert not marked[0]["duplicate_identity"] + + 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 + + +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) diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index 4e9ac8876e..3a95db94e8 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): two online rows answering with one rig id raise a fault that decays when one source goes quiet and clears on a token change; one source with changed display hints is an info event, not a fault; `worker-apply` and `worker-upgrade` refuse a faulted worker before any dial | two simulated sources / 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 15fd34d75c..ba7256e17c 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -427,6 +427,25 @@ 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 and remembers which connecting IPs +answered with it. + +| 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 | Two online rows answer with the same id within three poll intervals (90 seconds at the default `UPDATE_INTERVAL`). The workers carry 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: change its access token, then adopt it again. The fault clears the moment the id is served from one source only. | +| **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 once as an info event, `rig-identity` / `moved-hardware`, in the Security panel's event log. 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, and a replacement booted from a copy is not a clone while the original stays off. | 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 +#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 +row lingers online, then it clears on its own. + #### 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 64050b7915..a6a330d7f3 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 628a5ddd2e..3217385e7c 100644 --- a/lib/pithead/49-control-request-loop.sh +++ b/lib/pithead/49-control-request-loop.sh @@ -80,7 +80,7 @@ control_process_request() { # # 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 5053b71be0..b786934078 100644 --- a/tests/stack/control/test-control-status-vocabulary.sh +++ b/tests/stack/control/test-control-status-vocabulary.sh @@ -46,3 +46,39 @@ 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" CONTROL_WA_BUDGET=0 CONTROL_WU_BUDGET=0 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" +di_run "{\"id\":\"$da1\",\"action\":\"worker-apply\",\"actor\":\"admin\",\"worker\":\"rig1\",\"changes\":{\"DONATION\":2},\"duplicate_identity\":true}" +di_run "{\"id\":\"$da2\",\"action\":\"worker-apply\",\"actor\":\"admin\",\"worker\":\"rig1\",\"changes\":{\"DONATION\":2}}" +di_run "{\"id\":\"$du1\",\"action\":\"worker-upgrade\",\"actor\":\"admin\",\"worker\":\"rig1\",\"version\":\"v1.11.2\",\"duplicate_identity\":true}" +di_run "{\"id\":\"$du2\",\"action\":\"worker-upgrade\",\"actor\":\"admin\",\"worker\":\"rig1\",\"version\":\"v1.11.2\"}" +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 "the same apply without the fault gets past the gate" "$(di_err "$da2")" "too many worker config changes" +assert_contains "worker-upgrade of a duplicate-identity rig is refused with the cure" "$(di_err "$du1")" "re-key one copy" +assert_contains "the same upgrade without the fault gets past the gate" "$(di_err "$du2")" "already in this cycle" +assert_eq "no refusal dialed the rig" "$(cat "$DI/dials.log" 2>/dev/null)" "" From a414c4f8fcb2db8238a5e00b56e7effd1b900ca6 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:09:57 -0600 Subject: [PATCH 2/8] Drop an explanatory comment from the new test helper Co-Authored-By: Claude Sonnet 5.5 --- tests/stack/control/test-control-status-vocabulary.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/stack/control/test-control-status-vocabulary.sh b/tests/stack/control/test-control-status-vocabulary.sh index b786934078..5111e084f8 100644 --- a/tests/stack/control/test-control-status-vocabulary.sh +++ b/tests/stack/control/test-control-status-vocabulary.sh @@ -61,7 +61,7 @@ echo "dialed \$*" >>"$DI/dials.log" exit 7 STUB chmod +x "$DI/bin/curl" -di_run() { # +di_run() { printf '%s\n' "$1" >"$DI/req.json" PATH="$DI/bin:$PATH" CONTROL_WA_BUDGET=0 CONTROL_WU_BUDGET=0 PITHEAD_CONFIG_FILE="$DI/config.json" \ run_sourced_e "$SANDBOX" control_process_request "$DI/req.json" "$DI" >/dev/null 2>&1 From e1e48bef27b5c90dca38065a608ec3dacd909abf Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:14:35 -0600 Subject: [PATCH 3/8] Address review: per-rig-id moved-event limit, real-merge tests, dial-budget-open shell proof, docs wording Co-Authored-By: Claude Sonnet 5.5 --- .../service/workers/worker_identity.py | 4 ++++ .../service/workers/worker_identity_poll.py | 2 +- .../tests/service/workers/test_worker_identity.py | 13 ++++++++++--- docs/workers.md | 10 ++++++---- .../control/test-control-status-vocabulary.sh | 15 +++++++++------ 5 files changed, 30 insertions(+), 14 deletions(-) diff --git a/dashboard/mining_dashboard/service/workers/worker_identity.py b/dashboard/mining_dashboard/service/workers/worker_identity.py index d2f7f7f809..9856c66924 100644 --- a/dashboard/mining_dashboard/service/workers/worker_identity.py +++ b/dashboard/mining_dashboard/service/workers/worker_identity.py @@ -6,6 +6,7 @@ IDENTITY_WINDOW_S = IDENTITY_WINDOW_POLLS * config.UPDATE_INTERVAL _MAX_TRACKED_RIGS = 1024 _MAX_SOURCES_PER_RIG = 8 +MOVED_EVENT_INTERVAL_S = 3600 _faulted_names = frozenset() @@ -44,6 +45,9 @@ def observe(self, rig_id, source, fingerprint, credential, now): if prev is None and len(rec["sources"]) >= _MAX_SOURCES_PER_RIG: return False moved = bool(prev and prev[1] and fingerprint and prev[1] != fingerprint) + moved = moved and now - rec.get("moved_at", float("-inf")) >= MOVED_EVENT_INTERVAL_S + if moved: + rec["moved_at"] = now rec["sources"][source] = (now, fingerprint or (prev[1] if prev else None)) return moved diff --git a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py index 240b60f5e2..f0102e5ca0 100644 --- a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py +++ b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py @@ -29,7 +29,7 @@ async def observe_poll(svc, workers, results, now=None): moved = tracker.observe( rig_id, w.get("ip"), _fingerprint(rf), _credential_key(name, rig_id), now ) - if moved and svc._rig_edit_within_cap(name, now)[0]: + if moved: await svc._record_audit_event( "rig-identity", name, diff --git a/dashboard/tests/service/workers/test_worker_identity.py b/dashboard/tests/service/workers/test_worker_identity.py index dbfbba005c..210379df01 100644 --- a/dashboard/tests/service/workers/test_worker_identity.py +++ b/dashboard/tests/service/workers/test_worker_identity.py @@ -6,6 +6,7 @@ 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 @@ -20,7 +21,7 @@ def _row(ip, name="rig1"): - return {"name": name, "ip": ip, "status": "online"} + return {"name": name, "ip": ip, "status": "online", "uptime": 5} def _reply(hints=None, rig_id=RIG): @@ -41,8 +42,8 @@ def svc(monkeypatch): def _poll(svc, rows, replies, now): asyncio.run(worker_identity_poll.observe_poll(svc, rows, replies, now=now)) - marked = [dict(r, rigforge=r.get("rigforge") or {"rig_id": RIG}) for r in rows] - return worker_identity.mark_duplicates(svc, marked, 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: @@ -119,6 +120,12 @@ def test_same_id_different_hints_from_one_source_is_an_info_event(self, svc): _poll(svc, [_row("10.0.0.1")], [_reply(HINTS_B)], 1002) assert len(svc.state_manager.get_audit_events()) == 1 + 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 diff --git a/docs/workers.md b/docs/workers.md index ba7256e17c..a8b01c3ca4 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -435,16 +435,18 @@ answered with it. | 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 | Two online rows answer with the same id within three poll intervals (90 seconds at the default `UPDATE_INTERVAL`). The workers carry 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: change its access token, then adopt it again. The fault clears the moment the id is served from one source only. | -| **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 once as an info event, `rig-identity` / `moved-hardware`, in the Security panel's event log. 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, and a replacement booted from a copy is not a clone while the original stays off. | Adopt the replacement; remove the dead entry once the replacement is live. | +| **Clone** — two machines boot from copies of one stick, so both carry the same name, token and rig id | Two online rows answer with the same id within three poll intervals (90 seconds at the default `UPDATE_INTERVAL`). The workers carry 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: change its access token, then adopt it again. The fault clears once the id has been served from one source only for a full window, or when you re-key a copy. | +| **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. 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 #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 -row lingers online, then it clears on its own. +row lingers online, then it clears on its own. 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 diff --git a/tests/stack/control/test-control-status-vocabulary.sh b/tests/stack/control/test-control-status-vocabulary.sh index 5111e084f8..72eeffb504 100644 --- a/tests/stack/control/test-control-status-vocabulary.sh +++ b/tests/stack/control/test-control-status-vocabulary.sh @@ -63,7 +63,7 @@ STUB chmod +x "$DI/bin/curl" di_run() { printf '%s\n' "$1" >"$DI/req.json" - PATH="$DI/bin:$PATH" CONTROL_WA_BUDGET=0 CONTROL_WU_BUDGET=0 PITHEAD_CONFIG_FILE="$DI/config.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"; } @@ -71,14 +71,17 @@ 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\":\"$da2\",\"action\":\"worker-apply\",\"actor\":\"admin\",\"worker\":\"rig1\",\"changes\":{\"DONATION\":2}}" di_run "{\"id\":\"$du1\",\"action\":\"worker-upgrade\",\"actor\":\"admin\",\"worker\":\"rig1\",\"version\":\"v1.11.2\",\"duplicate_identity\":true}" -di_run "{\"id\":\"$du2\",\"action\":\"worker-upgrade\",\"actor\":\"admin\",\"worker\":\"rig1\",\"version\":\"v1.11.2\"}" 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 "the same apply without the fault gets past the gate" "$(di_err "$da2")" "too many worker config changes" assert_contains "worker-upgrade of a duplicate-identity rig is refused with the cure" "$(di_err "$du1")" "re-key one copy" -assert_contains "the same upgrade without the fault gets past the gate" "$(di_err "$du2")" "already in this cycle" -assert_eq "no refusal dialed the rig" "$(cat "$DI/dials.log" 2>/dev/null)" "" +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 From 865c7b7c82ca04fc44c3e283867ec0c8114fbd3e Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:27:16 -0600 Subject: [PATCH 4/8] docs: keep the issue reference off the start of a line Co-Authored-By: Claude Sonnet 5.5 --- docs/workers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/workers.md b/docs/workers.md index a8b01c3ca4..07fc45f5e3 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -440,7 +440,7 @@ answered with it. | **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 -#4016) reaches only the copy that answers the rotation; the other copy keeps the old token until it +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 From 1ce93363d686e265242cfd51aa7df6b74dc16d97 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:11:24 -0600 Subject: [PATCH 5/8] Identity fault counts stratum connections, the source a merged proxy row hides (#4182) xmrig-proxy 6.26.0 groups worker rows by rig id (Workers::add keyed by rigId(true), default workers mode RigID), so two cloned machines arrive as ONE row whose IP is whichever connection spoke last; the same-name rows the first cut detected on never occur. Detect instead on the proxy's per-connection /1/miners listing (ApiRouter::getMiners), keyed by rig id with the stratum user as fallback, observing each (id, ip) pair only when the id is a live feed id. A merged clone row now raises the fault from its two connections, two connections from one machine never do, and the re-key proof keeps both copies online through an adopted entry's host. Drop the stale allowlist comment the request-key edit left in the hunk. Co-Authored-By: Claude Code --- .../client/xmrig_proxy_client.py | 6 ++ .../service/workers/worker_identity_poll.py | 52 ++++++++++- .../tests/client/test_xmrig_proxy_client.py | 6 ++ .../service/workers/test_worker_identity.py | 92 +++++++++++++++++-- docs/dev/file-budget.tsv | 1 - docs/dev/testing-strategy.md | 2 +- docs/workers.md | 13 +-- lib/pithead/49-control-request-loop.sh | 4 - 8 files changed, 154 insertions(+), 22 deletions(-) diff --git a/dashboard/mining_dashboard/client/xmrig_proxy_client.py b/dashboard/mining_dashboard/client/xmrig_proxy_client.py index 7cb323b83b..189d7ddb8c 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/workers/worker_identity_poll.py b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py index f0102e5ca0..2d186ec5bd 100644 --- a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py +++ b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py @@ -1,9 +1,53 @@ +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 + + +async def _fetch_miners(svc): + 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 {} @@ -16,15 +60,17 @@ def _fingerprint(rigforge): return tuple(sorted(hints.items())) if hints else None -async def observe_poll(svc, workers, results, now=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() 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 "" moved = tracker.observe( rig_id, w.get("ip"), _fingerprint(rf), _credential_key(name, rig_id), now @@ -40,3 +86,7 @@ async def observe_poll(svc, workers, results, now=None): "rig-moved", rig_id, w.get("ip"), repr(_fingerprint(rf)) ), ) + payload = miners if miners is not None else await _fetch_miners(svc) + for key, ip in _parse_proxy_miners(payload): + if key in feed_ids: + tracker.observe(key, ip, None, _credential_key(key, key), now) diff --git a/dashboard/tests/client/test_xmrig_proxy_client.py b/dashboard/tests/client/test_xmrig_proxy_client.py index a7393d070a..e0d4fa4778 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 index 210379df01..6dfa143fab 100644 --- a/dashboard/tests/service/workers/test_worker_identity.py +++ b/dashboard/tests/service/workers/test_worker_identity.py @@ -16,8 +16,10 @@ ) 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"): @@ -31,6 +33,14 @@ def _reply(hints=None, rig_id=RIG): } +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:") @@ -40,8 +50,8 @@ def svc(monkeypatch): sm.close() -def _poll(svc, rows, replies, now): - asyncio.run(worker_identity_poll.observe_poll(svc, rows, replies, now=now)) +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) @@ -96,18 +106,52 @@ def test_an_offline_or_unanswered_row_is_not_a_source(self, svc): 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_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): - rows = [_row("10.0.0.1"), _row("10.0.0.2")] - replies = [_reply(), _reply()] monkeypatch.setattr( - xmrig_client, "WORKER_ENDPOINTS", [{"name": "rig1", "rig_id": RIG, "read_token": "t1"}] + xmrig_client, + "WORKER_ENDPOINTS", + [{"name": "rig1", "host": "10.0.0.1", "rig_id": RIG, "read_token": "t1"}], ) - assert _poll(svc, rows, replies, 1000)[0]["duplicate_identity"] + 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", "rig_id": RIG, "read_token": "t2"}] + xmrig_client, + "WORKER_ENDPOINTS", + [{"name": "rig1", "host": "10.0.0.1", "rig_id": NEW_RIG, "read_token": "t2"}], ) - marked = _poll(svc, rows[:1], replies[:1], 1001) - assert not marked[0]["duplicate_identity"] + 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) @@ -154,3 +198,33 @@ def test_verbs_carry_the_fault_only_while_it_is_set(self, spool, monkeypatch): 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 17f1a7548d..3188eb08ae 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 3a95db94e8..dac6c6688c 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -406,7 +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): two online rows answering with one rig id raise a fault that decays when one source goes quiet and clears on a token change; one source with changed display hints is an info event, not a fault; `worker-apply` and `worker-upgrade` refuse a faulted worker before any dial | two simulated sources / 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`) | +| 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 — 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 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 07fc45f5e3..cb0d5b39d4 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -430,12 +430,12 @@ 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 and remembers which connecting IPs -answered with it. +reads the id from each connected row's feed on every poll, counts the same id once per stratum +connection the proxy reports, and remembers which machine addresses answered with it. | 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 | Two online rows answer with the same id within three poll intervals (90 seconds at the default `UPDATE_INTERVAL`). The workers carry 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: change its access token, then adopt it again. The fault clears once the id has been served from one source only for a full window, or when you re-key a copy. | +| **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. 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. | @@ -444,9 +444,10 @@ issue #4016) reaches only the copy that answers the rotation; the other copy kee 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 -row lingers online, then it clears on its own. 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. +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 diff --git a/lib/pithead/49-control-request-loop.sh b/lib/pithead/49-control-request-loop.sh index 3217385e7c..89ccd278e9 100644 --- a/lib/pithead/49-control-request-loop.sh +++ b/lib/pithead/49-control-request-loop.sh @@ -76,10 +76,6 @@ 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 . != "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" From ab02c1f0a3d2fed21240573512ccbc2c3564e772 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:49:24 -0600 Subject: [PATCH 6/8] Identity fault normalizes proxy ip:port sources and keeps one credential per id The proxy and stratum occasionally report an "ip:port" form for a worker address, so a healthy machine could present its row address and its connection address as two sources, and a re-login's new ephemeral port looked like a new machine. Strip the port from a source key exactly as the SSRF probe guard does, and let the connection leg reuse the credential the row leg resolved for an id so the two legs never reset each other's source history. Annotate the fail-soft miners fetch return channel, as the collapsed-return gate requires. Co-Authored-By: Claude Code --- .../service/workers/worker_identity_poll.py | 21 ++++++++++++++----- .../service/workers/test_worker_identity.py | 20 ++++++++++++++++++ 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py index 2d186ec5bd..eeb190c7b5 100644 --- a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py +++ b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py @@ -41,7 +41,17 @@ def _parse_proxy_miners(miners_data): return sources -async def _fetch_miners(svc): +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: @@ -65,6 +75,7 @@ async def observe_poll(svc, workers, results, miners=None, now=None): tracker = svc._identity tracker.sweep(now) feed_ids = set() + feed_creds = {} 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 @@ -72,9 +83,9 @@ async def observe_poll(svc, workers, results, miners=None, now=None): continue feed_ids.add(rig_id) name = w.get("name") or "" - moved = tracker.observe( - rig_id, w.get("ip"), _fingerprint(rf), _credential_key(name, rig_id), now - ) + credential = _credential_key(name, rig_id) + feed_creds.setdefault(rig_id, credential) + moved = tracker.observe(rig_id, _source_key(w.get("ip")), _fingerprint(rf), credential, now) if moved: await svc._record_audit_event( "rig-identity", @@ -89,4 +100,4 @@ async def observe_poll(svc, workers, results, miners=None, now=None): payload = miners if miners is not None else await _fetch_miners(svc) for key, ip in _parse_proxy_miners(payload): if key in feed_ids: - tracker.observe(key, ip, None, _credential_key(key, key), now) + tracker.observe(key, _source_key(ip), None, feed_creds.get(key), now) diff --git a/dashboard/tests/service/workers/test_worker_identity.py b/dashboard/tests/service/workers/test_worker_identity.py index 6dfa143fab..9ef6d167b4 100644 --- a/dashboard/tests/service/workers/test_worker_identity.py +++ b/dashboard/tests/service/workers/test_worker_identity.py @@ -117,6 +117,26 @@ def test_two_connections_from_one_machine_are_not_a_fault(self, svc): 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): + monkeypatch.setattr( + xmrig_client, "WORKER_ENDPOINTS", [{"name": "rig1", "read_token": "t1"}] + ) + 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"] + marked = _poll(svc, [_row("10.0.0.2")], [_reply()], 1001) + assert 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) From 94a5bc5458e5593fbff1b8c73513e04a0dbed4ff Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:49:26 -0600 Subject: [PATCH 7/8] Identity fault matches proxy connections to feed ids by worker name and remembers fingerprints across the window (#4182) Co-Authored-By: Claude Sonnet 5.5 --- .../service/workers/worker_identity.py | 36 ++++++--- .../service/workers/worker_identity_poll.py | 9 ++- .../service/workers/test_worker_identity.py | 73 ++++++++++++++++++- docs/dev/testing-strategy.md | 2 +- docs/workers.md | 7 +- 5 files changed, 109 insertions(+), 18 deletions(-) diff --git a/dashboard/mining_dashboard/service/workers/worker_identity.py b/dashboard/mining_dashboard/service/workers/worker_identity.py index 9856c66924..1a36470096 100644 --- a/dashboard/mining_dashboard/service/workers/worker_identity.py +++ b/dashboard/mining_dashboard/service/workers/worker_identity.py @@ -1,4 +1,5 @@ import time +from collections import OrderedDict from mining_dashboard.config import config @@ -6,6 +7,7 @@ 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() @@ -21,9 +23,11 @@ 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: v for s, v in rec["sources"].items() if now - v[0] <= self._window_s} + 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): @@ -32,23 +36,35 @@ def sweep(self, 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 False + 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) - prev = rec["sources"].get(source) - if prev is None and len(rec["sources"]) >= _MAX_SOURCES_PER_RIG: - return False - moved = bool(prev and prev[1] and fingerprint and prev[1] != fingerprint) - moved = moved and now - rec.get("moved_at", float("-inf")) >= MOVED_EVENT_INTERVAL_S - if moved: - rec["moved_at"] = now - rec["sources"][source] = (now, fingerprint or (prev[1] if prev else None)) + 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): diff --git a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py index eeb190c7b5..70050dcaab 100644 --- a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py +++ b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py @@ -76,6 +76,7 @@ async def observe_poll(svc, workers, results, miners=None, now=None): 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 @@ -85,6 +86,7 @@ async def observe_poll(svc, workers, results, miners=None, now=None): name = w.get("name") or "" credential = _credential_key(name, rig_id) feed_creds.setdefault(rig_id, credential) + ids_by_name.setdefault(name.split("+")[0].strip(), rig_id) moved = tracker.observe(rig_id, _source_key(w.get("ip")), _fingerprint(rf), credential, now) if moved: await svc._record_audit_event( @@ -97,7 +99,10 @@ async def observe_poll(svc, workers, results, miners=None, now=None): "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): - if key in feed_ids: - tracker.observe(key, _source_key(ip), None, feed_creds.get(key), now) + rig_id = key if key in feed_ids else 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/service/workers/test_worker_identity.py b/dashboard/tests/service/workers/test_worker_identity.py index 9ef6d167b4..799a823564 100644 --- a/dashboard/tests/service/workers/test_worker_identity.py +++ b/dashboard/tests/service/workers/test_worker_identity.py @@ -86,6 +86,28 @@ def test_one_source_with_changing_hints_is_moved_not_a_fault(self): 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): @@ -128,15 +150,44 @@ def test_the_same_machine_with_two_ephemeral_ports_is_not_a_fault(self, svc): assert not marked[0]["duplicate_identity"] def test_the_fault_survives_a_failed_miners_fetch(self, svc, monkeypatch): - monkeypatch.setattr( - xmrig_client, "WORKER_ENDPOINTS", [{"name": "rig1", "read_token": "t1"}] - ) 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_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) @@ -184,6 +235,22 @@ def test_same_id_different_hints_from_one_source_is_an_info_event(self, svc): _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): diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md index dac6c6688c..a18f4d30d6 100644 --- a/docs/dev/testing-strategy.md +++ b/docs/dev/testing-strategy.md @@ -406,7 +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 — 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 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`) | +| 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 cb0d5b39d4..83fd607c5d 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -431,12 +431,15 @@ status the dashboard recognizes. 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, and remembers which machine addresses answered with it. +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. | 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. Nothing is blocked. | Nothing: the record, history and token follow the id. | +| **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 From 00c782776b2ce216e99ac52e9db6b70def4cc9da Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:50:38 -0600 Subject: [PATCH 8/8] Identity fault keeps suffixed logins separate and documents the shared-login limit (#4182) Co-Authored-By: Claude Sonnet 5.5 --- .../service/workers/worker_identity_poll.py | 6 ++++-- .../tests/service/workers/test_worker_identity.py | 10 ++++++++++ docs/workers.md | 7 ++++--- 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py index 70050dcaab..d828206fee 100644 --- a/dashboard/mining_dashboard/service/workers/worker_identity_poll.py +++ b/dashboard/mining_dashboard/service/workers/worker_identity_poll.py @@ -86,7 +86,7 @@ async def observe_poll(svc, workers, results, miners=None, now=None): name = w.get("name") or "" credential = _credential_key(name, rig_id) feed_creds.setdefault(rig_id, credential) - ids_by_name.setdefault(name.split("+")[0].strip(), rig_id) + 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( @@ -103,6 +103,8 @@ async def observe_poll(svc, workers, results, miners=None, now=None): 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.split("+")[0].strip()) + 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/service/workers/test_worker_identity.py b/dashboard/tests/service/workers/test_worker_identity.py index 799a823564..4644f0b515 100644 --- a/dashboard/tests/service/workers/test_worker_identity.py +++ b/dashboard/tests/service/workers/test_worker_identity.py @@ -175,6 +175,16 @@ def test_a_login_suffix_still_maps_to_the_worker(self, svc): 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"), diff --git a/docs/workers.md b/docs/workers.md index 83fd607c5d..a25c5c9899 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -433,13 +433,14 @@ The rig id identifies a stick, so the dashboard can tell three look-alike situat 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. +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. | +| **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