diff --git a/node/rustchain_v2_integrated_v2.2.1_rip200.py b/node/rustchain_v2_integrated_v2.2.1_rip200.py index 6cc410d3bc..dec72274e2 100644 --- a/node/rustchain_v2_integrated_v2.2.1_rip200.py +++ b/node/rustchain_v2_integrated_v2.2.1_rip200.py @@ -74,6 +74,19 @@ def generate_latest(): return b"# Prometheus not available" HW_PROOF_AVAILABLE = False print(f"[INIT] Hardware proof module not found: {e}") +# Temporal entropy validation (bounty #19) +try: + from temporal_entropy_validation import ( + init_temporal_tables, + build_temporal_snapshot, + record_and_validate_temporal, + ) + TEMPORAL_VALIDATION_AVAILABLE = True + print("[INIT] ✓ Temporal entropy validation module loaded") +except ImportError as e: + TEMPORAL_VALIDATION_AVAILABLE = False + print(f"[INIT] Temporal entropy module not found: {e}") + app = Flask(__name__) # Register Hall of Rust blueprint (tables initialized after DB_PATH is set) @@ -659,6 +672,10 @@ def init_db(): (int(time.time()),)) c.execute("INSERT OR IGNORE INTO gov_threshold(id, threshold) VALUES(1, 3)") c.execute("INSERT OR IGNORE INTO checkpoints_meta(k, v) VALUES('chain_id', 'rustchain-mainnet-candidate')") + + # Temporal entropy history/flags tables. + if TEMPORAL_VALIDATION_AVAILABLE: + init_temporal_tables(c) c.commit() # Hardware multipliers @@ -782,16 +799,48 @@ def auto_induct_to_hall(miner: str, device: dict): except Exception as e: print(f"[HALL] Auto-induct error: {e}") -def record_attestation_success(miner: str, device: dict, fingerprint_passed: bool = False, source_ip: str = None): +def record_attestation_success( + miner: str, + device: dict, + fingerprint_passed: bool = False, + source_ip: str = None, + temporal_snapshot: Optional[dict] = None, +): now = int(time.time()) + epoch = slot_to_epoch(current_slot()) + temporal_result = { + "status": "disabled", + "consistency_score": 1.0, + "review_required": False, + "reasons": [], + } + entropy_score = 0.0 + if isinstance(temporal_snapshot, dict): + try: + entropy_score = float(temporal_snapshot.get("entropy_score", 0.0)) + except Exception: + entropy_score = 0.0 + with sqlite3.connect(DB_PATH) as conn: conn.execute(""" INSERT OR REPLACE INTO miner_attest_recent (miner, ts_ok, device_family, device_arch, entropy_score, fingerprint_passed, source_ip) VALUES (?, ?, ?, ?, ?, ?, ?) - """, (miner, now, device.get("device_family", device.get("family", "unknown")), device.get("device_arch", device.get("arch", "unknown")), 0.0, 1 if fingerprint_passed else 0, source_ip)) + """, (miner, now, device.get("device_family", device.get("family", "unknown")), device.get("device_arch", device.get("arch", "unknown")), entropy_score, 1 if fingerprint_passed else 0, source_ip)) + + if TEMPORAL_VALIDATION_AVAILABLE and temporal_snapshot: + temporal_result = record_and_validate_temporal( + conn, + miner=miner, + ts_ok=now, + epoch=epoch, + snapshot=temporal_snapshot, + source_ip=source_ip, + ) + conn.commit() # Auto-induct to Hall of Rust auto_induct_to_hall(miner, device) + return temporal_result # ============================================================================= # FINGERPRINT VALIDATION (RIP-PoA Anti-Emulation) # ============================================================================= @@ -1643,8 +1692,18 @@ def submit_attestation(): print(f"[VM_CHECK] Miner: {miner} - VM DETECTED (zero rewards): {vm_reason}") fingerprint_passed = False # Mark as failed for zero weight - # Record successful attestation (with fingerprint status) - record_attestation_success(miner, device, fingerprint_passed, client_ip) + temporal_snapshot = None + if TEMPORAL_VALIDATION_AVAILABLE: + temporal_snapshot = build_temporal_snapshot(device, fingerprint, signals) + + # Record successful attestation (with fingerprint + temporal status) + temporal_result = record_attestation_success( + miner, + device, + fingerprint_passed, + client_ip, + temporal_snapshot=temporal_snapshot, + ) # Record MACs if provided if macs: @@ -1663,6 +1722,13 @@ def submit_attestation(): enroll_weight = 0.000000001 else: enroll_weight = hw_weight + + # Temporal anomalies are eligible but down-weighted and flagged for review. + if temporal_result.get("review_required"): + enroll_weight = min(enroll_weight, 0.25) + app.logger.warning( + f"[TEMPORAL] {miner[:20]}... flagged review reasons={temporal_result.get('reasons', [])}" + ) miner_id = data.get("miner_id", miner) @@ -1714,7 +1780,8 @@ def submit_attestation(): "status": "accepted", "device": device, "fingerprint_passed": fingerprint_passed, - "macs_recorded": len(macs) if macs else 0 + "macs_recorded": len(macs) if macs else 0, + "temporal_consistency": temporal_result, }) # ============= EPOCH ENDPOINTS ============= @@ -2632,12 +2699,28 @@ def api_miners(): conn.row_factory = sqlite3.Row c = conn.cursor() # Get all miners attested in the last hour - rows = c.execute(""" - SELECT miner, ts_ok, device_family, device_arch, entropy_score - FROM miner_attest_recent - WHERE ts_ok > ? - ORDER BY ts_ok DESC - """, (now - 3600,)).fetchall() + try: + rows = c.execute(""" + SELECT m.miner, m.ts_ok, m.device_family, m.device_arch, m.entropy_score, + COALESCE(t.status, 'unknown') as temporal_status, + COALESCE(t.review_required, 0) as temporal_review_required, + COALESCE(t.consistency_score, 1.0) as temporal_consistency_score + FROM miner_attest_recent m + LEFT JOIN miner_temporal_flags t ON t.miner = m.miner + WHERE m.ts_ok > ? + ORDER BY m.ts_ok DESC + """, (now - 3600,)).fetchall() + except sqlite3.OperationalError: + # Backward compatibility for nodes that have not created temporal tables yet. + rows = c.execute(""" + SELECT miner, ts_ok, device_family, device_arch, entropy_score, + 'unknown' as temporal_status, + 0 as temporal_review_required, + 1.0 as temporal_consistency_score + FROM miner_attest_recent + WHERE ts_ok > ? + ORDER BY ts_ok DESC + """, (now - 3600,)).fetchall() miners = [] for r in rows: @@ -2669,7 +2752,10 @@ def api_miners(): "device_arch": r["device_arch"], "hardware_type": hw_type, # Museum System classification "entropy_score": r["entropy_score"] or 0.0, - "antiquity_multiplier": mult + "antiquity_multiplier": mult, + "temporal_status": r["temporal_status"], + "temporal_review_required": bool(r["temporal_review_required"]), + "temporal_consistency_score": r["temporal_consistency_score"], }) return jsonify(miners) diff --git a/node/temporal_entropy_validation.py b/node/temporal_entropy_validation.py new file mode 100644 index 0000000000..80ce956a8e --- /dev/null +++ b/node/temporal_entropy_validation.py @@ -0,0 +1,287 @@ +#!/usr/bin/env python3 +"""Temporal entropy profile validation for RustChain attestations. + +This module tracks per-miner fingerprint snapshots and flags profiles that are: +- frozen (variance ~ 0 across multiple attestations) +- noisy (variance too high, likely random spoofing) +- out-of-band drift (jumps outside expected ranges) +""" + +from __future__ import annotations + +import json +import math +import statistics +from typing import Dict, List, Optional + +HISTORY_LIMIT = 10 +MIN_SERIES = 3 + +# Expected absolute drift bands per metric between current sample and historical mean. +DRIFT_BANDS = { + "clock_cv": 0.03, + "entropy_score": 0.25, + "thermal_score": 0.35, +} + + +def init_temporal_tables(conn) -> None: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS miner_fingerprint_history ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + miner TEXT NOT NULL, + ts_ok INTEGER NOT NULL, + epoch INTEGER NOT NULL, + clock_cv REAL DEFAULT 0.0, + entropy_score REAL DEFAULT 0.0, + thermal_score REAL DEFAULT 0.0, + simd_identity TEXT DEFAULT '', + source_ip TEXT, + snapshot_json TEXT, + UNIQUE(miner, ts_ok) + ) + """ + ) + conn.execute( + """ + CREATE INDEX IF NOT EXISTS idx_miner_fingerprint_history_miner_ts + ON miner_fingerprint_history(miner, ts_ok DESC) + """ + ) + conn.execute( + """ + CREATE TABLE IF NOT EXISTS miner_temporal_flags ( + miner TEXT PRIMARY KEY, + last_ts INTEGER NOT NULL, + consistency_score REAL NOT NULL, + status TEXT NOT NULL, + review_required INTEGER NOT NULL, + reasons_json TEXT NOT NULL + ) + """ + ) + + +def _safe_float(v, default: float = 0.0) -> float: + try: + return float(v) + except Exception: + return default + + +def build_temporal_snapshot(device: Dict, fingerprint: Dict, signals: Dict) -> Dict: + """Build comparable metrics from attestation payload. + + We intentionally keep this schema compact so it can be used in SQL and tests. + """ + checks = (fingerprint or {}).get("checks", {}) if isinstance(fingerprint, dict) else {} + + def check_data(name: str) -> Dict: + raw = checks.get(name, {}) + if isinstance(raw, dict): + return raw.get("data", {}) if isinstance(raw.get("data", {}), dict) else {} + return {} + + clock = check_data("clock_drift") + thermal = check_data("thermal_variance") + simd = check_data("simd_identity") + + simd_identity = "" + if isinstance(simd.get("profile_hash"), str): + simd_identity = simd.get("profile_hash", "") + elif isinstance(simd.get("cpu_flags_hash"), str): + simd_identity = simd.get("cpu_flags_hash", "") + + if not simd_identity: + simd_identity = str(device.get("device_arch", device.get("arch", "unknown"))) + + snapshot = { + "clock_cv": _safe_float(clock.get("cv", 0.0)), + "entropy_score": _safe_float((signals or {}).get("entropy_score", 0.0)), + "thermal_score": _safe_float(thermal.get("variance", 0.0)), + "simd_identity": simd_identity[:128], + } + return snapshot + + +def _series_stats(values: List[float]) -> Dict[str, float]: + if not values: + return {"mean": 0.0, "var": 0.0, "stdev": 0.0} + mean = statistics.fmean(values) + var = statistics.pvariance(values) if len(values) > 1 else 0.0 + stdev = math.sqrt(var) + return {"mean": mean, "var": var, "stdev": stdev} + + +def _is_frozen(clock_vals: List[float], entropy_vals: List[float], thermal_vals: List[float]) -> bool: + if min(len(clock_vals), len(entropy_vals), len(thermal_vals)) < MIN_SERIES: + return False + clock_var = statistics.pvariance(clock_vals) + entropy_var = statistics.pvariance(entropy_vals) + thermal_var = statistics.pvariance(thermal_vals) + return clock_var <= 1e-10 and entropy_var <= 1e-8 and thermal_var <= 1e-8 + + +def _is_noisy(clock_vals: List[float], entropy_vals: List[float], thermal_vals: List[float]) -> bool: + if min(len(clock_vals), len(entropy_vals), len(thermal_vals)) < MIN_SERIES: + return False + + def cv(vals: List[float]) -> float: + if len(vals) < 2: + return 0.0 + mean = abs(statistics.fmean(vals)) + if mean < 1e-9: + return statistics.pstdev(vals) + return statistics.pstdev(vals) / mean + + return cv(clock_vals) > 0.8 or cv(entropy_vals) > 0.6 or cv(thermal_vals) > 1.0 + + +def validate_temporal_consistency(history_rows: List[Dict], current_snapshot: Dict) -> Dict: + """Validate temporal consistency and return anomaly metadata.""" + rows = list(history_rows) + if len(rows) < MIN_SERIES: + return { + "status": "insufficient_data", + "consistency_score": 1.0, + "review_required": False, + "reasons": [], + } + + clock_vals = [_safe_float(r.get("clock_cv", 0.0)) for r in rows] + entropy_vals = [_safe_float(r.get("entropy_score", 0.0)) for r in rows] + thermal_vals = [_safe_float(r.get("thermal_score", 0.0)) for r in rows] + + reasons: List[str] = [] + score = 1.0 + + if _is_frozen(clock_vals, entropy_vals, thermal_vals): + reasons.append("frozen_profile") + score -= 0.55 + + if _is_noisy(clock_vals, entropy_vals, thermal_vals): + reasons.append("noisy_profile") + score -= 0.45 + + prev_rows = rows[:-1] if len(rows) > 1 else rows + if prev_rows: + prev_clock = _series_stats([_safe_float(r.get("clock_cv", 0.0)) for r in prev_rows]) + prev_entropy = _series_stats([_safe_float(r.get("entropy_score", 0.0)) for r in prev_rows]) + prev_thermal = _series_stats([_safe_float(r.get("thermal_score", 0.0)) for r in prev_rows]) + + if abs(_safe_float(current_snapshot.get("clock_cv", 0.0)) - prev_clock["mean"]) > DRIFT_BANDS["clock_cv"]: + reasons.append("clock_drift_out_of_band") + score -= 0.2 + + if abs(_safe_float(current_snapshot.get("entropy_score", 0.0)) - prev_entropy["mean"]) > DRIFT_BANDS["entropy_score"]: + reasons.append("entropy_drift_out_of_band") + score -= 0.2 + + if abs(_safe_float(current_snapshot.get("thermal_score", 0.0)) - prev_thermal["mean"]) > DRIFT_BANDS["thermal_score"]: + reasons.append("thermal_drift_out_of_band") + score -= 0.2 + + # SIMD identity should be stable. Rapid changes indicate suspicious spoofing. + simd_values = [str(r.get("simd_identity", "")) for r in rows if str(r.get("simd_identity", ""))] + if len(set(simd_values)) > 2: + reasons.append("simd_identity_instability") + score -= 0.25 + + review_required = any(r in reasons for r in ("frozen_profile", "noisy_profile", "simd_identity_instability")) + status = "ok" if not reasons else ("review" if review_required else "drift_warning") + + return { + "status": status, + "consistency_score": max(0.0, round(score, 4)), + "review_required": review_required, + "reasons": reasons, + } + + +def record_and_validate_temporal( + conn, + miner: str, + ts_ok: int, + epoch: int, + snapshot: Dict, + source_ip: Optional[str] = None, + history_limit: int = HISTORY_LIMIT, +) -> Dict: + init_temporal_tables(conn) + + conn.execute( + """ + INSERT OR REPLACE INTO miner_fingerprint_history + (miner, ts_ok, epoch, clock_cv, entropy_score, thermal_score, simd_identity, source_ip, snapshot_json) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + miner, + ts_ok, + epoch, + _safe_float(snapshot.get("clock_cv", 0.0)), + _safe_float(snapshot.get("entropy_score", 0.0)), + _safe_float(snapshot.get("thermal_score", 0.0)), + str(snapshot.get("simd_identity", ""))[:128], + source_ip, + json.dumps(snapshot, separators=(",", ":")), + ), + ) + + # Keep only last N snapshots per miner. + conn.execute( + """ + DELETE FROM miner_fingerprint_history + WHERE miner = ? AND id NOT IN ( + SELECT id FROM miner_fingerprint_history + WHERE miner = ? ORDER BY ts_ok DESC LIMIT ? + ) + """, + (miner, miner, history_limit), + ) + + rows = conn.execute( + """ + SELECT clock_cv, entropy_score, thermal_score, simd_identity + FROM miner_fingerprint_history + WHERE miner = ? + ORDER BY ts_ok ASC + """, + (miner,), + ).fetchall() + + history_rows = [ + { + "clock_cv": r[0], + "entropy_score": r[1], + "thermal_score": r[2], + "simd_identity": r[3], + } + for r in rows + ] + + result = validate_temporal_consistency(history_rows, snapshot) + + conn.execute( + """ + INSERT INTO miner_temporal_flags(miner, last_ts, consistency_score, status, review_required, reasons_json) + VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT(miner) DO UPDATE SET + last_ts=excluded.last_ts, + consistency_score=excluded.consistency_score, + status=excluded.status, + review_required=excluded.review_required, + reasons_json=excluded.reasons_json + """, + ( + miner, + ts_ok, + float(result["consistency_score"]), + result["status"], + 1 if result["review_required"] else 0, + json.dumps(result["reasons"], separators=(",", ":")), + ), + ) + + return result diff --git a/node/tests/test_temporal_entropy_validation.py b/node/tests/test_temporal_entropy_validation.py new file mode 100644 index 0000000000..50802f7edd --- /dev/null +++ b/node/tests/test_temporal_entropy_validation.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +import unittest + +from temporal_entropy_validation import validate_temporal_consistency + + +class TemporalEntropyValidationTests(unittest.TestCase): + def test_frozen_profile_detected(self): + rows = [ + {"clock_cv": 0.0100, "entropy_score": 0.5000, "thermal_score": 0.0200, "simd_identity": "g4"}, + {"clock_cv": 0.0100, "entropy_score": 0.5000, "thermal_score": 0.0200, "simd_identity": "g4"}, + {"clock_cv": 0.0100, "entropy_score": 0.5000, "thermal_score": 0.0200, "simd_identity": "g4"}, + ] + current = rows[-1] + result = validate_temporal_consistency(rows, current) + self.assertTrue(result["review_required"]) + self.assertIn("frozen_profile", result["reasons"]) + + def test_noisy_profile_detected(self): + rows = [ + {"clock_cv": 0.001, "entropy_score": 0.20, "thermal_score": 0.01, "simd_identity": "g4"}, + {"clock_cv": 0.090, "entropy_score": 0.95, "thermal_score": 0.70, "simd_identity": "g4"}, + {"clock_cv": 0.002, "entropy_score": 0.15, "thermal_score": 0.02, "simd_identity": "g4"}, + {"clock_cv": 0.120, "entropy_score": 0.99, "thermal_score": 0.80, "simd_identity": "g4"}, + ] + current = rows[-1] + result = validate_temporal_consistency(rows, current) + self.assertTrue(result["review_required"]) + self.assertIn("noisy_profile", result["reasons"]) + + def test_expected_drift_is_ok(self): + rows = [ + {"clock_cv": 0.020, "entropy_score": 0.55, "thermal_score": 0.10, "simd_identity": "g5"}, + {"clock_cv": 0.022, "entropy_score": 0.58, "thermal_score": 0.11, "simd_identity": "g5"}, + {"clock_cv": 0.024, "entropy_score": 0.57, "thermal_score": 0.12, "simd_identity": "g5"}, + {"clock_cv": 0.026, "entropy_score": 0.59, "thermal_score": 0.13, "simd_identity": "g5"}, + ] + current = rows[-1] + result = validate_temporal_consistency(rows, current) + self.assertIn(result["status"], ("ok", "drift_warning")) + self.assertGreater(result["consistency_score"], 0.5) + + +if __name__ == "__main__": + unittest.main()