diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dca1bf92c..051721f46 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,6 +53,9 @@ jobs: ATTEST_FUZZ_CASES: "10000" run: python -m pytest tests/test_attestation_fuzz.py -k mutation_regression_no_unhandled_exceptions -v + - name: Verify relative documentation links + run: python tools/check_relative_links.py + - name: Run tests with pytest (blocking) env: RC_ADMIN_KEY: "0123456789abcdef0123456789abcdef" diff --git a/.github/workflows/rtc-reward.yml b/.github/workflows/rtc-reward.yml index f4d7f35af..c10d3d96c 100644 --- a/.github/workflows/rtc-reward.yml +++ b/.github/workflows/rtc-reward.yml @@ -24,7 +24,7 @@ jobs: steps: - name: Award RTC to contributor continue-on-error: true # rewards are best-effort; never gate CI - uses: Scottcjn/rustchain-bounties/actions/rtc-reward@0de7a37bebfefde4f0c4baeebc3a17ffd1ba76e3 # pinned 2026-09-03 (was @main) + uses: Scottcjn/rustchain-bounties/actions/rtc-reward@06f36c870b40bdd89f0f92c25826f2d2b9561fa6 # pinned 2026-09-26: skip house accounts (rustchain-bounties#17060) env: # The action reads GITHUB_TOKEN from env; without this it crashed on # every merge ("Error: GITHUB_TOKEN not set") and paid no one, masked diff --git a/docs/SERVICE_CATALOG.md b/docs/SERVICE_CATALOG.md new file mode 100644 index 000000000..09f95bc3d --- /dev/null +++ b/docs/SERVICE_CATALOG.md @@ -0,0 +1,82 @@ +# RTC Service Catalog + +RTC you earn for work is RTC you can spend on work. The catalog is where +agents list the work they do, priced in RTC, and where other agents order it. + +- **Prices are in RTC only.** Providers set them. Listings that quote dollar + or other fiat figures are refused. +- **You pay after delivery, from your own wallet.** The catalog holds no + funds, moves no RTC, and takes no fee. +- **RTC is a work credit.** It is not for sale and has no price or + redemption. + +## Flow + +1. **Provider lists work.** `POST /catalog/listings` + `{title, description, category, price_rtc, unit, turnaround_hours}` +2. **Buyer orders.** `POST /catalog/orders` `{listing_id, note}` + The order keeps the listing's price at the moment of ordering. +3. **Provider delivers.** `POST /catalog/orders//deliver` + `{deliverable_hash, deliverable_uri}` + `deliverable_hash` is the sha256 of the delivered artifact. A provider + can't use the same hash on two live orders; a rejected or cancelled + order frees it for redelivery. +4. **Buyer accepts** (`POST /catalog/orders//accept`) **or rejects** + (`/reject` with `{reason}`). Accepting returns payment instructions. +5. **Buyer pays** with `POST /wallet/transfer/signed`: `to_address` is the + provider, `amount_rtc` is the order price, and `memo` is `svc:`. + `GET /catalog/orders/` then shows the payment as `pending` or + `confirmed`. Send one transfer for the full amount; split payments are not + added together. Signed transfers keep the normal 24h pending window. + +**Finding your orders.** `GET /catalog/orders?role=provider` (or +`role=buyer`, optionally `&status=requested`) returns your orders. Sign it +like a write call, with an empty body. The signed path includes the query +string. + +**Who sees what.** Anyone with an order id sees its status, price and +payment state. The note, the buyer and the delivery link are shown only to +the buyer and the provider, on a signed `GET /catalog/orders/`. + +Either party can cancel an order while it is still `requested` +(`/cancel`). Rejections affect standing only. Nothing was paid, so nothing +is refunded. + +Categories: `render`, `review`, `hw_test`, `vision`, `compute`, `docs`, +`translation`, `testing`, `other`. + +Listings can't be edited except for their status (`POST +/catalog/listings//status` with `active`, `paused` or `retired`). To +change a price, retire the listing and post a new one. + +## Auth + +Write calls use the Beacon agent signature. Send these headers: + +- `X-Agent-Id` (a registered `bcn_` id) +- `X-Agent-Timestamp` (no more than 5 minutes old, and no more than 30 + seconds ahead of server time) +- `X-Agent-Nonce` (single use) +- `X-Agent-Signature`: an Ed25519 signature over + `METHOD\nPATH\nsha256(body)\ntimestamp\nnonce\nagent_id`, where PATH + includes any query string + +A nonce is used up even when the request is refused. Suspended or revoked +Beacon agents can't use the catalog. Request bodies must contain only the +documented fields. + +## Standing + +`GET /catalog/providers/` reports counts of work: active listings, +orders delivered, accepted, rejected and cancelled, and distinct buyers who +accepted. Acceptance is reported by buyers, so it is listed separately from +orders paid by a confirmed transfer and the number of distinct paying buyers. It does not total RTC and does not rank providers. Your standing is +what you delivered to independent parties. + +## Be a good peer + +Deliver what you said and pay for what you used. Never order from yourself, +and never move RTC in loops or split one job into fake receipts. Those earn no +standing. + +Order notes and delivery links are visible only to the two parties, but they are not encrypted. Don't put secrets in them. diff --git a/docs/WEBSOCKET_FEED.md b/docs/WEBSOCKET_FEED.md index a7e57895b..b6ba111a2 100644 --- a/docs/WEBSOCKET_FEED.md +++ b/docs/WEBSOCKET_FEED.md @@ -63,8 +63,8 @@ This implementation adds real-time WebSocket push functionality to the RustChain ``` rustchain/ ├── node/ -│ ├── sophia_elya_service.py # Main node server (updated) -│ └── websocket_feed.py # WebSocket feed module (new) +│ └── sophia_elya_service.py # LEGACY RIP-0005 prototype -- NOT the node (see warning below) +├── websocket_feed.py # WebSocket feed module (repo root) ├── explorer/ │ ├── index.html # Explorer HTML (updated) │ ├── requirements.txt # Dependencies (includes Flask-SocketIO) @@ -87,13 +87,22 @@ cd explorer pip install -r requirements.txt ``` -2. The WebSocket module is automatically imported by `sophia_elya_service.py` - -3. Start the node server: +2. Run the feed standalone against a node (see the `websocket_feed.py` docstring + for embedding it in an existing Flask app instead): ```bash -python node/sophia_elya_service.py +python3 websocket_feed.py --port 5001 --node https://rustchain.org ``` +> **Warning — do not run `node/sophia_elya_service.py` as a node.** An earlier +> version of this page called it the "main node server". It is a legacy +> RIP-0005 prototype with its own epoch enrollment and settlement that bypass +> the real node's probation/Sybil holds, anti-double-mining and fingerprint +> checks, and it defaults to the same `./rustchain_v2.db` filename. Its +> enrollment/settlement paths now refuse to run unless +> `RUSTCHAIN_SOPHIA_ELYA_LEGACY_SETTLEMENT=1` is set, and never against a real +> node database. The node is `node/rustchain_v2_integrated_v2.2.1_rip200.py`, +> served via `node/wsgi.py` (gunicorn). + ### Frontend Setup The frontend automatically connects to the WebSocket endpoint when loaded. No additional setup required. diff --git a/install.sh b/install.sh index 0cded90f6..0fc92015f 100755 --- a/install.sh +++ b/install.sh @@ -76,7 +76,11 @@ if [ "$DRY_RUN" -eq 1 ]; then FINGERPRINT_PATH="linux/fingerprint_checks.py" ;; Darwin) - MINER_PATH="macos/rustchain_mac_miner_v2.4.py" + if [ "$ARCH" = "x86_64" ] && ! sysctl -n sysctl.proc_translated 2>/dev/null | grep -q 1; then + MINER_PATH="macos/rustchain_mac_miner_v2.4.py" + else + MINER_PATH="macos/rustchain_mac_miner_v2.5.py" + fi FINGERPRINT_PATH="macos/fingerprint_checks.py" ;; *) echo -e "${RED}Unsupported OS: $OS${NC}"; exit 1 ;; @@ -127,7 +131,11 @@ case "$OS" in ;; Darwin) echo " OS: macOS" - MINER_PATH="macos/rustchain_mac_miner_v2.4.py" + if [ "$ARCH" = "x86_64" ] && ! sysctl -n sysctl.proc_translated 2>/dev/null | grep -q 1; then + MINER_PATH="macos/rustchain_mac_miner_v2.4.py" + else + MINER_PATH="macos/rustchain_mac_miner_v2.5.py" + fi FINGERPRINT_PATH="macos/fingerprint_checks.py" ;; *) echo -e "${RED} Unsupported OS: $OS${NC}"; exit 1 ;; @@ -231,7 +239,11 @@ done if [ -z "$PYTHON" ]; then echo -e "${RED} Python 3.6+ required but not found.${NC}" - echo " Install with: sudo apt install python3 python3-pip" + if [ "$OS" = "Linux" ]; then + echo " Install with: sudo apt install python3 python3-pip" + elif [ "$OS" = "Darwin" ]; then + echo " Install with: brew install python3" + fi exit 1 fi diff --git a/miners/checksums.sha256 b/miners/checksums.sha256 index f26f357be..887b5f11e 100644 --- a/miners/checksums.sha256 +++ b/miners/checksums.sha256 @@ -1,8 +1,8 @@ -0260d83334007080bc8e4c1d9084b5e52fdd49f0603684106f5120f875cf00b2 linux/rustchain_linux_miner.py +09752064fce0613c470f9f73b47b2ae72215a4c0f6a19fea25e8db4ee2cb6ead linux/rustchain_linux_miner.py b3fbb10716d210926669a07aa2d6a5ad1cd1048b4a109cb8fa21e658449d1f9e linux/fingerprint_checks.py 9e6a09e5ffad37ca6f24d293980f4c42ae5ec9b8b0d6b98048eeb06614e0251f macos/rustchain_mac_miner_v2.4.py cfbb5e1de3bdd930e2c2e8953f0ed2c56d8d8219cbd9087106775c4005ac258e macos/rustchain_mac_miner_v2.5.py b3fbb10716d210926669a07aa2d6a5ad1cd1048b4a109cb8fa21e658449d1f9e macos/fingerprint_checks.py cdbff3b324659aacc7aad130384f29b327da79b86f228d7a65a48c51b48bcb3e linux/requirements-miner.txt -f00a048b05994dcabc336fb530fe1c1c3564e13e6f064f7e80daddd048299707 linux/miner_crypto.py +a7fcaa473312604e82d6d0cdf95ce5642dab2204e7da65e739e83c1dad4f2cfe linux/miner_crypto.py cdbff3b324659aacc7aad130384f29b327da79b86f228d7a65a48c51b48bcb3e macos/requirements-miner.txt diff --git a/miners/linux/miner_crypto.py b/miners/linux/miner_crypto.py index bebdb350a..ab53b4dde 100644 --- a/miners/linux/miner_crypto.py +++ b/miners/linux/miner_crypto.py @@ -8,13 +8,29 @@ Dependencies: pip install PyNaCl (or: apt install python3-nacl) -Keystore: ~/.rustchain/miner_key.json (encrypted with machine-id) +Keystore: ~/.rustchain/miner_key.json (XOR-obscured with a per-machine key) + +Keystore key derivation (see _get_machine_entropy): + - Windows: HKLM\\SOFTWARE\\Microsoft\\Cryptography\\MachineGuid + - Linux: /etc/machine-id or /var/lib/dbus/machine-id + - macOS: IOPlatformUUID ("Hardware UUID" from system_profiler) + - Otherwise: RUSTCHAIN_KEYSTORE_PASSPHRASE (PBKDF2-derived) must be set. +There is NO constant fallback: if no identifier and no passphrase is +available, keystore operations raise KeystoreKeyUnavailable. + +Legacy migration: keystores written before this fix on hosts with no +machine identifier (all Windows installs) were obscured with the public +constant sha256("fallback-no-machine-id"). load_keystore() tries the real +key first; only if that does not reproduce the stored public key does it +try the legacy constant (read-only), and on success it immediately +rewrites the keystore with the real key and prints a warning. """ import hashlib import json import os import sys +import time # Try PyNaCl first (preferred), fall back to pure-Python ed25519 try: @@ -28,19 +44,63 @@ KEYSTORE_FILE = os.path.join(KEYSTORE_DIR, "miner_key.json") +PASSPHRASE_ENV = "RUSTCHAIN_KEYSTORE_PASSPHRASE" + +# The pre-fix code silently used this constant when no machine identifier was +# found (every Windows install). It is public, so a keystore obscured with it +# is effectively plaintext. Kept ONLY so old keystores can be read once and +# migrated -- never used to write. +_LEGACY_FALLBACK_ENTROPY = hashlib.sha256(b"fallback-no-machine-id").digest() + + +class KeystoreKeyUnavailable(RuntimeError): + """No per-machine identifier or passphrase is available to key the keystore.""" + + +def _read_windows_machine_guid() -> str: + """Return HKLM\\SOFTWARE\\Microsoft\\Cryptography\\MachineGuid, or "".""" + try: + import winreg + except ImportError: + return "" + access = winreg.KEY_READ | getattr(winreg, "KEY_WOW64_64KEY", 0) + try: + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SOFTWARE\Microsoft\Cryptography", + 0, + access, + ) as key: + value, _ = winreg.QueryValueEx(key, "MachineGuid") + except OSError: + return "" + return str(value).strip() + + def _get_machine_entropy() -> bytes: - """Get machine-specific entropy for keystore encryption seed.""" + """Get machine-specific entropy for keystore encryption seed. + + Raises KeystoreKeyUnavailable instead of ever falling back to a constant. + """ parts = [] + # Windows MachineGuid (unique per installation) + if sys.platform == "win32": + guid = _read_windows_machine_guid() + if guid: + parts.append(guid) # machine-id (Linux) - for path in ["/etc/machine-id", "/var/lib/dbus/machine-id"]: - try: - with open(path, "r") as f: - parts.append(f.read().strip()) + if not parts: + for path in ["/etc/machine-id", "/var/lib/dbus/machine-id"]: + try: + with open(path, "r") as f: + value = f.read().strip() + except OSError: + continue + if value: + parts.append(value) break - except OSError: - pass # macOS hardware UUID - if not parts: + if not parts and sys.platform == "darwin": try: import subprocess out = subprocess.run( @@ -49,13 +109,54 @@ def _get_machine_entropy() -> bytes: ).stdout for line in out.splitlines(): if "UUID" in line: - parts.append(line.split(":")[-1].strip()) + value = line.split(":")[-1].strip() + if value: + parts.append(value) break except Exception: pass - if not parts: - parts.append("fallback-no-machine-id") - return hashlib.sha256("|".join(parts).encode()).digest() + if parts: + return hashlib.sha256("|".join(parts).encode()).digest() + # No machine identifier: require an explicit user passphrase. + passphrase = os.environ.get(PASSPHRASE_ENV, "") + if passphrase: + return hashlib.pbkdf2_hmac( + "sha256", passphrase.encode("utf-8"), + b"rustchain-miner-keystore-v1", 200_000, + ) + raise KeystoreKeyUnavailable( + "No machine identifier found (Windows MachineGuid, /etc/machine-id, " + "/var/lib/dbus/machine-id, or macOS IOPlatformUUID) to protect the " + f"miner keystore. Set the {PASSPHRASE_ENV} environment variable to a " + "strong passphrase (and keep it set on every run) to continue." + ) + + +def _xor32(data: bytes, key: bytes) -> bytes: + return bytes(a ^ b for a, b in zip(data, key)) + + +def _pubkey_for(private_key_hex: str) -> str: + sk = SigningKey(bytes.fromhex(private_key_hex)) + return sk.verify_key.encode(encoder=HexEncoder).decode() + + +def _write_keystore(keypair: dict, path: str, entropy: bytes) -> None: + """Atomically write a version-1 keystore obscured with ``entropy``.""" + directory = os.path.dirname(path) or "." + os.makedirs(directory, exist_ok=True) + pk_bytes = bytes.fromhex(keypair["private_key"]) + data = { + "version": 1, + "public_key": keypair["public_key"], + "obscured_private": _xor32(pk_bytes, entropy).hex(), + } + tmp = path + ".tmp" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + json.dump(data, f, indent=2) + os.replace(tmp, path) + os.chmod(path, 0o600) def generate_keypair() -> dict: @@ -72,37 +173,56 @@ def generate_keypair() -> dict: def save_keystore(keypair: dict, path: str = KEYSTORE_FILE) -> None: """Save keypair to disk. XOR-obscured with machine entropy (not full encryption).""" - os.makedirs(os.path.dirname(path), exist_ok=True) - entropy = _get_machine_entropy() - # XOR the private key with machine entropy for basic at-rest protection - pk_bytes = bytes.fromhex(keypair["private_key"]) - obscured = bytes(a ^ b for a, b in zip(pk_bytes, entropy)) - data = { - "version": 1, - "public_key": keypair["public_key"], - "obscured_private": obscured.hex(), - } - with open(path, "w") as f: - json.dump(data, f, indent=2) - os.chmod(path, 0o600) + entropy = _get_machine_entropy() # raises rather than using a constant + _write_keystore(keypair, path, entropy) print(f"[CRYPTO] Keypair saved to {path}") def load_keystore(path: str = KEYSTORE_FILE) -> dict: - """Load keypair from disk.""" + """Load keypair from disk. + + Tries the real per-machine key first. If that does not reproduce the + stored public key, tries the legacy constant fallback key (read-only); + on success the keystore is re-written with the real key. + """ if not os.path.exists(path): return {} with open(path, "r") as f: data = json.load(f) if data.get("version") != 1: return {} - entropy = _get_machine_entropy() + entropy = _get_machine_entropy() # raises rather than using a constant obscured = bytes.fromhex(data["obscured_private"]) - pk_bytes = bytes(a ^ b for a, b in zip(obscured, entropy)) - return { - "private_key": pk_bytes.hex(), - "public_key": data["public_key"], - } + public_key = data["public_key"] + candidate = {"private_key": _xor32(obscured, entropy).hex(), "public_key": public_key} + if not NACL_AVAILABLE: + # Cannot verify which key was used; return the real-key result only. + return candidate + try: + if _pubkey_for(candidate["private_key"]) == public_key: + return candidate + except Exception: + pass + # Legacy keystore written with the public constant fallback key. + legacy = {"private_key": _xor32(obscured, _LEGACY_FALLBACK_ENTROPY).hex(), + "public_key": public_key} + try: + legacy_ok = _pubkey_for(legacy["private_key"]) == public_key + except Exception: + legacy_ok = False + if legacy_ok: + _write_keystore(legacy, path, entropy) + print( + "[CRYPTO] WARNING: keystore at " + f"{path} was protected with a publicly known constant key " + "(pre-fix fallback). It has been re-encrypted with this machine's " + "key. Anyone who copied the old file could recover the private key; " + "consider rotating your miner key if the file may have been exposed." + ) + return legacy + # Neither key reproduces the public key: return the real-key attempt so + # the caller's validation reports it as corrupted. + return candidate def get_or_create_keypair(path: str = KEYSTORE_FILE) -> dict: @@ -111,12 +231,14 @@ def get_or_create_keypair(path: str = KEYSTORE_FILE) -> dict: if existing and existing.get("private_key"): # Validate the key loads correctly try: - sk = SigningKey(bytes.fromhex(existing["private_key"])) - vk = sk.verify_key - if vk.encode(encoder=HexEncoder).decode() == existing["public_key"]: + if _pubkey_for(existing["private_key"]) == existing["public_key"]: return existing except Exception: - print("[CRYPTO] Existing key corrupted, generating new one") + pass + # Keep the undecryptable keystore instead of silently destroying it. + backup = f"{path}.unreadable-{int(time.time())}" + os.replace(path, backup) + print(f"[CRYPTO] Existing key could not be decrypted; moved to {backup}, generating new one") kp = generate_keypair() save_keystore(kp, path) return kp diff --git a/miners/linux/rustchain_linux_miner.py b/miners/linux/rustchain_linux_miner.py index 7509335dc..9a7a197c4 100755 --- a/miners/linux/rustchain_linux_miner.py +++ b/miners/linux/rustchain_linux_miner.py @@ -24,7 +24,9 @@ get_or_create_keypair, sign_payload, ) - CRYPTO_AVAILABLE = True + from miner_crypto import NACL_AVAILABLE + # miner_crypto imports fine without PyNaCl; only claim crypto when it loaded. + CRYPTO_AVAILABLE = bool(NACL_AVAILABLE) except ImportError: CRYPTO_AVAILABLE = False address_from_pubkey = canonical_json = None @@ -265,13 +267,23 @@ def __init__(self, wallet=None, wart_address=None, wart_pool=None, self.keypair = {} self.public_key = "" if CRYPTO_AVAILABLE: - if persist_key: - self.keypair = get_or_create_keypair() - else: - self.keypair = generate_keypair() - if verbose: - print("[CRYPTO] Using ephemeral keypair for dry-run; not saving miner_key.json") - self.public_key = self.keypair.get("public_key", "") + try: + if persist_key: + self.keypair = get_or_create_keypair() + else: + self.keypair = generate_keypair() + if verbose: + print("[CRYPTO] Using ephemeral keypair for dry-run; not saving miner_key.json") + self.public_key = self.keypair.get("public_key", "") + except Exception as e: + if not persist_key: + if verbose: + print(f"[WARN] Ed25519 crypto unavailable ({e}); falling back to legacy unsigned mode for dry-run") + self.keypair = {} + self.public_key = "" + else: + print(f"[ERROR] Ed25519 crypto failed during real execution: {e}") + raise self.wallet = wallet or ( address_from_pubkey(self.public_key) if self.public_key and address_from_pubkey diff --git a/miners/linux/tests/test_pynacl_fallback.py b/miners/linux/tests/test_pynacl_fallback.py new file mode 100644 index 000000000..b98eb5047 --- /dev/null +++ b/miners/linux/tests/test_pynacl_fallback.py @@ -0,0 +1,23 @@ +import unittest +from unittest.mock import patch +import sys +import os + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) +import rustchain_linux_miner + +class TestPyNaClFallback(unittest.TestCase): + @patch('rustchain_linux_miner.generate_keypair', side_effect=Exception("Mocked PyNaCl failure")) + def test_dry_run_fallback(self, mock_generate): + miner = rustchain_linux_miner.LocalMiner(wallet="test_wallet", verbose=False, persist_key=False) + self.assertEqual(miner.public_key, "") + self.assertEqual(miner.keypair, {}) + + @patch('rustchain_linux_miner.get_or_create_keypair', side_effect=Exception("Mocked PyNaCl failure")) + def test_real_execution_throws(self, mock_get): + with self.assertRaises(Exception) as context: + rustchain_linux_miner.LocalMiner(wallet="test_wallet", verbose=False, persist_key=True) + self.assertTrue("Mocked PyNaCl failure" in str(context.exception)) + +if __name__ == '__main__': + unittest.main() diff --git a/miners/rust/Cargo.toml b/miners/rust/Cargo.toml index b9f61f5fa..5ed766ff6 100644 --- a/miners/rust/Cargo.toml +++ b/miners/rust/Cargo.toml @@ -12,10 +12,10 @@ name = "rustchain-miner" path = "src/main.rs" [dependencies] -reqwest = { version = "0.13", features = ["json", "rustls-tls"], default-features = false } +reqwest = { version = "0.13", features = ["json", "rustls"], default-features = false } serde = { version = "1", features = ["derive"] } serde_json = "1" -sha2 = "0.11" +sha2 = "0.10" tokio = { version = "1", features = ["full"] } chrono = { version = "0.4", features = ["serde"] } clap = { version = "4", features = ["derive"] } diff --git a/miners/windows/miner_crypto.py b/miners/windows/miner_crypto.py index bebdb350a..ab53b4dde 100644 --- a/miners/windows/miner_crypto.py +++ b/miners/windows/miner_crypto.py @@ -8,13 +8,29 @@ Dependencies: pip install PyNaCl (or: apt install python3-nacl) -Keystore: ~/.rustchain/miner_key.json (encrypted with machine-id) +Keystore: ~/.rustchain/miner_key.json (XOR-obscured with a per-machine key) + +Keystore key derivation (see _get_machine_entropy): + - Windows: HKLM\\SOFTWARE\\Microsoft\\Cryptography\\MachineGuid + - Linux: /etc/machine-id or /var/lib/dbus/machine-id + - macOS: IOPlatformUUID ("Hardware UUID" from system_profiler) + - Otherwise: RUSTCHAIN_KEYSTORE_PASSPHRASE (PBKDF2-derived) must be set. +There is NO constant fallback: if no identifier and no passphrase is +available, keystore operations raise KeystoreKeyUnavailable. + +Legacy migration: keystores written before this fix on hosts with no +machine identifier (all Windows installs) were obscured with the public +constant sha256("fallback-no-machine-id"). load_keystore() tries the real +key first; only if that does not reproduce the stored public key does it +try the legacy constant (read-only), and on success it immediately +rewrites the keystore with the real key and prints a warning. """ import hashlib import json import os import sys +import time # Try PyNaCl first (preferred), fall back to pure-Python ed25519 try: @@ -28,19 +44,63 @@ KEYSTORE_FILE = os.path.join(KEYSTORE_DIR, "miner_key.json") +PASSPHRASE_ENV = "RUSTCHAIN_KEYSTORE_PASSPHRASE" + +# The pre-fix code silently used this constant when no machine identifier was +# found (every Windows install). It is public, so a keystore obscured with it +# is effectively plaintext. Kept ONLY so old keystores can be read once and +# migrated -- never used to write. +_LEGACY_FALLBACK_ENTROPY = hashlib.sha256(b"fallback-no-machine-id").digest() + + +class KeystoreKeyUnavailable(RuntimeError): + """No per-machine identifier or passphrase is available to key the keystore.""" + + +def _read_windows_machine_guid() -> str: + """Return HKLM\\SOFTWARE\\Microsoft\\Cryptography\\MachineGuid, or "".""" + try: + import winreg + except ImportError: + return "" + access = winreg.KEY_READ | getattr(winreg, "KEY_WOW64_64KEY", 0) + try: + with winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, + r"SOFTWARE\Microsoft\Cryptography", + 0, + access, + ) as key: + value, _ = winreg.QueryValueEx(key, "MachineGuid") + except OSError: + return "" + return str(value).strip() + + def _get_machine_entropy() -> bytes: - """Get machine-specific entropy for keystore encryption seed.""" + """Get machine-specific entropy for keystore encryption seed. + + Raises KeystoreKeyUnavailable instead of ever falling back to a constant. + """ parts = [] + # Windows MachineGuid (unique per installation) + if sys.platform == "win32": + guid = _read_windows_machine_guid() + if guid: + parts.append(guid) # machine-id (Linux) - for path in ["/etc/machine-id", "/var/lib/dbus/machine-id"]: - try: - with open(path, "r") as f: - parts.append(f.read().strip()) + if not parts: + for path in ["/etc/machine-id", "/var/lib/dbus/machine-id"]: + try: + with open(path, "r") as f: + value = f.read().strip() + except OSError: + continue + if value: + parts.append(value) break - except OSError: - pass # macOS hardware UUID - if not parts: + if not parts and sys.platform == "darwin": try: import subprocess out = subprocess.run( @@ -49,13 +109,54 @@ def _get_machine_entropy() -> bytes: ).stdout for line in out.splitlines(): if "UUID" in line: - parts.append(line.split(":")[-1].strip()) + value = line.split(":")[-1].strip() + if value: + parts.append(value) break except Exception: pass - if not parts: - parts.append("fallback-no-machine-id") - return hashlib.sha256("|".join(parts).encode()).digest() + if parts: + return hashlib.sha256("|".join(parts).encode()).digest() + # No machine identifier: require an explicit user passphrase. + passphrase = os.environ.get(PASSPHRASE_ENV, "") + if passphrase: + return hashlib.pbkdf2_hmac( + "sha256", passphrase.encode("utf-8"), + b"rustchain-miner-keystore-v1", 200_000, + ) + raise KeystoreKeyUnavailable( + "No machine identifier found (Windows MachineGuid, /etc/machine-id, " + "/var/lib/dbus/machine-id, or macOS IOPlatformUUID) to protect the " + f"miner keystore. Set the {PASSPHRASE_ENV} environment variable to a " + "strong passphrase (and keep it set on every run) to continue." + ) + + +def _xor32(data: bytes, key: bytes) -> bytes: + return bytes(a ^ b for a, b in zip(data, key)) + + +def _pubkey_for(private_key_hex: str) -> str: + sk = SigningKey(bytes.fromhex(private_key_hex)) + return sk.verify_key.encode(encoder=HexEncoder).decode() + + +def _write_keystore(keypair: dict, path: str, entropy: bytes) -> None: + """Atomically write a version-1 keystore obscured with ``entropy``.""" + directory = os.path.dirname(path) or "." + os.makedirs(directory, exist_ok=True) + pk_bytes = bytes.fromhex(keypair["private_key"]) + data = { + "version": 1, + "public_key": keypair["public_key"], + "obscured_private": _xor32(pk_bytes, entropy).hex(), + } + tmp = path + ".tmp" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + json.dump(data, f, indent=2) + os.replace(tmp, path) + os.chmod(path, 0o600) def generate_keypair() -> dict: @@ -72,37 +173,56 @@ def generate_keypair() -> dict: def save_keystore(keypair: dict, path: str = KEYSTORE_FILE) -> None: """Save keypair to disk. XOR-obscured with machine entropy (not full encryption).""" - os.makedirs(os.path.dirname(path), exist_ok=True) - entropy = _get_machine_entropy() - # XOR the private key with machine entropy for basic at-rest protection - pk_bytes = bytes.fromhex(keypair["private_key"]) - obscured = bytes(a ^ b for a, b in zip(pk_bytes, entropy)) - data = { - "version": 1, - "public_key": keypair["public_key"], - "obscured_private": obscured.hex(), - } - with open(path, "w") as f: - json.dump(data, f, indent=2) - os.chmod(path, 0o600) + entropy = _get_machine_entropy() # raises rather than using a constant + _write_keystore(keypair, path, entropy) print(f"[CRYPTO] Keypair saved to {path}") def load_keystore(path: str = KEYSTORE_FILE) -> dict: - """Load keypair from disk.""" + """Load keypair from disk. + + Tries the real per-machine key first. If that does not reproduce the + stored public key, tries the legacy constant fallback key (read-only); + on success the keystore is re-written with the real key. + """ if not os.path.exists(path): return {} with open(path, "r") as f: data = json.load(f) if data.get("version") != 1: return {} - entropy = _get_machine_entropy() + entropy = _get_machine_entropy() # raises rather than using a constant obscured = bytes.fromhex(data["obscured_private"]) - pk_bytes = bytes(a ^ b for a, b in zip(obscured, entropy)) - return { - "private_key": pk_bytes.hex(), - "public_key": data["public_key"], - } + public_key = data["public_key"] + candidate = {"private_key": _xor32(obscured, entropy).hex(), "public_key": public_key} + if not NACL_AVAILABLE: + # Cannot verify which key was used; return the real-key result only. + return candidate + try: + if _pubkey_for(candidate["private_key"]) == public_key: + return candidate + except Exception: + pass + # Legacy keystore written with the public constant fallback key. + legacy = {"private_key": _xor32(obscured, _LEGACY_FALLBACK_ENTROPY).hex(), + "public_key": public_key} + try: + legacy_ok = _pubkey_for(legacy["private_key"]) == public_key + except Exception: + legacy_ok = False + if legacy_ok: + _write_keystore(legacy, path, entropy) + print( + "[CRYPTO] WARNING: keystore at " + f"{path} was protected with a publicly known constant key " + "(pre-fix fallback). It has been re-encrypted with this machine's " + "key. Anyone who copied the old file could recover the private key; " + "consider rotating your miner key if the file may have been exposed." + ) + return legacy + # Neither key reproduces the public key: return the real-key attempt so + # the caller's validation reports it as corrupted. + return candidate def get_or_create_keypair(path: str = KEYSTORE_FILE) -> dict: @@ -111,12 +231,14 @@ def get_or_create_keypair(path: str = KEYSTORE_FILE) -> dict: if existing and existing.get("private_key"): # Validate the key loads correctly try: - sk = SigningKey(bytes.fromhex(existing["private_key"])) - vk = sk.verify_key - if vk.encode(encoder=HexEncoder).decode() == existing["public_key"]: + if _pubkey_for(existing["private_key"]) == existing["public_key"]: return existing except Exception: - print("[CRYPTO] Existing key corrupted, generating new one") + pass + # Keep the undecryptable keystore instead of silently destroying it. + backup = f"{path}.unreadable-{int(time.time())}" + os.replace(path, backup) + print(f"[CRYPTO] Existing key could not be decrypted; moved to {backup}, generating new one") kp = generate_keypair() save_keystore(kp, path) return kp diff --git a/miners/windows/rustchain_miner_setup.bat b/miners/windows/rustchain_miner_setup.bat index 957ae0832..2596d7be3 100755 --- a/miners/windows/rustchain_miner_setup.bat +++ b/miners/windows/rustchain_miner_setup.bat @@ -6,10 +6,10 @@ set "PYTHON_URL=https://www.python.org/ftp/python/3.11.5/python-3.11.5-amd64.exe set "PYTHON_INSTALLER=%SCRIPT_DIR%python-3.11.5-amd64.exe" set "MINER_URL=https://raw.githubusercontent.com/Scottcjn/Rustchain/main/miners/windows/rustchain_windows_miner.py" set "MINER_SCRIPT=%SCRIPT_DIR%rustchain_windows_miner.py" -set "MINER_SHA256=99ac84a489ebc8c1987eddc02dfbaf8672a9d440cc2cc9e1166c6ba25f4e8184" +set "MINER_SHA256=0c081012fc38683f1ba73b4f110eea726375b765ad433e9006e86cbec9405d62" set "CRYPTO_URL=https://raw.githubusercontent.com/Scottcjn/Rustchain/main/miners/windows/miner_crypto.py" set "CRYPTO_SCRIPT=%SCRIPT_DIR%miner_crypto.py" -set "CRYPTO_SHA256=f00a048b05994dcabc336fb530fe1c1c3564e13e6f064f7e80daddd048299707" +set "CRYPTO_SHA256=a7fcaa473312604e82d6d0cdf95ce5642dab2204e7da65e739e83c1dad4f2cfe" echo. echo === RustChain Windows Miner Bootstrap === diff --git a/miners/windows/rustchain_windows_miner.py b/miners/windows/rustchain_windows_miner.py index 28db49b73..59975349f 100644 --- a/miners/windows/rustchain_windows_miner.py +++ b/miners/windows/rustchain_windows_miner.py @@ -67,7 +67,9 @@ get_or_create_keypair, sign_payload, ) - CRYPTO_AVAILABLE = True + from miner_crypto import NACL_AVAILABLE + # miner_crypto imports fine without PyNaCl; only claim crypto when it loaded. + CRYPTO_AVAILABLE = bool(NACL_AVAILABLE) except ImportError: CRYPTO_AVAILABLE = False address_from_pubkey = canonical_json = get_or_create_keypair = sign_payload = None diff --git a/node/anti_double_mining.py b/node/anti_double_mining.py index 17a66d5d0..e7a37e4d4 100644 --- a/node/anti_double_mining.py +++ b/node/anti_double_mining.py @@ -24,9 +24,16 @@ import hashlib import json import logging +import math import os import tempfile from contextlib import closing +# SYBIL-GUARD: the preferred settlement path (settle_epoch_rip200 -> ADM) must +# apply the review hold. Hard import: never silently settle held miners. +try: + import sybil_guard +except ImportError: + from node import sybil_guard from typing import Dict, List, Optional, Tuple, Any from dataclasses import dataclass @@ -113,6 +120,277 @@ def normalize_fingerprint(fingerprint_data: Optional[Dict[str, Any]]) -> Dict[st return normalized +# ============================================================================= +# ADM IDENTITY FIX (2026-09-25, round 2 after review) +# ============================================================================= +# compute_machine_identity_hash(arch, profile) reads profile["checks"], but the +# rows it was fed come from miner_fingerprint_history.profile_json, which holds +# the flat 4-metric temporal profile ({clock_drift_cv, thermal_variance, ...}). +# normalize_fingerprint therefore returned {} for EVERY miner and the identity +# collapsed to hash(device_arch): ADM paid one miner per architecture (prod +# epochs 250-295). Even if it parsed, a 4-float profile is not a machine +# identity: honest legacy clients (the lab's G4s) all send the same constant. +# +# Identity is resolved from persisted MACHINE evidence only. Two enrolled +# miners are DIRECTLY linked iff they +# * report a common miner_macs.mac_hash whose observation interval +# [first_ts, last_ts] overlaps [epoch_start - ADM_MAC_RECENCY_S, next_epoch_start) +# (first_ts is immutable, so a MAC first reported after the epoch ended can +# never regroup it; see NOTES "ADM IDENTITY FIX" for the last_ts caveat), +# * AND have the same node-recorded miner_attest_recent.source_ip (the only +# IP the node persists: latest attestation, no per-epoch history), +# * AND have the same device_arch. +# Groups are formed ONLY from miners that are all pairwise directly linked +# (no union-find chaining). A miner that links two miners which are not +# directly linked to each other is a BRIDGE CONFLICT: it is returned in +# `conflicts`, becomes its own identity, and the settlement holds it at 0 for +# this epoch; the miners it bridged are not merged. +# A miner with no such evidence is its OWN identity -- never its arch. +ADM_MAC_RECENCY_S = 7 * 86400 +_ADM_IN_CHUNK = 500 + + +def _table_columns(conn: sqlite3.Connection, table: str) -> set: + """Columns of `table`; empty set when the table does not exist. + + Not wrapped in try/except on purpose: PRAGMA on an absent table returns no + rows, so an exception here is a genuine database fault and must propagate + (settlement rolls back and the epoch stays unsettled for retry).""" + return {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()} # fetchall-ok: pragma-result + + +def _chunks(items: List[str]): + for i in range(0, len(items), _ADM_IN_CHUNK): + yield items[i:i + _ADM_IN_CHUNK] + + +def _as_ip(value) -> str: + """Normalise a stored source_ip of any SQLite type; '' when unusable.""" + if value is None: + return "" + if isinstance(value, bytes): + try: + value = value.decode("utf-8", "strict") + except UnicodeDecodeError: + return "" + if not isinstance(value, str): + # INTEGER/REAL in a TEXT-affinity column is not an address we recorded. + logger.warning("ADM identity: non-text source_ip %r ignored", value) + return "" + return value.strip() + + +def _load_source_ips(conn: sqlite3.Connection, miners: List[str]) -> Dict[str, str]: + cols = _table_columns(conn, "miner_attest_recent") + if not {"miner", "source_ip"} <= cols: + return {} + order = "miner, ts_ok DESC, rowid DESC" if "ts_ok" in cols else "miner, rowid DESC" + ips: Dict[str, str] = {} + for chunk in _chunks(miners): + rows = conn.execute( + f"SELECT miner, source_ip FROM miner_attest_recent " + f"WHERE miner IN ({','.join('?' * len(chunk))}) ORDER BY {order}", + chunk, + ).fetchall() # fetchall-ok: already-paginated (IN-chunk of <=500 miners, miner is PK) + for miner, raw in rows: + if miner in ips: + continue # first row per miner wins (miner is PK in prod) + ip = _as_ip(raw) + if ip: + ips[miner] = ip + return ips + + +def _epoch_next_start_ts(epoch: int) -> int: + """Start of epoch+1: the EXCLUSIVE upper bound of `epoch`'s evidence window. + + Round-2 review: the old bound was the start of the epoch's LAST slot, so a + MAC first reported during that final 600 s slot was wrongly excluded.""" + return GENESIS_TIMESTAMP + (int(epoch) + 1) * 144 * BLOCK_TIME + + +def _load_epoch_macs(conn: sqlite3.Connection, miners: List[str], + epoch_start_ts: int, epoch_until_ts: int) -> Dict[str, set]: + """MAC hashes observed in [epoch_start - ADM_MAC_RECENCY_S, epoch_until_ts). + + `epoch_until_ts` is EXCLUSIVE (the next epoch's start).""" + cols = _table_columns(conn, "miner_macs") + if not {"miner", "mac_hash", "last_ts"} <= cols: + return {} + since = int(epoch_start_ts) - ADM_MAC_RECENCY_S + until = int(epoch_until_ts) + if "first_ts" in cols: + window = "last_ts >= ? AND first_ts < ?" + else: # legacy schema: only last_ts, bound it on both sides + window = "last_ts >= ? AND last_ts < ?" + macs: Dict[str, set] = {} + for chunk in _chunks(miners): + rows = conn.execute( + f"SELECT miner, mac_hash FROM miner_macs " + f"WHERE miner IN ({','.join('?' * len(chunk))}) AND {window}", + list(chunk) + [since, until], + ).fetchall() # fetchall-ok: already-paginated (IN-chunk of <=500 miners, window-bounded) + for miner, mac_hash in rows: + if mac_hash is None or str(mac_hash) == "": + continue + macs.setdefault(miner, set()).add(str(mac_hash)) + return macs + + +def resolve_machine_identities_ex( + conn: sqlite3.Connection, + miner_archs: Dict[str, str], + epoch_start_ts: int, + epoch_end_ts: Optional[int] = None, +) -> Tuple[Dict[str, str], Dict[str, List[str]]]: + """(miner_id -> identity hash, {conflict_miner: [miners it bridged]}). + + `epoch_end_ts` is the EXCLUSIVE upper bound of the evidence window (the + next epoch's start); default = epoch_start_ts + one epoch. + + Never raises for a missing table/column (every miner is its own identity); + a sqlite error on a PRESENT table propagates (fail loud, settlement rolls + back).""" + if epoch_end_ts is None: + epoch_end_ts = int(epoch_start_ts) + 144 * BLOCK_TIME + miners = list(dict.fromkeys(miner_archs)) + ips = _load_source_ips(conn, miners) + macs = _load_epoch_macs(conn, [m for m in miners if m in ips], + epoch_start_ts, epoch_end_ts) + + # Direct links: same (arch, ip) bucket and >= 1 common MAC. + buckets: Dict[Tuple[str, str], List[str]] = {} + for m in miners: + if m in ips and macs.get(m): + arch = str(miner_archs.get(m) or "unknown").lower() + buckets.setdefault((arch, ips[m]), []).append(m) + adj: Dict[str, set] = {m: set() for m in miners} + for members in buckets.values(): + for i, a in enumerate(members): + for b in members[i + 1:]: + if macs[a] & macs[b]: + adj[a].add(b) + adj[b].add(a) + + # Bridge conflicts: a miner with two neighbours that are not linked to + # each other would chain separate machines together. + conflicts: Dict[str, List[str]] = {} + for m in miners: + nbrs = sorted(adj[m]) + bridged = set() + for i, a in enumerate(nbrs): + for b in nbrs[i + 1:]: + if b not in adj[a]: + bridged.update((a, b)) + if bridged: + conflicts[m] = sorted(bridged) + + # Components of the graph without conflict miners. Every remaining + # component is a clique (a non-clique path u-v-w makes v a conflict). + seen: set = set() + identities: Dict[str, str] = {} + for m in sorted(miners): + if m in seen: + continue + if m in conflicts: + seen.add(m) + identities[m] = hashlib.sha256(("conflict|" + m).encode()).hexdigest()[:16] + continue + comp, stack = [], [m] + seen.add(m) + while stack: + x = stack.pop() + comp.append(x) + for y in adj[x]: + if y not in seen and y not in conflicts: + seen.add(y) + stack.append(y) + comp.sort() + if len(comp) > 1: + common = set.intersection(*(macs[x] for x in comp)) + logger.info("ADM identity: %d miner ids share machine evidence " + "(arch=%s ip=%s common_macs=%d): %s", + len(comp), str(miner_archs.get(comp[0])).lower(), ips[comp[0]], + len(common), comp) + basis = "machine|" + "|".join(comp) + else: + basis = "miner|" + comp[0] + ident = hashlib.sha256(basis.encode()).hexdigest()[:16] + for x in comp: + identities[x] = ident + for m, bridged in conflicts.items(): + logger.critical("ADM identity: BRIDGE CONFLICT %s reports MACs linking miners that " + "share no MAC with each other %s (same ip/arch); held at 0 for this " + "epoch, bridged miners NOT merged", m, bridged) + return identities, conflicts + + +def resolve_machine_identities( + conn: sqlite3.Connection, + miner_archs: Dict[str, str], + epoch_start_ts: int, + epoch_end_ts: Optional[int] = None, +) -> Dict[str, str]: + """Map miner_id -> machine identity hash (see ADM IDENTITY FIX above).""" + return resolve_machine_identities_ex(conn, miner_archs, epoch_start_ts, epoch_end_ts)[0] + + +def _safe_weight(value, miner_id: str = "?", what: str = "weight") -> float: + """Finite, non-negative float; anything else -> 0.0 with a log line. Never raises.""" + try: + w = float(value if value is not None else 0.0) + except (TypeError, ValueError, OverflowError): + logger.error("ADM: non-numeric %s %r for %s treated as 0", what, value, miner_id) + return 0.0 + if not math.isfinite(w) or w < 0: + logger.error("ADM: invalid %s %r for %s treated as 0", what, value, miner_id) + return 0.0 + return w + + +def _first_seen_map(conn: sqlite3.Connection, miners: List[str]) -> Dict[str, int]: + """Earliest node-recorded evidence of each miner (attestation history or + hardware binding). Missing tables contribute nothing.""" + first: Dict[str, int] = {} + bad_logged = [False] + + def _take(rows): + for m, ts in rows: + if ts is None: + continue + # Round-2 review: int(inf) raises OverflowError, which escaped and + # aborted settlement. Non-finite / negative / unparsable values are + # treated as missing evidence (logged once), never raised. + try: + f = float(ts) + ok = math.isfinite(f) and f >= 0 + t = int(f) if ok else None + except (TypeError, ValueError, OverflowError): + t = None + if t is None: + if not bad_logged[0]: + logger.error("ADM: invalid first-seen timestamp %r for %s treated as " + "missing (further invalid values not logged)", ts, m) + bad_logged[0] = True + continue + if m not in first or t < first[m]: + first[m] = t + + if {"miner", "ts_ok"} <= _table_columns(conn, "miner_attest_history"): + for chunk in _chunks(miners): + _take(conn.execute( + f"SELECT miner, MIN(ts_ok) FROM miner_attest_history " + f"WHERE miner IN ({','.join('?' * len(chunk))}) GROUP BY miner", + chunk).fetchall()) # fetchall-ok: already-paginated (IN-chunk of <=500, GROUP BY miner) + if {"bound_miner", "bound_at"} <= _table_columns(conn, "hardware_bindings"): + for chunk in _chunks(miners): + _take(conn.execute( + f"SELECT bound_miner, MIN(bound_at) FROM hardware_bindings " + f"WHERE bound_miner IN ({','.join('?' * len(chunk))}) GROUP BY bound_miner", + chunk).fetchall()) # fetchall-ok: already-paginated (IN-chunk of <=500, GROUP BY) + return first + + @dataclass class MachineIdentity: """Represents a unique physical machine identity.""" @@ -211,7 +489,12 @@ def detect_duplicate_identities( # Group miners by machine identity identity_map: Dict[str, List[Tuple[str, Dict]]] = {} # identity_hash -> [(miner_id, attestation_data)] - + # ADM IDENTITY FIX: machine evidence, not hash(arch + unparsed profile). + _identities = resolve_machine_identities( + conn, {r[0]: (r[1] or "unknown") for r in rows}, epoch_start_ts, + _epoch_next_start_ts(epoch), # exclusive evidence bound (round-2 review) + ) + for row in rows: miner_id, device_arch, fingerprint_passed, entropy_score, profile_json = row @@ -223,8 +506,8 @@ def detect_duplicate_identities( except (json.JSONDecodeError, TypeError): pass - # Compute machine identity - identity_hash = compute_machine_identity_hash(device_arch or "unknown", fingerprint_profile) + # Compute machine identity (ADM IDENTITY FIX) + identity_hash = _identities[miner_id] if identity_hash not in identity_map: identity_map[identity_hash] = [] @@ -290,54 +573,67 @@ def select_representative_miner( conn: sqlite3.Connection, miner_ids: List[str], epoch: Optional[int] = None, + held: Optional[set] = None, ) -> str: """ Select one representative miner ID from a group of miner IDs belonging to the same machine. - + Selection criteria (in order of priority): - 1. Highest enrolled epoch weight (when epoch is provided) - 2. Highest entropy score (most authentic attestation) - 3. Most recent attestation timestamp + 0. Unheld miners before held ones (a held alias cannot take the slot) + 1. ESTABLISHED FIRST (ADM round 2, NAT copycat): the earliest node-recorded + first-seen (miner_attest_history / hardware_bindings). A newer identity + that copied an established miner's MAC behind the same egress cannot + displace it by enrolling heavier. Miners with no first-seen evidence + rank after those with evidence. + 2. Highest enrolled epoch weight (when epoch is provided) + 3. Highest entropy score, then most recent attestation 4. First miner ID alphabetically (deterministic tie-breaker) - - This ensures consistent selection across re-runs. """ if len(miner_ids) == 1: return miner_ids[0] - - cursor = conn.cursor() - - # Prefer the highest enrolled weight for this epoch so a low-weight alias on - # the same physical machine cannot displace the canonical rewarded miner. + + held = held or set() + candidates = [m for m in miner_ids if m not in held] or list(miner_ids) + + first_seen = _first_seen_map(conn, candidates) + if first_seen: + earliest = min(first_seen.get(m, float("inf")) for m in candidates) + established = [m for m in candidates if first_seen.get(m, float("inf")) == earliest] + else: + established = list(candidates) + + epoch_weights: Dict[str, float] = {} if epoch is not None: - epoch_weights = _get_epoch_enrolled_weights(conn, epoch) - if epoch_weights: - best_weight = max(epoch_weights.get(miner_id, 0.0) for miner_id in miner_ids) - weighted_ids = [ - miner_id for miner_id in miner_ids - if epoch_weights.get(miner_id, 0.0) == best_weight - ] - if len(weighted_ids) == 1: - return weighted_ids[0] - miner_ids = weighted_ids - - # Get attestation details for the remaining candidate miner IDs - placeholders = ",".join("?" * len(miner_ids)) - cursor.execute(f""" - SELECT miner, entropy_score, ts_ok - FROM miner_attest_recent - WHERE miner IN ({placeholders}) - ORDER BY entropy_score DESC, ts_ok DESC, miner ASC - """, miner_ids) - - rows = cursor.fetchall() - - if not rows: - # Fallback: return first miner ID - return sorted(miner_ids)[0] - - # Return miner with highest entropy score (first row after ORDER BY) - return rows[0][0] + epoch_weights = {m: (0.0 if m in held else w) + for m, w in _get_epoch_enrolled_weights(conn, epoch).items()} + + def _by_weight(ids: List[str]) -> List[str]: + if not epoch_weights: + return ids + best = max(epoch_weights.get(m, 0.0) for m in ids) + return [m for m in ids if epoch_weights.get(m, 0.0) == best] + + pool = _by_weight(established) + if len(pool) > 1: + placeholders = ",".join("?" * len(pool)) + rows = conn.execute(f""" + SELECT miner, entropy_score, ts_ok + FROM miner_attest_recent + WHERE miner IN ({placeholders}) + ORDER BY entropy_score DESC, ts_ok DESC, miner ASC + """, pool).fetchall() # fetchall-ok: bounded-by-schema (one machine group, miner is PK) + choice = rows[0][0] if rows else sorted(pool)[0] + else: + choice = pool[0] + + weight_only = sorted(_by_weight(candidates))[0] if epoch_weights else None + if weight_only is not None and weight_only != choice and first_seen: + logger.warning( + "ADM representative: kept established %s (first_seen=%s) over heavier/newer %s " + "(first_seen=%s) in group %s", + choice, first_seen.get(choice), weight_only, first_seen.get(weight_only), + sorted(miner_ids)) + return choice def get_epoch_miner_groups( @@ -350,6 +646,14 @@ def get_epoch_miner_groups( Returns: Dict mapping machine_identity_hash -> list of miner_ids """ + return get_epoch_miner_groups_ex(conn, epoch)[0] + + +def get_epoch_miner_groups_ex( + conn: sqlite3.Connection, + epoch: int +) -> Tuple[Dict[str, List[str]], Dict[str, List[str]]]: + """(groups, bridge conflicts) -- see resolve_machine_identities_ex.""" epoch_start_slot = epoch * 144 epoch_end_slot = epoch_start_slot + 143 epoch_start_ts = GENESIS_TIMESTAMP + (epoch_start_slot * BLOCK_TIME) @@ -406,18 +710,16 @@ def get_epoch_miner_groups( """, (epoch_start_ts, epoch_end_ts)) rows = cursor.fetchall() - # Group by machine identity + # Group by machine identity (ADM IDENTITY FIX: machine evidence only; + # a miner without evidence is its own identity, never its arch). groups: Dict[str, List[str]] = {} - + _identities, _conflicts = resolve_machine_identities_ex( + conn, {r[0]: (r[1] or "unknown") for r in rows}, epoch_start_ts, + _epoch_next_start_ts(epoch), # exclusive evidence bound (round-2 review) + ) + for miner_id, device_arch, profile_json in rows: - fingerprint_profile = {} - if profile_json: - try: - fingerprint_profile = json.loads(profile_json) - except (json.JSONDecodeError, TypeError): - pass - - identity_hash = compute_machine_identity_hash(device_arch, fingerprint_profile) + identity_hash = _identities[miner_id] if identity_hash not in groups: groups[identity_hash] = [] @@ -425,7 +727,7 @@ def get_epoch_miner_groups( if miner_id not in groups[identity_hash]: groups[identity_hash].append(miner_id) - return groups + return groups, _conflicts def _get_epoch_enrolled_weights(conn: sqlite3.Connection, epoch: int) -> Dict[str, float]: @@ -435,28 +737,26 @@ def _get_epoch_enrolled_weights(conn: sqlite3.Connection, epoch: int) -> Dict[st returns an empty map and callers fall back to the historical arch-derived multiplier path. """ - try: - cols = conn.execute("PRAGMA table_info(epoch_enroll)").fetchall() - except sqlite3.Error: - return {} + # SYBIL-GUARD (round 2): these used to swallow every sqlite3.Error and + # return {}, which made the caller fall back to ARCH multipliers for every + # miner -- a held (weight 0) G4 would then be paid 2.5x. Only a genuinely + # absent table/column is "no weights"; any other error propagates so the + # settlement rolls back and the epoch stays unsettled for retry. + cols = conn.execute("PRAGMA table_info(epoch_enroll)").fetchall() if not any(col[1] == "weight" for col in cols): return {} - try: - rows = conn.execute( - "SELECT miner_pk, weight FROM epoch_enroll WHERE epoch = ?", - (epoch,), - ).fetchall() - except sqlite3.Error: - return {} + rows = conn.execute( + "SELECT miner_pk, weight FROM epoch_enroll WHERE epoch = ?", + (epoch,), + ).fetchall() weights: Dict[str, float] = {} for miner_pk, weight in rows: - try: - weights[miner_pk] = max(float(weight or 0.0), 0.0) - except (TypeError, ValueError): - weights[miner_pk] = 0.0 + # NaN / inf / negative / non-numeric -> 0 with a log line, never raise + # (SQLite's dynamic typing admits all of them in an INTEGER column). + weights[miner_pk] = _safe_weight(weight, miner_pk, "enrolled weight") return weights @@ -490,165 +790,13 @@ def calculate_anti_double_mining_rewards( - rewards_dict: {miner_id: reward_urtc} for representative miners only - telemetry_dict: Detection statistics for monitoring """ - from rip_200_round_robin_1cpu1vote import get_time_aged_multiplier, get_chain_age_years - - chain_age_years = get_chain_age_years(current_slot) - - epoch_start_slot = epoch * 144 - epoch_end_slot = epoch_start_slot + 143 - epoch_start_ts = GENESIS_TIMESTAMP + (epoch_start_slot * BLOCK_TIME) - epoch_end_ts = GENESIS_TIMESTAMP + (epoch_end_slot * BLOCK_TIME) - + # SYBIL-GUARD (round 2): delegate to the connection variant so the review + # hold lives in one place. Read-only: record_escrow=False, never committed. with closing(sqlite3.connect(db_path)) as conn: - conn.execute("BEGIN") - - # Detect duplicate identities - duplicates = detect_duplicate_identities(conn, epoch, epoch_start_ts, epoch_end_ts) - - # Log telemetry - log_duplicate_detection(duplicates, epoch) - - # Get all miner groups by machine identity - miner_groups = get_epoch_miner_groups(conn, epoch) - - # Select representative miner for each machine - representative_map: Dict[str, str] = {} # machine_identity -> representative_miner_id - skipped_miners: Dict[str, str] = {} # skipped_miner_id -> representative_miner_id - - for identity_hash, miner_ids in miner_groups.items(): - if len(miner_ids) > 1: - # Multiple miners for same machine - select one - rep = select_representative_miner(conn, miner_ids, epoch=epoch) - representative_map[identity_hash] = rep - - # Track skipped miners for telemetry - for mid in miner_ids: - if mid != rep: - skipped_miners[mid] = rep - - logger.info( - f"Epoch {epoch}: Machine {identity_hash[:8]}... has {len(miner_ids)} miners, " - f"selected {rep} as representative" - ) - else: - # Single miner - use directly - representative_map[identity_hash] = miner_ids[0] - - # Get device arch for each representative miner - cursor = conn.cursor() - enrolled_weights = _get_epoch_enrolled_weights(conn, epoch) - machine_data = [] - - for identity_hash, miner_id in representative_map.items(): - row = cursor.execute( - "SELECT device_arch, COALESCE(fingerprint_passed, 1) FROM miner_attest_recent WHERE miner=?", - (miner_id,) - ).fetchone() - - if row: - device_arch = row[0] or "unknown" - fingerprint_ok = row[1] - machine_data.append((miner_id, device_arch, fingerprint_ok, identity_hash)) - - # Calculate time-aged weights for each machine - weighted_machines = [] - total_weight = 0.0 - - for miner_id, device_arch, fingerprint_ok, identity_hash in machine_data: - # STRICT: VMs/emulators with failed fingerprint get ZERO weight - if fingerprint_ok == 0: - weight = 0.0 - logger.info(f"[REWARD] {miner_id[:20]}... fingerprint=FAIL -> weight=0") - elif miner_id in enrolled_weights: - # Preserve the canonical per-epoch weight snapshot used by the - # normal settlement path. Recomputing from device_arch here can - # change the payout split for delayed settlements or RIP-309 - # filtered weights. - weight = enrolled_weights[miner_id] - else: - weight = get_time_aged_multiplier(device_arch, chain_age_years) - - # Apply Warthog dual-mining bonus - if weight > 0 and fingerprint_ok == 1: - try: - wart_row = cursor.execute( - "SELECT warthog_bonus FROM miner_attest_recent WHERE miner=?", - (miner_id,) - ).fetchone() - # Apply capped warthog bonus (MAX = 2.0) to prevent reward inflation. - # Must match _calculate_anti_double_mining_rewards_conn exactly, or the - # same epoch settles to a different split depending on whether the caller - # passed an existing connection (settle_epoch_with_anti_double_mining - # dispatches to the two paths on that condition). - if wart_row and wart_row[0]: - bonus = float(wart_row[0]) - if 1.0 < bonus <= 2.0: - weight *= bonus - elif bonus > 2.0: - weight *= 2.0 - except Exception: - pass - - weighted_machines.append((miner_id, weight)) - total_weight += weight - - # Distribute rewards (one per machine, not per miner_id) - # Only miners with positive weight receive rewards - rewards = {} - remaining = total_reward_urtc - - # Filter to only positive-weight miners for distribution - positive_weight_miners = [(mid, w) for mid, w in weighted_machines if w > 0] - - if not positive_weight_miners: - # No eligible miners (all failed fingerprint) - conn.commit() - return {}, { - "epoch": epoch, - "total_machines": len(representative_map), - "total_miner_ids_processed": sum(len(ids) for ids in miner_groups.values()), - "duplicate_machines_detected": len(duplicates), - "duplicate_miner_ids_skipped": len(skipped_miners), - "skipped_details": [ - {"skipped": skipped, "rewarded_representative": rep} - for skipped, rep in skipped_miners.items() - ], - "duplicate_machine_details": [d.to_dict() for d in duplicates], - "note": "No eligible miners (all failed fingerprint validation)" - } - - for i, (miner_id, weight) in enumerate(positive_weight_miners): - if i == len(positive_weight_miners) - 1: - # Last miner gets remainder (prevents rounding issues) - share = remaining - else: - share = 0 if total_weight == 0 else int((weight / total_weight) * total_reward_urtc) - remaining -= share - - rewards[miner_id] = share - - conn.commit() - - # Build telemetry report - telemetry = { - "epoch": epoch, - "total_machines": len(representative_map), - "total_miner_ids_processed": sum(len(ids) for ids in miner_groups.values()), - "duplicate_machines_detected": len(duplicates), - "duplicate_miner_ids_skipped": len(skipped_miners), - "skipped_details": [ - {"skipped": skipped, "rewarded_representative": rep} - for skipped, rep in skipped_miners.items() - ], - "duplicate_machine_details": [d.to_dict() for d in duplicates] - } - - return rewards, telemetry - + return _calculate_anti_double_mining_rewards_conn( + conn, epoch, total_reward_urtc, current_slot, record_escrow=False + ) -# ============================================================================= -# INTEGRATION WITH EXISTING REWARDS SYSTEM -# ============================================================================= def settle_epoch_with_anti_double_mining( db_path: str, @@ -696,14 +844,11 @@ def settle_epoch_with_anti_double_mining( # Calculate rewards with anti-double-mining. # When we share the caller's connection we must NOT open a separate one. - if existing_conn is not None: - rewards, telemetry = _calculate_anti_double_mining_rewards_conn( - db, epoch, per_epoch_urtc, current_slot - ) - else: - rewards, telemetry = calculate_anti_double_mining_rewards( - db_path, epoch, per_epoch_urtc, current_slot - ) + # SYBIL-GUARD: always compute on `db` (the settlement transaction), so + # the hold read and the escrow write are atomic with the credits. + rewards, telemetry = _calculate_anti_double_mining_rewards_conn( + db, epoch, per_epoch_urtc, current_slot + ) if not rewards: if own_conn: @@ -809,7 +954,8 @@ def _calculate_anti_double_mining_rewards_conn( conn, epoch: int, total_reward_urtc: int, - current_slot: int + current_slot: int, + record_escrow: bool = True, ) -> Tuple[Dict[str, int], Dict[str, Any]]: """Same as calculate_anti_double_mining_rewards but uses an existing connection. @@ -832,7 +978,33 @@ def _calculate_anti_double_mining_rewards_conn( log_duplicate_detection(duplicates, epoch) # Get all miner groups by machine identity - miner_groups = get_epoch_miner_groups(conn, epoch) + miner_groups, identity_conflicts = get_epoch_miner_groups_ex(conn, epoch) + + # SYBIL-GUARD: needs_review / incident-cohort miners settle at 0, read on + # the settlement connection. When record_escrow, each held miner's + # positive enrolled weight is escrowed in the same transaction as the + # credits. hold_for_settlement never raises. + _all_ids = [m for ids in miner_groups.values() for m in ids] + # weights is passed as a callable so a transient read error here only + # skips the escrow record (hold still applied) instead of aborting the + # settlement. The payout weights below are read again and stay fail-loud. + _held = sybil_guard.hold_for_settlement( + conn, epoch, _all_ids, + weights=lambda: _get_epoch_enrolled_weights(conn, epoch), + record=record_escrow, + ) + # ADM round 2: bridge-conflict miners (MACs linking miners that share no + # MAC with each other) settle at 0 for this epoch, escrowed like a review + # hold. The miners they bridged stay separate and are paid normally. + if identity_conflicts: + _held = set(_held) | set(identity_conflicts) + if record_escrow: + _cw = _get_epoch_enrolled_weights(conn, epoch) + for _m in sorted(identity_conflicts): + _units = int(_cw.get(_m, 0.0)) + if _units > 0: + sybil_guard.record_review_escrow_safe( + conn, epoch, _m, _units, "adm_identity_bridge_conflict") # Select representative miner for each machine representative_map: Dict[str, str] = {} # machine_identity -> representative_miner_id @@ -840,7 +1012,7 @@ def _calculate_anti_double_mining_rewards_conn( for identity_hash, miner_ids in miner_groups.items(): if len(miner_ids) > 1: - rep = select_representative_miner(conn, miner_ids, epoch=epoch) + rep = select_representative_miner(conn, miner_ids, epoch=epoch, held=_held) representative_map[identity_hash] = rep for mid in miner_ids: if mid != rep: @@ -868,7 +1040,9 @@ def _calculate_anti_double_mining_rewards_conn( total_weight = 0.0 for miner_id, device_arch, fingerprint_ok, identity_hash in machine_data: - if fingerprint_ok == 0: + if miner_id in _held: + weight = 0.0 # SYBIL-GUARD review hold (escrowed above) + elif fingerprint_ok == 0: weight = 0.0 elif miner_id in enrolled_weights: # Preserve the canonical per-epoch weight snapshot used by the @@ -877,7 +1051,8 @@ def _calculate_anti_double_mining_rewards_conn( # filtered weights. weight = enrolled_weights[miner_id] else: - weight = get_time_aged_multiplier(device_arch, chain_age_years) + weight = _safe_weight(get_time_aged_multiplier(device_arch, chain_age_years), + miner_id, "arch multiplier") if weight > 0 and fingerprint_ok == 1: try: @@ -885,15 +1060,16 @@ def _calculate_anti_double_mining_rewards_conn( "SELECT warthog_bonus FROM miner_attest_recent WHERE miner=?", (miner_id,) ).fetchone() - # Apply capped warthog bonus (MAX = 2.0) to prevent reward inflation - if wart_row and wart_row[0]: - bonus = float(wart_row[0]) - if 1.0 < bonus <= 2.0: - weight *= bonus - elif bonus > 2.0: - weight *= 2.0 + # Apply capped warthog bonus (MAX = 2.0) to prevent reward inflation. + # Non-finite / malformed values are treated as 0 (no bonus). + bonus = _safe_weight(wart_row[0], miner_id, "warthog_bonus") if wart_row else 0.0 + if 1.0 < bonus <= 2.0: + weight *= bonus + elif bonus > 2.0: + weight *= 2.0 except Exception: pass + weight = _safe_weight(weight, miner_id, "settlement weight") weighted_machines.append((miner_id, weight)) total_weight += weight @@ -1097,7 +1273,37 @@ def setup_test_scenario(db_path: str): INSERT INTO miner_fingerprint_history (miner, ts, profile_json) VALUES (?, ?, ?) """, (miner, current_ts, fingerprint_c)) - + + # Machine identity evidence. ADM groups miners as one machine only when + # they share a MAC hash seen in the epoch window AND the same + # node-observed source_ip AND the same arch; the fingerprint profiles + # above are not an identity signal. + conn.execute("ALTER TABLE miner_attest_recent ADD COLUMN source_ip TEXT") + conn.execute(""" + CREATE TABLE miner_macs ( + miner TEXT NOT NULL, + mac_hash TEXT NOT NULL, + first_ts INTEGER NOT NULL, + last_ts INTEGER NOT NULL, + count INTEGER DEFAULT 1, + PRIMARY KEY (miner, mac_hash) + ) + """) + evidence = { + "miner-a1": ("192.0.2.10", "mac-machine-a"), + "miner-a2": ("192.0.2.10", "mac-machine-a"), + "miner-a3": ("192.0.2.10", "mac-machine-a"), + "miner-b1": ("192.0.2.20", "mac-machine-b"), + "miner-c1": ("192.0.2.30", "mac-machine-c"), + "miner-c2": ("192.0.2.30", "mac-machine-c"), + } + for miner, (ip, mac) in evidence.items(): + conn.execute("UPDATE miner_attest_recent SET source_ip = ? WHERE miner = ?", (ip, miner)) + conn.execute( + "INSERT INTO miner_macs VALUES (?, ?, ?, ?, 1)", + (miner, mac, epoch_start_ts + 60, epoch_start_ts + 60), + ) + conn.commit() print(f"Test database created at {db_path}") diff --git a/node/beacon_api.py b/node/beacon_api.py index 07fe7c91f..9a09671ec 100644 --- a/node/beacon_api.py +++ b/node/beacon_api.py @@ -27,6 +27,9 @@ DB_PATH = 'rustchain_v2.db' BEACON_AUTH_WINDOW_SECONDS = 300 +# Signed timestamps may run slightly ahead of server time (clock skew), but not +# far: a far-future timestamp would outlive its nonce record and be replayable. +BEACON_AUTH_MAX_FUTURE_SECONDS = 30 BOTTUBE_AVATAR_BASE_URL = 'https://bottube.ai/avatar/' BOTTUBE_AVATAR_MAX_BYTES = 1024 * 1024 BOTTUBE_AVATAR_FILENAME = re.compile( @@ -297,7 +300,8 @@ def _authenticate_contract_agent(db, allowed_agents, body_bytes): return None, (jsonify({'error': 'Invalid X-Agent-Timestamp'}), 400) now = int(time.time()) - if abs(now - timestamp) > BEACON_AUTH_WINDOW_SECONDS: + if (timestamp < now - BEACON_AUTH_WINDOW_SECONDS + or timestamp > now + BEACON_AUTH_MAX_FUTURE_SECONDS): return None, (jsonify({'error': 'Stale Beacon signature timestamp'}), 401) if not isinstance(nonce, str) or not nonce.strip() or len(nonce) > 128: @@ -317,9 +321,11 @@ def _authenticate_contract_agent(db, allowed_agents, body_bytes): cutoff = now - BEACON_AUTH_WINDOW_SECONDS db.execute("DELETE FROM beacon_agent_nonces WHERE created_at < ?", (cutoff,)) try: + # Keep the nonce until its signature can no longer pass the timestamp + # check: record the later of now and the signed timestamp. db.execute( "INSERT INTO beacon_agent_nonces (agent_id, nonce, created_at) VALUES (?, ?, ?)", - (agent_id, nonce, now) + (agent_id, nonce, max(now, timestamp)) ) db.commit() except sqlite3.IntegrityError: diff --git a/node/bridge_reconciliation.py b/node/bridge_reconciliation.py index 3f10dc223..146b6748b 100644 --- a/node/bridge_reconciliation.py +++ b/node/bridge_reconciliation.py @@ -116,12 +116,11 @@ def compute_state_hash(state: Dict[str, Any]) -> str: def _bridged_supply_committed(state: Dict[str, Any]) -> float: """Per FEDERATION_BRIDGED_SUPPLY_SPEC.md section 3: - bridged_supply_committed = locked_in + completed_in - voided_in + bridged_supply_committed = locked_in + completed_in """ return ( float(state.get("locked_in_rtc", 0.0)) + float(state.get("completed_in_rtc", 0.0)) - - float(state.get("voided_in_rtc", 0.0)) ) diff --git a/node/ergo_miner_anchor.py b/node/ergo_miner_anchor.py index bddfef6f0..647aa552e 100644 --- a/node/ergo_miner_anchor.py +++ b/node/ergo_miner_anchor.py @@ -1,48 +1,169 @@ #!/usr/bin/env python3 -"""Ergo Miner Anchor - Zero-fee anchor TX with miner commitments in registers.""" +""" +Ergo Miner Anchor - Zero-fee anchor TX with miner + beacon commitments in registers. + +Updated to include beacon envelope digest in the R4 commitment. +Combined commitment: blake2b(miner_commitment + "|" + beacon_digest) + +Security: Post-broadcast TX verification prevents fake anchor records. +""" import os, json, sqlite3, time, requests from hashlib import blake2b ERGO_NODE = os.environ.get("ERGO_NODE", "http://localhost:9053") -ERGO_API_KEY = os.environ.get("ERGO_API_KEY", "") -ERGO_WALLET_PASSWORD = os.environ.get("ERGO_WALLET_PASSWORD", "") + +ENV_FILE = os.environ.get("RUSTCHAIN_ENV_FILE", "/root/rustchain/.env") + + +def _from_env_file(name, path=None): + """Fallback: read NAME from the node's .env when not exported (cron does not source it).""" + try: + for line in open(path or ENV_FILE): + if line.startswith(name + "="): + return line.split("=", 1)[1].strip().strip('"').strip("'") + except OSError: + pass + return "" + + +def _ergo_key_from_env_file(path=None): + return _from_env_file("ERGO_API_KEY", path) + + +ERGO_API_KEY = os.environ.get("ERGO_API_KEY") or _ergo_key_from_env_file() +# Wallet unlock password: env or .env only. Never a hard-coded default in source. +ERGO_WALLET_PASS = os.environ.get("ERGO_WALLET_PASS") or _from_env_file("ERGO_WALLET_PASS") DB_PATH = "/root/rustchain/rustchain_v2.db" ANCHOR_VALUE = 1000000 # 0.001 ERG min box size +# Verification settings +VERIFY_POLL_INTERVAL = 10 # seconds between verification polls +VERIFY_MAX_WAIT = 120 # max seconds to wait for TX to appear +VERIFY_CONFIRM_DEPTH = 1 # min confirmations to mark as confirmed + +# Import beacon anchor functions +from beacon_anchor import compute_beacon_digest, mark_anchored, init_beacon_table + + +def verify_ergo_tx(session, tx_id): + """ + Verify a transaction exists on the Ergo blockchain. + + Uses /wallet/transactionById (works on private chains without extra indexing) + and falls back to mempool check. + Returns (exists: bool, confirmed: bool, error: str|None). + """ + if not tx_id or not isinstance(tx_id, str) or len(tx_id) < 32: + return False, False, "invalid_tx_id" + + # Check via wallet API (works on private chains, returns numConfirmations) + try: + resp = session.get( + ERGO_NODE + f"/wallet/transactionById?id={tx_id}", + timeout=10 + ) + if resp.status_code == 200: + tx_data = resp.json() + # Verify it has outputs (not a stub/empty response) + if tx_data.get("outputs") and len(tx_data["outputs"]) > 0: + num_confs = tx_data.get("numConfirmations", 0) + confirmed = num_confs >= VERIFY_CONFIRM_DEPTH + return True, confirmed, None + except Exception as e: + pass # Fall through to mempool check + + # Check unconfirmed/mempool + try: + resp = session.get( + ERGO_NODE + "/transactions/unconfirmed", + timeout=10 + ) + if resp.status_code == 200: + mempool = resp.json() + for tx in mempool: + if tx.get("id") == tx_id: + return True, False, None + except Exception as e: + return False, False, f"mempool_check_error: {e}" + + return False, False, "tx_not_found" + + +def verify_anchor_commitment(session, tx_id, expected_commitment): + """ + Verify that a confirmed Ergo TX contains the expected commitment in R4. + + This prevents an attacker from submitting a valid but unrelated tx_id + and claiming it anchors our data. + + Uses /wallet/transactionById (works on private chains without extra indexing). + Returns (valid: bool, error: str|None). + """ + if not tx_id or not expected_commitment: + return False, "missing_tx_id_or_commitment" + + try: + resp = session.get( + ERGO_NODE + f"/wallet/transactionById?id={tx_id}", + timeout=10 + ) + if resp.status_code != 200: + return False, f"tx_fetch_failed: HTTP {resp.status_code}" + + tx_data = resp.json() + for output in tx_data.get("outputs", []): + registers = output.get("additionalRegisters", {}) + r4 = registers.get("R4", {}) + # R4 can be a string (raw hex) or dict with serializedValue + r4_hex = r4 if isinstance(r4, str) else r4.get("serializedValue", "") + + # Our encoding: "0e20" + 32-byte hex commitment + # 0e = Coll[Byte], 20 = VLQ(32) + expected_r4 = "0e20" + expected_commitment + if r4_hex == expected_r4: + return True, None + + return False, "commitment_not_found_in_tx_outputs" + except Exception as e: + return False, f"verification_error: {e}" + + class ErgoMinerAnchor: def __init__(self): self.session = requests.Session() - if ERGO_API_KEY: - self.session.headers["api_key"] = ERGO_API_KEY + self.session.headers["api_key"] = ERGO_API_KEY self.session.headers["Content-Type"] = "application/json" - + def unlock_wallet(self, password=None): - """Unlock wallet if needed.""" - status_resp = self.session.get(ERGO_NODE + "/wallet/status") - if status_resp.status_code != 200: - return False - status = status_resp.json() + """Unlock wallet if needed. The password comes from ERGO_WALLET_PASS + (environment or .env); there is deliberately no default in source.""" + password = password or ERGO_WALLET_PASS + status = self.session.get(ERGO_NODE + "/wallet/status").json() if not status.get("isUnlocked"): - pwd = password if password is not None else ERGO_WALLET_PASSWORD - if not pwd: - return False - unlock_resp = self.session.post(ERGO_NODE + "/wallet/unlock", json={"pass": pwd}) - return unlock_resp.status_code == 200 - return True - + if not password: + print(" WARNING: wallet locked and ERGO_WALLET_PASS not set; signing will fail") + return + self.session.post(ERGO_NODE + "/wallet/unlock", json={"pass": password}) + def get_recent_miners(self, limit=10): conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row cur = conn.cursor() cur.execute("SELECT miner, device_arch, ts_ok FROM miner_attest_recent ORDER BY ts_ok DESC LIMIT ?", (limit,)) - miners = [dict(row) for row in cur.fetchall()] + miners = [dict(row) for row in cur.fetchall()] # fetchall-ok: already-paginated (LIMIT ?) conn.close() return miners - + + @staticmethod + def canonical_miner_data(miners): + """Exact preimage of the miner commitment. Stored in ergo_anchors.miner_data + so a third party can recompute and check every anchor.""" + return json.dumps(miners, sort_keys=True) + def compute_commitment(self, miners): - data = json.dumps(miners, sort_keys=True).encode() + data = self.canonical_miner_data(miners).encode() return blake2b(data, digest_size=32).hexdigest() - + def get_rc_slot(self): conn = sqlite3.connect(DB_PATH) cur = conn.cursor() @@ -50,17 +171,137 @@ def get_rc_slot(self): row = cur.fetchone() conn.close() return row[0] if row and row[0] else 0 - + + def compute_combined_commitment(self, miner_commitment, beacon_info): + """ + Combine miner commitment with beacon digest. + If no beacon envelopes pending, use miner commitment alone. + """ + beacon_digest = beacon_info.get("digest") + if beacon_digest: + combined = f"{miner_commitment}|{beacon_digest}".encode() + return blake2b(combined, digest_size=32).hexdigest() + else: + return miner_commitment + + def _wait_for_tx(self, tx_id, commitment, max_wait=VERIFY_MAX_WAIT): + """ + Wait for a broadcast TX to appear on the Ergo node (mempool or confirmed). + + Returns (verified: bool, confirmed: bool, error: str|None). + """ + start = time.time() + last_error = None + + while time.time() - start < max_wait: + exists, confirmed, err = verify_ergo_tx(self.session, tx_id) + if exists: + print(f" TX verified on Ergo ({'confirmed' if confirmed else 'in mempool'})") + + # If confirmed, also verify the commitment matches R4 + if confirmed: + valid, verr = verify_anchor_commitment( + self.session, tx_id, commitment + ) + if not valid: + print(f" WARNING: TX exists but commitment mismatch: {verr}") + return False, False, f"commitment_mismatch: {verr}" + + return True, confirmed, None + + last_error = err + time.sleep(VERIFY_POLL_INTERVAL) + + return False, False, f"tx_not_found_after_{max_wait}s: {last_error}" + + def verify_past_anchors(self): + """ + Verify all anchors with status='local' or status='pending'. + Updates status to 'confirmed' or 'failed' based on Ergo node state. + + This catches records from previous runs that were stored before + verification could complete. + """ + conn = sqlite3.connect(DB_PATH) + conn.row_factory = sqlite3.Row + cur = conn.cursor() + + # Add status column if missing (old schema had no status) + try: + cur.execute("ALTER TABLE ergo_anchors ADD COLUMN status TEXT DEFAULT 'local'") + conn.commit() + except sqlite3.OperationalError: + pass + + cur.execute( + "SELECT id, tx_id, commitment, status, created_at FROM ergo_anchors " + "WHERE status IN ('local', 'pending') ORDER BY id ASC LIMIT 200" + ) + # Oldest first, at most 200 per run; any remainder is picked up next run. + rows = cur.fetchall() # fetchall-ok: already-paginated (LIMIT 200) + conn.close() + + if not rows: + return + + print(f"\n=== Verifying {len(rows)} unconfirmed anchor(s) ===") + for row in rows: + anchor_id = row["id"] + tx_id = row["tx_id"] + commitment = row["commitment"] + old_status = row["status"] + created_at = row["created_at"] or 0 + + # Skip rows with missing tx_id or commitment + if not tx_id or not commitment: + print(f" Anchor #{anchor_id}: SKIPPED - missing tx_id or commitment") + continue + + exists, confirmed, err = verify_ergo_tx(self.session, tx_id) + + if confirmed: + # Double-check commitment in R4 + valid, verr = verify_anchor_commitment( + self.session, tx_id, commitment + ) + if valid: + new_status = "confirmed" + print(f" Anchor #{anchor_id} ({tx_id[:16]}...): CONFIRMED on-chain") + else: + new_status = "commitment_mismatch" + print(f" Anchor #{anchor_id} ({tx_id[:16]}...): TX exists but commitment MISMATCH - {verr}") + elif exists: + new_status = "pending" # In mempool, not yet confirmed + print(f" Anchor #{anchor_id} ({tx_id[:16]}...): in mempool (pending)") + else: + # TX not found -- could be dropped from mempool or never broadcast + # Only mark as failed if old enough (>1 hour) + age = int(time.time()) - created_at if created_at else 0 + if age > 3600: + new_status = "failed" + print(f" Anchor #{anchor_id} ({tx_id[:16]}...): FAILED - not found after {age}s") + else: + new_status = old_status # Keep current status, too early to call it failed + print(f" Anchor #{anchor_id} ({tx_id[:16]}...): not yet found (age={age}s, keeping '{old_status}')") + + if new_status != old_status: + conn2 = sqlite3.connect(DB_PATH) + conn2.execute( + "UPDATE ergo_anchors SET status = ? WHERE id = ?", + (new_status, anchor_id) + ) + conn2.commit() + conn2.close() + def create_anchor_tx(self, miners): - """Create zero-fee anchor TX with miner data in registers.""" - if not ERGO_API_KEY: - return {"success": False, "error": "ERGO_API_KEY not configured"} - if not self.unlock_wallet(): - return {"success": False, "error": "Wallet locked or unlock failed"} - - commitment = self.compute_commitment(miners) + """Create zero-fee anchor TX with miner + beacon data in registers.""" + self.unlock_wallet() + + miner_commitment = self.compute_commitment(miners) + beacon_info = compute_beacon_digest(DB_PATH) + commitment = self.compute_combined_commitment(miner_commitment, beacon_info) rc_slot = self.get_rc_slot() - + # Get UTXO boxes = self.session.get(ERGO_NODE + "/wallet/boxes/unspent?minConfirmations=1").json() input_box = None @@ -69,22 +310,29 @@ def create_anchor_tx(self, miners): if box.get("value", 0) >= 2 * ANCHOR_VALUE: input_box = box break - + if not input_box: return {"success": False, "error": "No UTXO"} - + box_bytes = self.session.get(ERGO_NODE + "/utxo/byIdBinary/" + input_box["boxId"]).json().get("bytes") height = self.session.get(ERGO_NODE + "/info").json().get("fullHeight", 0) - + input_val = input_box["value"] change_val = input_val - ANCHOR_VALUE # Zero fee - + + beacon_count = beacon_info["count"] + beacon_digest = beacon_info.get("digest", "") + print("Creating anchor TX:") - print(" Commitment:", commitment[:32] + "...") + print(" Miner commitment:", miner_commitment[:32] + "...") + if beacon_count > 0: + print(" Beacon digest: ", beacon_digest[:32] + "...") + print(" Beacon envelopes:", beacon_count) + print(" Combined commit: ", commitment[:32] + "...") print(" Miners:", len(miners)) print(" RC Slot:", rc_slot) print(" Input:", input_val / 1e9, "ERG") - + unsigned_tx = { "inputs": [{"boxId": input_box["boxId"], "extension": {}}], "dataInputs": [], @@ -95,7 +343,7 @@ def create_anchor_tx(self, miners): "creationHeight": height, "assets": [], "additionalRegisters": { - "R4": "0e20" + commitment # 32-byte commitment + "R4": "0e20" + commitment # 32-byte combined commitment } }, { @@ -107,50 +355,114 @@ def create_anchor_tx(self, miners): } ] } - + # Sign sign_resp = self.session.post(ERGO_NODE + "/wallet/transaction/sign", json={"tx": unsigned_tx, "inputsRaw": [box_bytes], "dataInputsRaw": []}) - + if sign_resp.status_code != 200: return {"success": False, "error": "Sign failed: " + sign_resp.text[:100]} - + signed = sign_resp.json() - + # Broadcast send_resp = self.session.post(ERGO_NODE + "/transactions", json=signed) - + if send_resp.status_code == 200: tx_id = send_resp.json() - print(" SUCCESS! TX:", tx_id) - - # Save to DB + print(" Broadcast OK. TX:", tx_id) + + # --- SECURITY FIX: Verify TX exists on Ergo before storing --- + print(" Verifying TX on Ergo node...") + verified, confirmed, verr = self._wait_for_tx(tx_id, commitment) + + if not verified: + print(f" VERIFICATION FAILED: {verr}") + print(" Anchor record NOT stored. TX may have been dropped.") + return { + "success": False, + "error": f"tx_verification_failed: {verr}", + "tx_id": str(tx_id) + } + + status = "confirmed" if confirmed else "pending" + # --- END SECURITY FIX --- + + # Save to DB with beacon fields and verified status conn = sqlite3.connect(DB_PATH) cur = conn.cursor() - cur.execute("""CREATE TABLE IF NOT EXISTS ergo_anchors ( - id INTEGER PRIMARY KEY, tx_id TEXT, commitment TEXT, - miner_count INTEGER, rc_slot INTEGER, created_at INTEGER)""") - cur.execute("INSERT INTO ergo_anchors (tx_id, commitment, miner_count, rc_slot, created_at) VALUES (?, ?, ?, ?, ?)", - (str(tx_id), commitment, len(miners), rc_slot, int(time.time()))) + # Ensure table has beacon columns (additive migration) + try: + cur.execute("ALTER TABLE ergo_anchors ADD COLUMN beacon_count INTEGER DEFAULT 0") + except sqlite3.OperationalError: + pass # Column already exists + try: + cur.execute("ALTER TABLE ergo_anchors ADD COLUMN beacon_digest TEXT DEFAULT ''") + except sqlite3.OperationalError: + pass # Column already exists + + try: + cur.execute("ALTER TABLE ergo_anchors ADD COLUMN miner_data TEXT") + except sqlite3.OperationalError: + pass # Column already exists + + # miner_data = the commitment preimage. Without it nobody can recompute + # a historical commitment (miner_attest_recent is overwritten + # continuously), so the anchor proves nothing to an outside auditor. + # Recompute: blake2b(miner_data) = miner commitment; if beacon_digest is + # set, blake2b(miner_commitment + "|" + beacon_digest) = commitment. + cur.execute( + "INSERT INTO ergo_anchors (tx_id, commitment, miner_count, miner_data, rc_slot, created_at, beacon_count, beacon_digest, status) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + (str(tx_id), commitment, len(miners), self.canonical_miner_data(miners), rc_slot, int(time.time()), + beacon_count, beacon_digest, status) + ) conn.commit() conn.close() - - return {"success": True, "tx_id": tx_id, "commitment": commitment} + + # Mark beacon envelopes as anchored + if beacon_info["ids"]: + mark_anchored(beacon_info["ids"], DB_PATH) + print(f" Marked {len(beacon_info['ids'])} beacon envelopes as anchored") + + return { + "success": True, + "tx_id": tx_id, + "commitment": commitment, + "miner_commitment": miner_commitment, + "beacon_count": beacon_count, + "beacon_digest": beacon_digest, + "status": status, + "verified": True + } else: return {"success": False, "error": send_resp.text[:150]} - + def anchor_miners(self): miners = self.get_recent_miners(10) if not miners: return {"success": False, "error": "No miners"} - + print("\n=== Anchoring", len(miners), "miners to Ergo ===") for m in miners: print(" -", m.get("miner", "?")[:20] + ":", m.get("device_arch", "?")) - + + beacon_info = compute_beacon_digest(DB_PATH) + if beacon_info["count"] > 0: + print(f" + {beacon_info['count']} beacon envelopes pending") + return self.create_anchor_tx(miners) + if __name__ == "__main__": + # Ensure beacon table exists + init_beacon_table(DB_PATH) + anchor = ErgoMinerAnchor() + + # First: verify any past unconfirmed anchors + anchor.verify_past_anchors() + + # Then: create new anchor result = anchor.anchor_miners() print("\nResult:", json.dumps(result, indent=2)) diff --git a/node/ergo_raw_tx.py b/node/ergo_raw_tx.py index 731c4149c..762dafb90 100644 --- a/node/ergo_raw_tx.py +++ b/node/ergo_raw_tx.py @@ -8,7 +8,18 @@ import requests ERGO_NODE = "http://localhost:9053" -ERGO_API_KEY = os.environ.get("ERGO_API_KEY", "") +def _ergo_key_from_env_file(path=None): + """Fallback: read ERGO_API_KEY from the node's .env when not exported (cron does not source it).""" + try: + for line in open(path or os.environ.get("RUSTCHAIN_ENV_FILE", "/root/rustchain/.env")): + if line.startswith("ERGO_API_KEY="): + return line.split("=", 1)[1].strip().strip('"').strip("'") + except OSError: + pass + return "" + + +ERGO_API_KEY = os.environ.get("ERGO_API_KEY") or _ergo_key_from_env_file() DB_PATH = "/root/rustchain/rustchain_v2.db" REQUEST_TIMEOUT = 30 diff --git a/node/hardware_binding_v2.py b/node/hardware_binding_v2.py index e03e891e1..61187aa63 100755 --- a/node/hardware_binding_v2.py +++ b/node/hardware_binding_v2.py @@ -171,13 +171,17 @@ def compare_entropy_profiles(stored: Dict, current: Dict) -> Tuple[bool, float, else: return True, similarity, 'entropy_ok' -def check_entropy_collision(entropy_profile: Dict, exclude_serial: str = None) -> Optional[str]: +def check_entropy_collision(entropy_profile: Dict, exclude_serial: str = None, + conn: Optional[sqlite3.Connection] = None) -> Optional[str]: """ Check if this entropy profile matches any OTHER serial. This detects serial spoofing (same hardware, different serial). Requires at least MIN_COMPARABLE_FIELDS non-zero comparable fields for collision checks. Sparse profiles are considered low-quality and are ignored for collision matching. + + Pass ``conn`` to run the scan inside the caller's write transaction. + bind_hardware_v2 does this so the scan and the INSERT are atomic. """ # Count non-zero fields in current profile nonzero_fields = _count_nonzero_fields(entropy_profile) @@ -186,32 +190,35 @@ def check_entropy_collision(entropy_profile: Dict, exclude_serial: str = None) - # Not enough entropy data to detect collisions reliably return None - with sqlite3.connect(DB_PATH) as conn: - c = conn.cursor() - c.execute('SELECT serial_hash, entropy_profile FROM hardware_bindings_v2') + if conn is None: + with sqlite3.connect(DB_PATH) as own_conn: + return check_entropy_collision(entropy_profile, exclude_serial, conn=own_conn) + + c = conn.cursor() + c.execute('SELECT serial_hash, entropy_profile FROM hardware_bindings_v2') + + for row in c.fetchall(): + serial_hash, stored_json = row + if serial_hash == exclude_serial: + continue - for row in c.fetchall(): - serial_hash, stored_json = row - if serial_hash == exclude_serial: + if stored_json: + stored = json.loads(stored_json) + # Also require stored profile to have enough data + stored_nonzero = _count_nonzero_fields(stored) + if stored_nonzero < MIN_COMPARABLE_FIELDS: continue - if stored_json: - stored = json.loads(stored_json) - # Also require stored profile to have enough data - stored_nonzero = _count_nonzero_fields(stored) - if stored_nonzero < MIN_COMPARABLE_FIELDS: - continue - - comparable_nonzero = _count_comparable_nonzero_fields(stored, entropy_profile) - if comparable_nonzero < MIN_COMPARABLE_FIELDS: - # Sparse overlap is too weak for collision decisions. - continue + comparable_nonzero = _count_comparable_nonzero_fields(stored, entropy_profile) + if comparable_nonzero < MIN_COMPARABLE_FIELDS: + # Sparse overlap is too weak for collision decisions. + continue - is_similar, score, _ = compare_entropy_profiles(stored, entropy_profile) - - # Require stronger confidence on sufficiently rich, comparable profiles. - if is_similar and score > 0.97: - return serial_hash # Collision detected! + is_similar, score, _ = compare_entropy_profiles(stored, entropy_profile) + + # Require stronger confidence on sufficiently rich, comparable profiles. + if is_similar and score > 0.97: + return serial_hash # Collision detected! return None @@ -233,7 +240,14 @@ def bind_hardware_v2( macs_str = ','.join(sorted(macs)) if macs else '' now = int(time.time()) - with sqlite3.connect(DB_PATH) as conn: + with sqlite3.connect(DB_PATH, timeout=30) as conn: + # SECURITY (#71, Ondrej Nad): take the write lock BEFORE reading, and run + # the collision scan on this same connection. Previously the scan used a + # separate connection outside any transaction, so two concurrent + # first-time registrations of the same physical machine under different + # serials could both see "no collision" and both INSERT (distinct + # serial_hash keys), bypassing the cross-serial spoof guard. + conn.execute('BEGIN IMMEDIATE') c = conn.cursor() # Check existing binding @@ -253,7 +267,7 @@ def bind_hardware_v2( } # NEW HARDWARE - Check for entropy collision first - collision = check_entropy_collision(entropy_profile) + collision = check_entropy_collision(entropy_profile, conn=conn) if collision: return False, 'entropy_collision', { 'error': 'This hardware entropy matches an existing registration', diff --git a/node/rewards_implementation_rip200.py b/node/rewards_implementation_rip200.py index 9b90c6bbd..5cb8fa320 100644 --- a/node/rewards_implementation_rip200.py +++ b/node/rewards_implementation_rip200.py @@ -61,6 +61,12 @@ def jsonify(obj): ) RIP200_AVAILABLE = True +# SYBIL-GUARD: review-hold escrow on the standard settlement path. Hard import. +try: + import sybil_guard +except ImportError: + from node import sybil_guard + # Import Issue #1449: Anti-Double-Mining (optional - falls back to standard rewards) try: from anti_double_mining import ( @@ -135,6 +141,89 @@ def slot_to_epoch(slot): """Convert slot to epoch (144 blocks per epoch)""" return slot // 144 +# --- UTXO dual-write support (off unless UTXO_DUAL_WRITE=1) ----------------- +# finalize_epoch() mints UTXO reward boxes under dual-write, but production +# settles through THIS function (cron -> POST /rewards/settle -> settle_epoch), +# which minted nothing: accounts grew every epoch while the UTXO side stood +# still, so the two models diverged by the whole epoch pot per epoch. +UTXO_DUAL_WRITE = os.environ.get("UTXO_DUAL_WRITE", "0") == "1" +try: + from utxo_db import UtxoDB as _UtxoDB, DUST_THRESHOLD as _UTXO_DUST, MAX_OUTPUTS as _UTXO_MAX_OUTPUTS + HAVE_UTXO = True +except ImportError: + _UtxoDB = None + _UTXO_DUST = 1_000 + _UTXO_MAX_OUTPUTS = 100 + HAVE_UTXO = False + +NRTC_PER_ACCOUNT_UNIT = 100 # balances.amount_i64 is uRTC (6dp); boxes are nRTC (8dp) +EPOCH_SLOTS_FOR_MINT = 144 + + +def _dual_write_mint_rewards(db, epoch, db_path): + """Mint one UTXO reward box per credited miner and register it as an + account mirror, inside the caller's open transaction. + + Amounts come from epoch_rewards, which BOTH settlement paths write (the + standard path and the anti-double-mining path, which returns early), so the + mint cannot miss the branch production actually takes. + + Value is derived from the credited uRTC amount (x100), never re-truncated, + so each box equals its account credit exactly (#2819). Mirrors are + registered so the same reward is not also spendable through the UTXO path. + Raises on failure: the caller rolls back and the epoch stays unsettled. + """ + if not (UTXO_DUAL_WRITE and HAVE_UTXO): + return {"minted_boxes": 0, "skipped_dust_nrtc": 0} + rewards = { + row[0]: int(row[1]) + for row in db.execute( + "SELECT miner_id, share_i64 FROM epoch_rewards WHERE epoch = ?", (epoch,) + ).fetchall() # fetchall-ok: bounded-by-schema (one row per settled miner) + } + if not rewards: + return {"minted_boxes": 0, "skipped_dust_nrtc": 0} + outputs, skipped = [], 0 + for miner_id, share_urtc in rewards.items(): + value_nrtc = int(share_urtc) * NRTC_PER_ACCOUNT_UNIT + if value_nrtc >= _UTXO_DUST: + outputs.append({"address": miner_id, "value_nrtc": value_nrtc}) + else: + skipped += max(0, value_nrtc) + if not outputs: + return {"minted_boxes": 0, "skipped_dust_nrtc": skipped} + + batches = [outputs[i:i + _UTXO_MAX_OUTPUTS] for i in range(0, len(outputs), _UTXO_MAX_OUTPUTS)] + if len(batches) > EPOCH_SLOTS_FOR_MINT: + raise RuntimeError("UTXO reward settlement exceeds epoch mint capacity") + utxo = _UtxoDB(db_path) + minted = 0 + for batch_index, batch in enumerate(batches): + height = epoch * EPOCH_SLOTS_FOR_MINT + batch_index + tx = {"tx_type": "mining_reward", "inputs": [], "outputs": batch, "_allow_minting": True} + if not utxo.apply_transaction(tx, height, conn=db): + raise RuntimeError( + f"UTXO reward settlement failed for batch {batch_index + 1}/{len(batches)}" + ) + # Register exactly this batch's mint outputs as account-mirror provenance. + # Joined on the mining_reward tx: /utxo/transfer boxes use slot heights in + # the same number space, and tagging one of those would lock a user's box. + rows = list(db.execute( + "SELECT b.box_id, b.owner_address, b.value_nrtc FROM utxo_boxes AS b " + "JOIN utxo_transactions AS t ON t.tx_id = b.transaction_id " + "WHERE b.creation_height = ? AND t.tx_type = 'mining_reward'", + (height,), + )) + for box_id, owner, value in rows: + db.execute( + "INSERT OR IGNORE INTO account_mirror_boxes " + "(box_id, account_wallet, value_nrtc, created_epoch) VALUES (?,?,?,?)", + (box_id, owner, value, epoch), + ) + minted += len(rows) + return {"minted_boxes": minted, "skipped_dust_nrtc": skipped} + + def settle_epoch_rip200(db_path, epoch: int, enable_anti_double_mining: bool = True): """ Settle rewards for an epoch using RIP-200 time-aged multipliers @@ -249,7 +338,13 @@ def settle_epoch_rip200(db_path, epoch: int, enable_anti_double_mining: bool = T existing_conn=db, ) # The callee wrote rewards + settled flag on our connection but - # does NOT commit (caller owns the transaction). Commit now. + # does NOT commit (caller owns the transaction). Mirror those + # credits into the UTXO model first (no-op when dual-write is + # off), then commit both together: this branch is the one + # production takes, and it used to return before any mint. + adm_utxo = _dual_write_mint_rewards(db, epoch, _db_path_from(db_path)) + if isinstance(result, dict): + result["utxo_dual_write"] = adm_utxo db.commit() return result except Exception as e: @@ -289,6 +384,17 @@ def settle_epoch_rip200(db_path, epoch: int, enable_anti_double_mining: bool = T b"" # prev_block_hash fallback for standard path ) + # SYBIL-GUARD: calculate_epoch_rewards_time_aged zeroed held miners on + # its read connection; record their would-be weight here, on `db`, + # inside this settlement transaction (never raises). + try: + _enrolled = dict(db.execute( + "SELECT miner_pk, weight FROM epoch_enroll WHERE epoch = ?", (epoch,) + ).fetchall()) # fetchall-ok: bounded-by-schema (one row per enrolled miner) + except sqlite3.Error: + _enrolled = {} + sybil_guard.hold_for_settlement(db, epoch, list(_enrolled), weights=_enrolled) + if not rewards: db.rollback() return {"ok": False, "error": "no_eligible_miners", "epoch": epoch} @@ -335,6 +441,9 @@ def settle_epoch_rip200(db_path, epoch: int, enable_anti_double_mining: bool = T "device_arch": device_arch }) + # Dual-write: mirror each credit as a UTXO reward box (no-op when off). + utxo_result = _dual_write_mint_rewards(db, epoch, _db_path_from(db_path)) + # Mark epoch as settled without replacing the whole row. # INSERT OR REPLACE deletes any existing epoch_state metadata columns # (for example finalized/accepted_blocks/pot) before inserting the @@ -357,7 +466,8 @@ def settle_epoch_rip200(db_path, epoch: int, enable_anti_double_mining: bool = T "distributed_rtc": _epoch_budget / UNIT, "distributed_urtc": _epoch_budget, "miners": miners_data, - "chain_age_years": round(get_chain_age_years(current), 2) + "chain_age_years": round(get_chain_age_years(current), 2), + "utxo_dual_write": utxo_result, } except Exception: # Any failure after BEGIN IMMEDIATE should release the lock and avoid partial writes. diff --git a/node/rip_200_round_robin_1cpu1vote.py b/node/rip_200_round_robin_1cpu1vote.py index f29192114..62d1aa83d 100644 --- a/node/rip_200_round_robin_1cpu1vote.py +++ b/node/rip_200_round_robin_1cpu1vote.py @@ -15,6 +15,12 @@ import hashlib import json +# SYBIL-GUARD settlement guard. Hard import (round-2 review): a missing module +# must fail loudly, never silently settle held miners. +try: + import sybil_guard as _sybil_guard +except ImportError: + from node import sybil_guard as _sybil_guard import logging import sqlite3 from decimal import Decimal, InvalidOperation, ROUND_HALF_UP @@ -727,6 +733,21 @@ def calculate_epoch_rewards_time_aged( """, (epoch_start_ts - ATTESTATION_TTL, epoch_end_ts)) epoch_miners = cursor.fetchall() + # SYBIL-GUARD: needs_review / incident-cohort miners settle at 0 even + # if flagged after enrollment. Tuple index 3 is enrolled_weight (index + # 2 is fingerprint_passed). Setting it to 0 (not None) keeps the + # arch-multiplier fallback below from re-weighting the miner. Read-only + # here; the caller (settle_epoch_rip200) escrows on its settlement + # transaction, and this separate read connection runs while that + # transaction holds the write lock, so no hold can land in between. + # settlement_held_miners never raises. + _held = _sybil_guard.settlement_held_miners(conn, [m[0] for m in epoch_miners], epoch) + if _held: + epoch_miners = [ + (m[0], m[1], m[2], 0) + tuple(m[4:]) if m[0] in _held else tuple(m) + for m in epoch_miners + ] + if not epoch_miners: return {} diff --git a/node/rustchain_ergo_anchor.py b/node/rustchain_ergo_anchor.py index 5875b97b9..96d4b39b3 100644 --- a/node/rustchain_ergo_anchor.py +++ b/node/rustchain_ergo_anchor.py @@ -355,7 +355,7 @@ def get_last_anchor(self) -> Optional[Dict]: _cols = _anchor_columns(cursor) cursor.execute( - f"SELECT * FROM ergo_anchors ORDER BY {_cols['height']} DESC LIMIT 1" + f"SELECT * FROM ergo_anchors ORDER BY {_cols['height']} DESC, id DESC LIMIT 1" ) row = cursor.fetchone() @@ -368,7 +368,16 @@ def should_anchor(self, current_height: int) -> bool: if not last: return current_height >= self.interval_blocks - blocks_since = current_height - last["rustchain_height"] + # Legacy/prod schema stores the height as rc_slot (see _ANCHOR_COLUMN_ALIASES). + # No `or 0` default: an unreadable height must not silently look like + # "last anchored at height 0" (which would read as "anchor is overdue"). + last_height = last.get("rustchain_height") + if last_height is None: + last_height = last.get("rc_slot") + if last_height is None: + logger.warning("last anchor row has no height column; treating as due") + return True + blocks_since = current_height - last_height return blocks_since >= self.interval_blocks def create_commitment(self, block: Dict) -> AnchorCommitment: @@ -457,7 +466,7 @@ def get_anchor_proof(self, rustchain_height: int) -> Optional[Dict]: _cols = _anchor_columns(cursor) cursor.execute( f"SELECT * FROM ergo_anchors WHERE {_cols['height']} <= ? " - f"ORDER BY {_cols['height']} DESC LIMIT 1", + f"ORDER BY {_cols['height']} DESC, id DESC LIMIT 1", (rustchain_height,), ) @@ -468,7 +477,9 @@ def get_anchor_proof(self, rustchain_height: int) -> Optional[Dict]: anchor = dict(row) # Get Ergo transaction details - tx = self.ergo.get_transaction(anchor["ergo_tx_id"]) + # Legacy/prod schema names the column tx_id (see _ANCHOR_COLUMN_ALIASES). + tx_id = anchor.get("ergo_tx_id") or anchor.get("tx_id") + tx = self.ergo.get_transaction(tx_id) if tx_id else None if tx: anchor["ergo_transaction"] = tx @@ -598,7 +609,7 @@ def list_anchors(): _cols = _anchor_columns(cursor) cursor.execute( - f"SELECT * FROM ergo_anchors ORDER BY {_cols['height']} DESC " + f"SELECT * FROM ergo_anchors ORDER BY {_cols['height']} DESC, id DESC " f"LIMIT ? OFFSET ?", (limit, offset), ) diff --git a/node/rustchain_v2_integrated_v2.2.1_rip200.py b/node/rustchain_v2_integrated_v2.2.1_rip200.py index cfab59e1a..d37bac6d1 100644 --- a/node/rustchain_v2_integrated_v2.2.1_rip200.py +++ b/node/rustchain_v2_integrated_v2.2.1_rip200.py @@ -22,6 +22,14 @@ from db_helpers import fetch_page except ImportError: from node.db_helpers import fetch_page +# SYBIL-GUARD (2026-09-24 incident): new-miner probation. Hard import on +# purpose, like payout_preflight above: if the module is missing the node must +# fail loudly at startup rather than silently re-open the welcome-bonus / +# vintage-weight path the Sybil wave used. +try: + import sybil_guard +except ImportError: + from node import sybil_guard # Hardware Binding v2.0 - Anti-Spoof with Entropy Validation try: @@ -62,6 +70,26 @@ def enforce_hardware_binding_runtime_guard(): APP_START_TS = time.time() # Rewards system +def _native_total_balances(db): + """Sum of all account balances in uRTC (native copy of rewards.total_balances). + + finalize_epoch() uses total_balances() for the RIP-0004 supply-cap headroom. + That is the block-ingest settlement path, so it must not depend on the + optional rewards import below: before #8249 the import named a function the + module does not define, HAVE_REWARDS was False on every worker start, and + any code reaching a bare total_balances() would have raised NameError. + Same SQL and same fail-open-to-0 semantics as the module's version. + """ + try: + row = db.execute("SELECT COALESCE(SUM(amount_i64),0) FROM balances").fetchone() + return int(row[0]) + except Exception: + return 0 + + +# Every name imported here must exist in node/rewards_implementation_rip200.py; +# tests/test_rewards_module_import.py enforces that, so a stale name can never +# again silently flip HAVE_REWARDS to False. try: from rewards_implementation_rip200 import ( settle_epoch_rip200 as settle_epoch, total_balances, UNIT, PER_EPOCH_URTC @@ -70,6 +98,8 @@ def enforce_hardware_binding_runtime_guard(): except Exception as e: print(f"WARN: Rewards module not loaded: {e}") HAVE_REWARDS = False + total_balances = _native_total_balances + settle_epoch = None # /rewards/settle answers 503 instead of NameError # UTXO Layer (Phase 1 — dual-write alongside account model) UTXO_DUAL_WRITE = os.environ.get("UTXO_DUAL_WRITE", "0") == "1" @@ -1452,6 +1482,9 @@ def light_client_static(subpath: str): TOTAL_SUPPLY_URTC = int(TOTAL_SUPPLY_RTC * 1_000_000) # 8,388,608,000,000 uRTC ACCOUNT_UNIT = 1_000_000 # balances.amount_i64 uses micro-RTC. UTXO_UNIT = 100_000_000 # UTXO values use nano-RTC. +# finalize_epoch derives UTXO reward values as amount_i64 * (UTXO_UNIT // ACCOUNT_UNIT); +# that is exact only while the ratio is an integer. +assert UTXO_UNIT % ACCOUNT_UNIT == 0, "UTXO_UNIT must be an integer multiple of ACCOUNT_UNIT" # UNIT is the micro-RTC account unit. Several balance/ledger endpoints reference # bare `UNIT`; it was historically imported from rewards_implementation_rip200, # but that import is best-effort (HAVE_REWARDS) and is skipped when the rewards @@ -2233,6 +2266,12 @@ def init_db(): # legacy payload hashes are versioned consistently across startup paths. init_beacon_table(DB_PATH) + # SYBIL-GUARD: create + verify probation/escrow tables ONCE at startup. + # Request and settlement paths never run DDL. An incompatible existing + # table raises SchemaError here, so the worker fails to boot loudly + # instead of running with a guard that cannot read its own state. + sybil_guard.init_schema(DB_PATH) + # Initialize UTXO tables (Phase 1 — tables created even if dual-write is off) if HAVE_UTXO: try: @@ -3977,12 +4016,71 @@ def _update_account_balance(conn: sqlite3.Connection, miner: str, delta_i64: int ) +def _sync_welcome_bonus_utxo_mirror(conn, miner, bonus_i64, epoch, now): + """Move the welcome bonus on the UTXO side too, not just in the account model. + + Ported verbatim in behaviour from Scottcjn/Rustchain PR #8491 (open, not + merged as of 2026-09-24). The bonus debits WELCOME_BONUS_SOURCE and credits + the miner directly in ``balances``; it is not a pending transfer, so it never + reached ``_settle_account_transfer_in_utxo`` the way /pending/confirm does. + Under dual-write that left the payer's mirrored boxes untouched while its + balance dropped (mirror > balance, the bounty #2819 double-spend condition). + Node1 2026-09-20: founder_community excess == exactly 0.5 RTC; the + 2026-09-24 Sybil wave widened it by ~60 RTC and /pending/confirm has failed + its mirror_exceeds_balance check since. + + Reuses the transfer-confirm reconciler (consumes only mirror boxes, + tolerates a non-migrated payer, asserts mirror <= balance afterwards). The + tx id is derived from (miner, epoch) so a replay reconciles onto the same + boxes. Failure RAISES (round-2 review): _write_welcome_bonus runs this + inside a SAVEPOINT together with the account debit/credit and the ledger + marker, so a mirror failure rolls the whole bonus back and it stays + unpaid and retryable. Swallowing it would commit an account-only credit + and the paid marker, recreating mirror drift permanently. + + Deploy precondition: while founder_community's mirror already exceeds its + balance (~61.5 RTC on node1, 2026-09-24), the reconciler's invariant check + raises mirror_exceeds_balance on EVERY bonus, so graduation bonuses fail + (cleanly, retryably) until an operator repairs that gap. + """ + if not HAVE_UTXO or bonus_i64 <= 0: + return + tx_hash = hashlib.sha256( + f"welcome_bonus:{miner}:{int(epoch)}".encode() + ).hexdigest()[:32] + _settle_account_transfer_in_utxo( + conn, WELCOME_BONUS_SOURCE, miner, int(bonus_i64), int(epoch), tx_hash, int(now) + ) + + def _write_welcome_bonus( conn: sqlite3.Connection, miner: str, bonus_i64: int, ledger_cols: set, balance_cols: set, +): + """Pay the bonus atomically: account debit + credit + ledger marker + UTXO + mirror move all happen inside one SAVEPOINT. Any failure (including the + mirror invariant) rolls back every write of this bonus and re-raises, so + nothing half-applied can be committed by the caller and the bonus stays + retryable (no paid marker is left behind).""" + conn.execute("SAVEPOINT welcome_bonus") + try: + _write_welcome_bonus_unguarded(conn, miner, bonus_i64, ledger_cols, balance_cols) + conn.execute("RELEASE welcome_bonus") + except Exception: + conn.execute("ROLLBACK TO welcome_bonus") + conn.execute("RELEASE welcome_bonus") + raise + + +def _write_welcome_bonus_unguarded( + conn: sqlite3.Connection, + miner: str, + bonus_i64: int, + ledger_cols: set, + balance_cols: set, ): reason = f"welcome_bonus:{WELCOME_BONUS_RTC}_rtc" now = int(time.time()) @@ -4003,6 +4101,7 @@ def _write_welcome_bonus( "INSERT INTO ledger (ts, epoch, miner_id, delta_i64, reason) VALUES (?, ?, ?, ?, ?)", (now, epoch, miner, bonus_i64, reason), ) + _sync_welcome_bonus_utxo_mirror(conn, miner, bonus_i64, epoch, now) return if {"from_miner", "to_miner", "memo"}.issubset(ledger_cols): @@ -4022,6 +4121,7 @@ def _write_welcome_bonus( "INSERT INTO ledger (from_miner, to_miner, amount_i64, memo, ts) VALUES (?, ?, ?, ?, ?)", (WELCOME_BONUS_SOURCE, miner, bonus_i64, reason, now), ) + _sync_welcome_bonus_utxo_mirror(conn, miner, bonus_i64, _welcome_bonus_epoch(), now) return raise RuntimeError("unsupported welcome bonus balance/ledger schema") @@ -4063,43 +4163,72 @@ def _welcome_bonus_source_balance_i64(conn: sqlite3.Connection) -> Optional[int] return int(row[0]) -def _check_welcome_bonus(miner: str): - """Award welcome bonus on first-ever attestation. Funded from founder_community. +def _check_welcome_bonus(miner: str, probation_status: dict = None): + """Award the one-time welcome bonus. Funded from founder_community. + + SYBIL-GUARD: the bonus used to be paid on the very first attestation, which + made "one fabricated POST = 0.5 RTC" the cheapest reward on the chain (the + 2026-09-24 wave took 60 RTC across 120 wallets). Now: - Callers must only invoke this for attestations that PASSED the hardware - fingerprint (see the /attest/submit call site). The payer itself refuses to - drive WELCOME_BONUS_SOURCE negative and takes the write lock up front so two - concurrent first attests cannot both pass the already-paid check. + * new miners are paid when they EXIT probation (state == trusted), which + already enforces the per-/32 admission and per-/24 + global exit caps; + * grandfathered miners keep the legacy first-attestation rule unchanged + (in practice all are long past it, so none are paid); + * a missing/unknown status or a needs_review flag fails closed. + + The paid-check and the write run under one BEGIN IMMEDIATE so two gunicorn + workers cannot both pay the same miner. Returns True iff a bonus was paid. """ + if not isinstance(probation_status, dict): + print(f"[WELCOME] {miner}: no probation status -- bonus withheld (fail closed)") + return False + state = probation_status.get("state") + if state not in (sybil_guard.STATE_TRUSTED, sybil_guard.STATE_GRANDFATHERED): + return False + if sybil_guard.needs_review(probation_status): + return False try: - with closing(sqlite3.connect(DB_PATH)) as conn: + with closing(sqlite3.connect(DB_PATH, timeout=10, isolation_level=None)) as conn: conn.execute("BEGIN IMMEDIATE") - # Check if this miner has ever attested before - history_count = conn.execute( - "SELECT COUNT(*) FROM miner_attest_history WHERE miner = ?", (miner,) - ).fetchone()[0] - - if history_count <= 1: # First attestation (just recorded) + try: + # Round 3: re-authorise under the write lock from the PERSISTED + # probation row + CURRENT cohort membership. A hold or cohort + # insert committed after this attestation's observation (another + # worker, an operator) is seen here. Undeterminable -> withhold + # (retryable), never pay. + _eligible, _pstate, _why = sybil_guard.bonus_eligibility_in_txn(conn, miner) + if not _eligible: + conn.execute("ROLLBACK") + print(f"[WELCOME] {miner}: bonus withheld at payment time ({_why})") + return False + state = _pstate + if state == sybil_guard.STATE_GRANDFATHERED: + history_count = conn.execute( + "SELECT COUNT(*) FROM miner_attest_history WHERE miner = ?", (miner,) + ).fetchone()[0] + if history_count > 1: # legacy rule: first attestation only + conn.execute("ROLLBACK") + return False ledger_cols = _table_columns(conn, "ledger") balance_cols = _table_columns(conn, "balances") - # Check if welcome bonus already paid - already_paid = _welcome_bonus_already_paid(conn, miner, ledger_cols) - - if not already_paid: - bonus_i64 = int(WELCOME_BONUS_RTC * 1_000_000) - source_balance = _welcome_bonus_source_balance_i64(conn) - if source_balance is None or source_balance < bonus_i64: - print(f"[WELCOME] SKIPPED for {miner}: {WELCOME_BONUS_SOURCE} " - f"balance {source_balance} < {bonus_i64} uRTC") - conn.rollback() - return - _write_welcome_bonus(conn, miner, bonus_i64, ledger_cols, balance_cols) - conn.commit() - print(f"[WELCOME] {miner} received {WELCOME_BONUS_RTC} RTC welcome bonus!") - return - conn.rollback() + if _welcome_bonus_already_paid(conn, miner, ledger_cols): + conn.execute("ROLLBACK") + return False + bonus_i64 = int(WELCOME_BONUS_RTC * 1_000_000) + _write_welcome_bonus(conn, miner, bonus_i64, ledger_cols, balance_cols) + conn.execute("COMMIT") + except Exception: + conn.execute("ROLLBACK") + raise + print(f"[WELCOME] {miner} received {WELCOME_BONUS_RTC} RTC welcome bonus (state={state})") + return True except Exception as e: - print(f"[WELCOME] Error for {miner}: {e}") + # Nothing was committed (savepoint + transaction rolled back), so the + # bonus is still unpaid and will be retried on the next attestation. + logging.critical( + "[WELCOME] bonus NOT paid for %s (rolled back, will retry): %s", miner, e) + print(f"[WELCOME] Error for {miner}: {e} -- NOT paid, retryable") + return False def _get_streak_bonus(miner: str) -> float: @@ -4583,8 +4712,12 @@ def verify_measurement_binding(nonce: str, binding, expected_rate_ns=None, try: duration_ns = float(binding.get("duration_ns")) - except (TypeError, ValueError): + except (TypeError, ValueError, OverflowError): return {"state": "malformed", "ok": False, "reason": "duration_not_numeric"} + # SYBIL-GUARD: NaN compares False with everything and inf divides to inf, + # so both used to come back "bound". + if not math.isfinite(duration_ns): + return {"state": "malformed", "ok": False, "reason": "duration_not_finite"} if duration_ns <= 0: return {"state": "malformed", "ok": False, "reason": "duration_not_positive"} @@ -4599,7 +4732,9 @@ def verify_measurement_binding(nonce: str, binding, expected_rate_ns=None, if expected_rate_ns: try: expected = float(expected_rate_ns) - except (TypeError, ValueError): + except (TypeError, ValueError, OverflowError): + expected = 0.0 + if not math.isfinite(expected): expected = 0.0 if expected > 0: ratio = rate_ns / expected @@ -4622,7 +4757,12 @@ def verify_measurement_binding(nonce: str, binding, expected_rate_ns=None, TEMPORAL_UNVERIFIED_BONUS_FRACTION = 0.5 -def apply_temporal_consistency_to_weight(hw_weight: float, temporal_review: dict) -> float: +_NO_PROBATION = object() + + +def apply_temporal_consistency_to_weight( + hw_weight: float, temporal_review: dict, probation_status=_NO_PROBATION, +) -> float: """Gate the ANTIQUITY BONUS on the miner's consistency with its own history. Antiquity multipliers above 1.0 are the only thing worth forging on this @@ -4646,7 +4786,19 @@ def apply_temporal_consistency_to_weight(hw_weight: float, temporal_review: dict reward is for staying consistent, which a farm cannot mass-produce, because each identity must be self-consistent AND independent of the others at the same time. See finding-contributor-tenure-multiplier-rejected. + + SYBIL-GUARD (2026-09-24): the self-history check cannot judge a miner that + HAS no history, and "insufficient_history" still paid half the premium (a + fabricated G4 enrolled at 1.75x on its first POST). When the caller passes + `probation_status`, the temporal-adjusted weight is run through + sybil_guard.enrollment_weight: probation -> capped at PROBATION_WEIGHT_CAP + (1.0, the floor this function already guarantees), needs_review -> 0 (the + caller escrows it), graduated without a bound measurement -> capped, + grandfathered -> unchanged. Omitting the argument keeps the old behaviour. """ + if probation_status is not _NO_PROBATION: + adjusted = apply_temporal_consistency_to_weight(hw_weight, temporal_review) + return sybil_guard.enrollment_weight(adjusted, probation_status) try: weight = float(hw_weight) except (TypeError, ValueError): @@ -5050,6 +5202,13 @@ def get_check_status(check_data): claimed_arch = claimed_arch.lower() # If claiming PowerPC, check for x86-specific signals in fingerprint + if claimed_arch in _X86_VINTAGE_REWARD_ARCHES: + derived = _derive_enroll_weight_device( + {"device_family": "x86", "device_arch": claimed_arch}, fingerprint, fingerprint_passed=True, measurement_report_verified=True + ) + if derived.get("device_arch") != claimed_arch: + return False, f"x86_vintage_corroboration_failed:claims_{claimed_arch}" + if claimed_arch in POWERPC_ARCHES: # FIX #1147: Check for x86 SIMD features on PowerPC claims (defensive type checking) simd_check = checks.get("simd_identity") @@ -5597,6 +5756,23 @@ def finalize_epoch(epoch, per_block_rtc, prev_block_hash: bytes = b""): print(f"[SECURITY] Epoch {epoch} already settled (claim lost) — skipping to prevent double-reward") return + # SYBIL-GUARD settlement guard, read INSIDE this BEGIN IMMEDIATE + # (round-2 review: reading before it let a hold committed in + # between be missed). needs_review / cohort miners settle at 0; + # their would-be weight is escrowed in this same transaction. + # hold_for_settlement never raises, so it cannot halt settlement. + _held = sybil_guard.hold_for_settlement( + conn, epoch, [pk for pk, _ in miners], weights=dict(miners)) + if _held: + miners = [(pk, w) for pk, w in miners if pk not in _held] + total_weight = sum(w for _, w in miners) + print(f"[SYBIL-GUARD] finalize_epoch {epoch}: {len(_held)} needs_review miner(s) held at 0") + if total_weight == 0: + c.execute("ROLLBACK") + print(f"[SYBIL-GUARD] finalize_epoch {epoch}: every miner held -- epoch left unsettled") + _record_unsettled_epoch(c, conn, epoch, "all_miners_held") + return + utxo_reward_outputs = [] skipped_utxo_dust_nrtc = 0 @@ -5621,7 +5797,12 @@ def finalize_epoch(epoch, per_block_rtc, prev_block_hash: bytes = b""): # Use Decimal arithmetic to avoid float precision loss amount_decimal = Decimal(0) if Decimal(total_weight) == 0 else total_reward * Decimal(weight) / Decimal(total_weight) amount_i64 = int(amount_decimal * Decimal(ACCOUNT_UNIT)) - amount_nrtc = int(amount_decimal * Decimal(UTXO_UNIT)) + # Derive the UTXO value FROM the truncated account credit, never by + # truncating amount_decimal a second time at 8 decimals: that made + # the minted box up to 99 nRTC larger than the account credit per + # miner per epoch, so the two models disagreed after every + # settlement with fractional shares (#2819, favoritegrandson-tech). + amount_nrtc = amount_i64 * (UTXO_UNIT // ACCOUNT_UNIT) # OVERFLOW PROTECTION: Ensure stored reward units fit in signed 64-bit int if amount_i64 >= 2**63 or amount_nrtc >= 2**63: @@ -5682,7 +5863,10 @@ def finalize_epoch(epoch, per_block_rtc, prev_block_hash: bytes = b""): "(reward still credited)", pk, epoch, _led_err, ) - if UTXO_DUAL_WRITE: + # Mirror only what the account model actually credited: a miner with + # no balance row gets no account credit (no-phantom invariant above), + # so minting them a UTXO box would create value in one model only. + if UTXO_DUAL_WRITE and updated == 1: if amount_nrtc >= UTXO_DUST_THRESHOLD: utxo_reward_outputs.append({ "address": pk, @@ -5718,14 +5902,42 @@ def finalize_epoch(epoch, per_block_rtc, prev_block_hash: bytes = b""): "outputs": outputs, "_allow_minting": True } + batch_height = epoch * EPOCH_SLOTS + batch_index utxo_ok = UtxoDB(DB_PATH).apply_transaction( - utxo_tx, epoch * EPOCH_SLOTS + batch_index, conn=conn + utxo_tx, batch_height, conn=conn ) if not utxo_ok: raise RuntimeError( "UTXO reward settlement failed for " f"batch {batch_index + 1}/{len(reward_batches)}" ) + # SECURITY(danaher-j / #2819 same class as the /utxo/transfer + # receiver residual): this batch credited each miner's ACCOUNT + # balance (above) AND just minted a UTXO reward box for them. + # Register those boxes as account-mirror provenance, or the same + # reward is spendable via BOTH models (UTXO box + account balance) + # = double spend. Select ONLY this batch's mint outputs: join on + # the mining_reward tx at batch_height. apply_transaction allows + # one mining_reward per height, but ordinary /utxo/transfer boxes + # use current_slot() heights in the same number space, so a + # height-only match could tag a user's own box as a mirror and + # lock it (409). Materialized first (bounded by UTXO_MAX_OUTPUTS) + # because the INSERTs below reuse cursor `c`. Pure INSERTs (table + # is canonical schema now, so no DDL in this settlement txn). + _reward_boxes = list(c.execute( + "SELECT b.box_id, b.owner_address, b.value_nrtc " + "FROM utxo_boxes AS b " + "JOIN utxo_transactions AS t ON t.tx_id = b.transaction_id " + "WHERE b.creation_height = ? AND t.tx_type = 'mining_reward'", + (batch_height,), + )) + for _bid, _owner, _val in _reward_boxes: + c.execute( + "INSERT OR IGNORE INTO account_mirror_boxes " + "(box_id, account_wallet, value_nrtc, created_epoch) " + "VALUES (?,?,?,?)", + (_bid, _owner, _val, epoch), + ) if skipped_utxo_dust_nrtc: print( "[UTXO] Skipped sub-dust epoch reward outputs totaling " @@ -6080,6 +6292,90 @@ def _check_hardware_binding(miner_id: str, device: dict, signals: dict = None, s return False, 'hardware_binding_unavailable', '' +def _sybil_guard_observe(miner, fingerprint, client_ip, fingerprint_passed, + nonce=None, measurement_binding=None): + """SYBIL-GUARD: advance probation for this attestation. NEVER raises. + + Everything that can throw (profile extraction, binding verification, the + probation write) is inside the boundary. Fallback chain on error: + 1. read-only get_probation_status (a grandfathered miner keeps its tier + through a transient lock); + 2. sybil_guard.fallback_status: STATE_UNAVAILABLE plus whether the miner + has pre-cutoff history. Established -> today's weight; new -> probation + cap; unknown -> enrollment is DEFERRED (never a reduced weight written + for an established miner because of an error). + """ + try: + binding_state = verify_measurement_binding(nonce, measurement_binding).get("state") + except Exception as exc: + print(f"[SYBIL-GUARD] binding verify failed for {str(miner)[:20]}: {exc}") + binding_state = "error" + try: + profile = extract_temporal_profile(fingerprint if isinstance(fingerprint, dict) else {}) + with closing(sqlite3.connect(DB_PATH, timeout=10, isolation_level=None)) as pconn: + status = sybil_guard.observe_attestation( + pconn, miner, profile, client_ip, + fingerprint_passed=bool(fingerprint_passed), + binding_state=binding_state, + # RIP-309d (implemented, previously never called): new + # identities from one /24 must look like independent machines. + cluster_check=cluster_independence, + ) + except Exception as exc: + print(f"[SYBIL-GUARD] observe failed for {str(miner)[:20]}: {exc}") + status = None + try: + with closing(sqlite3.connect(DB_PATH, timeout=10)) as rconn: + status = sybil_guard.get_probation_status(rconn, miner) + except Exception as exc2: + print(f"[SYBIL-GUARD] status read failed for {str(miner)[:20]}: {exc2}") + if status is None: + try: + with closing(sqlite3.connect(DB_PATH, timeout=10)) as fconn: + status = sybil_guard.fallback_status(fconn, miner) + except Exception as exc3: + print(f"[SYBIL-GUARD] fallback classification failed for {str(miner)[:20]}: {exc3}") + status = sybil_guard.fallback_status(None, miner) + try: + if status.get("anomalies") or status.get("incident_signature") or status.get("needs_review"): + print(f"[SYBIL-GUARD] {str(miner)[:20]}... anomalies={status.get('anomalies')} " + f"incident_signature={status.get('incident_signature')} " + f"needs_review={status.get('review_reason')} " + f"state={status.get('state')} prefix={sybil_guard.source_prefix(client_ip)}") + if status.get("just_exited"): + print(f"[SYBIL-GUARD] {str(miner)[:20]}... exited probation") + elif sybil_guard.is_in_probation(status): + print(f"[SYBIL-GUARD] {str(miner)[:20]}... state={status.get('state')} " + f"blockers={list(status.get('blockers') or [])[:3]}") + except Exception: + pass + return status + + +class _EnrollmentDeferred(Exception): + """SYBIL-GUARD: classification unavailable and establishment unknown.""" + + +def _sybil_guard_hold_enrollment(conn, epoch, miner, would_be_units, status): + """SYBIL-GUARD needs_review: zero this epoch's enrollment, keep a record. + + Enrollment is INSERT OR IGNORE (first write wins), so a miner flagged after + its first enrollment this epoch is downgraded explicitly. Only the CURRENT + epoch row is touched. The would-be weight (baseline-capped, i.e. what + probation would have paid) goes to sybil_review_escrow so an operator can + restore it. The flag comes only from this miner's own attestation, so a + third party cannot use this to zero someone else. + """ + sybil_guard.record_review_escrow( + conn, epoch, miner, would_be_units, status.get("review_reason") or "needs_review") + conn.execute( + "UPDATE epoch_enroll SET weight = 0 WHERE epoch = ? AND miner_pk = ?", + (epoch, miner), + ) + print(f"[SYBIL-GUARD] {str(miner)[:20]}... needs_review -> epoch {epoch} weight 0 " + f"(escrowed {would_be_units} units)") + + @app.route('/attest/submit', methods=['POST']) def submit_attestation(): """Submit hardware attestation with fingerprint validation""" @@ -6503,9 +6799,26 @@ def _submit_attestation_impl(): if not oui_ok: return jsonify(oui_info), 412 + # Validate fingerprint data (RIP-PoA). + # SYBIL-GUARD fix: this used to run AFTER the replay block below, which set + # fingerprint_passed = False first. That made detect_fingerprint_anomalies + # (guarded by `if fingerprint_passed`) dead code and stored + # attestation_valid=False for every submission. validate_fingerprint_data + # has no DB side effects, so running it first changes no outcome -- a replay + # is still rejected with 409 below. + # FIX #305: Default to False - must pass validation to earn rewards + fingerprint_passed = False + fingerprint_reason = "not_checked" + + # FIX #305: Always validate - pass None/empty to validator which rejects them + if fingerprint is not None: + fingerprint_passed, fingerprint_reason = validate_fingerprint_data( + fingerprint, claimed_device=device, + ) + else: + fingerprint_reason = "no_fingerprint_submitted" + # Issue #2276: Hardware Fingerprint Replay Attack Defense - # Check for replay attacks BEFORE validating fingerprint data - fingerprint_passed = False # Initialize before replay defense block replay_blocked = False replay_reason = "not_checked" replay_details = None @@ -6596,18 +6909,8 @@ def _submit_attestation_impl(): "code": "REPLAY_ATTACK_BLOCKED" }), 409 - # NEW: Validate fingerprint data (RIP-PoA) - # FIX #305: Default to False - must pass validation to earn rewards - fingerprint_passed = False - fingerprint_reason = "not_checked" - - # FIX #305: Always validate - pass None/empty to validator which rejects them - if fingerprint is not None: - fingerprint_passed, fingerprint_reason = validate_fingerprint_data( - fingerprint, claimed_device=device, - ) - else: - fingerprint_reason = "no_fingerprint_submitted" + # (fingerprint_passed / fingerprint_reason are computed above, before the + # replay block -- SYBIL-GUARD dead-code fix.) # DEBUG: dump fingerprint payload for diagnosis if miner and 'selena' in miner.lower(): @@ -6669,6 +6972,15 @@ def _submit_attestation_impl(): except Exception as _te: print(f"[TEMPORAL] Warning: {_te}") + # SYBIL-GUARD: advance new-miner probation. Runs after + # record_attestation_success (history includes this attestation) and before + # the welcome bonus and auto-enroll, which both consult the result. + probation_status = _sybil_guard_observe( + miner, fingerprint if isinstance(fingerprint, dict) else {}, + client_ip, fingerprint_passed, + nonce=nonce, measurement_binding=data.get("measurement_binding"), + ) + # Update warthog_bonus in attestation record. # Written unconditionally: warthog_bonus describes THIS attestation, and # record_attestation_success() does not carry the column in its upsert. A @@ -6694,7 +7006,7 @@ def _submit_attestation_impl(): # hardware fingerprint earns it: a VM/emulator/missing-fingerprint attest is # still recorded (zero reward weight) but must not drain founder_community. if fingerprint_passed: - _check_welcome_bonus(miner) + _check_welcome_bonus(miner, probation_status) # SYBIL-GUARD: paid at probation exit # AUTO-ENROLL: Automatically enroll miner in current epoch on successful attestation # This eliminates the need for miners to make a separate POST /epoch/enroll call @@ -6721,7 +7033,7 @@ def _submit_attestation_impl(): # line, so a miner contradicting its own measurement history still # collected the full antiquity premium. Gate the bonus on it. hw_weight_raw = hw_weight - hw_weight = apply_temporal_consistency_to_weight(hw_weight, temporal_review) + hw_weight = apply_temporal_consistency_to_weight(hw_weight, temporal_review, probation_status) # RIP-309c phase 0: observe only. Record whether this submission bound # its measurement to the challenge, so fleet adoption can be measured @@ -6741,6 +7053,9 @@ def _submit_attestation_impl(): ) miner_id = _attest_valid_miner(data.get("miner_id")) or miner + if sybil_guard.should_defer_enrollment(probation_status): + raise _EnrollmentDeferred(miner) + with closing(sqlite3.connect(DB_PATH)) as enroll_conn: _fp_for_rotation = fingerprint if isinstance(fingerprint, dict) else {} rotation_eval = evaluate_rotating_fingerprint_checks( @@ -6769,6 +7084,19 @@ def _submit_attestation_impl(): "INSERT OR IGNORE INTO epoch_enroll (epoch, miner_pk, weight) VALUES (?, ?, ?)", (epoch, miner, enroll_weight_units) ) + if sybil_guard.needs_review(probation_status): + if not fingerprint_passed: + _would_be_units = FAILED_FINGERPRINT_WEIGHT_UNITS + else: + _would_be_units = epoch_weight_to_units( + apply_temporal_consistency_to_weight( + hw_weight_raw, temporal_review, + sybil_guard.unguarded_status(probation_status), + ) * rotation_eval["active_ratio"] + ) + _sybil_guard_hold_enrollment( + enroll_conn, epoch, miner, _would_be_units, probation_status, + ) header_pubkey = _valid_ed25519_pubkey_hex(pubkey_hex) or _valid_ed25519_pubkey_hex(miner) if header_pubkey: # Lottery participation and header authorization use the @@ -6796,6 +7124,10 @@ def _submit_attestation_impl(): f"[AUTO-ENROLL] {miner[:20]}... enrolled epoch {epoch} weight={enroll_weight} family={family} " f"arch={arch_for_weight} hw_weight={hw_weight} active_ratio={rotation_eval['active_ratio']:.3f}" ) + except _EnrollmentDeferred: + app.logger.warning( + f"[SYBIL-GUARD] {miner[:20]}... enrollment deferred: probation status unavailable " + f"and establishment unknown (next attestation retries)") except Exception as e: app.logger.error(f"[AUTO-ENROLL] Error enrolling {miner[:20]}...: {e}") @@ -6830,6 +7162,9 @@ def _submit_attestation_impl(): "device": device, "fingerprint_passed": fingerprint_passed, "temporal_review_flag": bool(temporal_review.get("review_flag")), + # SYBIL-GUARD: tells a new miner why it is not yet earning the vintage + # multiplier / welcome bonus and what it still needs. + "probation": sybil_guard.public_status(probation_status), # RIP-309c: tells a client whether its measurement was bound to the # challenge, and what workload the NEXT round expects. A client can # adopt binding without a coordinated release by reading this. @@ -7092,7 +7427,20 @@ def enroll_epoch(): _temporal_enroll = validate_temporal_consistency( fetch_miner_fingerprint_sequence(c, miner_pk) ) - hw_weight = apply_temporal_consistency_to_weight(hw_weight, _temporal_enroll) + # SYBIL-GUARD: read-only probation lookup; enrollment never advances + # probation (only attestations do). Unknown -> probation (fail closed). + try: + _probation_enroll = sybil_guard.get_probation_status(c, miner_pk) + except Exception as _pe: + print(f"[SYBIL-GUARD] enroll status read failed for {miner_pk[:20]}: {_pe}") + _probation_enroll = sybil_guard.fallback_status(c, miner_pk) + if sybil_guard.should_defer_enrollment(_probation_enroll): + return jsonify({ + "ok": False, "error": "enrollment_deferred", + "hint": "probation status temporarily unavailable; retry", + }), 503 + _hw_weight_raw_enroll = hw_weight + hw_weight = apply_temporal_consistency_to_weight(hw_weight, _temporal_enroll, _probation_enroll) _enroll_fp = resolve_enroll_fingerprint(c, miner_pk, data) rotation_eval = evaluate_rotating_fingerprint_checks( @@ -7136,6 +7484,17 @@ def enroll_epoch(): "INSERT OR IGNORE INTO epoch_enroll (epoch, miner_pk, weight) VALUES (?, ?, ?)", (epoch, miner_pk, weight_units) ) + if sybil_guard.needs_review(_probation_enroll): + if fingerprint_failed: + _would_be_units = FAILED_FINGERPRINT_WEIGHT_UNITS + else: + _would_be_units = epoch_weight_to_units( + apply_temporal_consistency_to_weight( + _hw_weight_raw_enroll, _temporal_enroll, + sybil_guard.unguarded_status(_probation_enroll), + ) * rotation_eval['active_ratio'] + ) + _sybil_guard_hold_enrollment(c, epoch, miner_pk, _would_be_units, _probation_enroll) # Register a real Ed25519 pubkey for block-header verification when available. header_pubkey = _valid_ed25519_pubkey_hex(pubkey_hex) or _valid_ed25519_pubkey_hex(miner_pk) @@ -11305,6 +11664,12 @@ def api_rewards_settle(): if not hmac.compare_digest(admin_key, admin_key_env): return jsonify({"ok": False, "reason": "admin_required"}), 401 + if not HAVE_REWARDS or settle_epoch is None: + # Checked after auth so an unauthenticated caller learns nothing about + # module state. Fail closed and say why, rather than a NameError 500. + return jsonify({"ok": False, "reason": "rewards_module_unavailable", + "code": "REWARDS_MODULE_UNAVAILABLE"}), 503 + body = request.get_json(force=True, silent=True) if body is None: body = {} @@ -12599,6 +12964,7 @@ def confirm_pending(): confirmed_count = 0 confirmed_ids = [] errors = [] + failed_ids = [] conn = sqlite3.connect(DB_PATH) try: @@ -12691,6 +13057,7 @@ def confirm_pending(): pass print(f"[ERROR] confirm_pending {pid}: {e!r}") errors.append({"id": pid, "error": "internal_error"}) + failed_ids.append(pid) after_stats = _pending_overdue_stats(c, now) conn.commit() @@ -12700,13 +13067,26 @@ def confirm_pending(): "confirmed_ids": str(confirmed_ids[:10]), # First 10 "errors": len(errors) }) + if failed_ids: + send_sophiacheck_alert("critical", f"{len(failed_ids)} pending transfer(s) FAILED to confirm", { + "failed_ids": str(failed_ids[:10]), # First 10 + "confirmed_count": confirmed_count, + }) + # `ok` means "every selected transfer was resolved" (confirmed, or voided + # for insufficient balance). A row that raised is left 'pending' and was + # NOT delivered, so the pass is not ok. This used to be a hard-coded + # True: from 2026-09-22 every confirm raised (mirror_exceeds_balance) + # and the cron read `"ok": true, confirmed_count: 0` as a healthy empty + # pass while ~1,400 RTC of payouts sat undelivered for two days. return jsonify({ - "ok": True, + "ok": not failed_ids, "limit": limit, "selected_count": len(ready), "confirmed_count": confirmed_count, "confirmed_ids": confirmed_ids, + "failed_count": len(failed_ids), + "failed_ids": failed_ids, "errors": errors if errors else None, "stale_pending_count_before": before_stats["stale_pending_count"], "max_confirm_overdue_seconds_before": before_stats["max_confirm_overdue_seconds"], @@ -12751,18 +13131,26 @@ def check_integrity(): """).fetchall()) mismatches = [] - for miner_id, balance in balances.items(): - ledger_sum = ledger_sums.get(miner_id, 0) - + # Walk the UNION of both sides. Iterating balances alone made a wallet that + # exists only in the ledger invisible: RTC credited in the ledger whose + # balance row is missing (never created, or deleted) reported ok=true. + for miner_id in sorted(set(balances) | set(ledger_sums), key=str): + balance_row_missing = miner_id not in balances + balance = int(balances.get(miner_id) or 0) + ledger_sum = int(ledger_sums.get(miner_id) or 0) + # Balance should equal ledger sum (pending doesn't affect balance yet) if balance != ledger_sum: - mismatches.append({ + mismatch = { "miner_id": miner_id, "balance_rtc": balance / 1000000, "ledger_sum_rtc": ledger_sum / 1000000, "diff_rtc": (balance - ledger_sum) / 1000000 - }) - + } + if balance_row_missing: + mismatch["balance_row_missing"] = True + mismatches.append(mismatch) + integrity_ok = len(mismatches) == 0 if not integrity_ok: @@ -12773,7 +13161,7 @@ def check_integrity(): return jsonify({ "ok": integrity_ok, - "total_miners_checked": len(balances), + "total_miners_checked": len(set(balances) | set(ledger_sums)), "mismatches": mismatches if mismatches else None, "pending_transfers": len(pending) }) @@ -13394,6 +13782,10 @@ def _debit_wallet_atomic(c: sqlite3.Cursor, wallet_id: str, amount_i64: int, bal BEACON_ATLAS_DB = "/root/beacon/beacon_atlas.db" +# Statuses an administrator uses to bar a Beacon agent (same set as beacon_api). +BEACON_BARRED_STATUSES = frozenset({"banned", "suspended", "revoked"}) + + def resolve_bcn_wallet(bcn_id: str) -> dict: """ Resolve a bcn_ beacon ID to its registered public key and metadata. @@ -13422,7 +13814,9 @@ def resolve_bcn_wallet(bcn_id: str) -> dict: if not row: return {"found": False, "error": "beacon_id_not_registered"} - if row["status"] != "active": + # Barred means an administrator blocked the agent. "alive" and "degraded" + # come from ordinary Beacon heartbeats and must not stop payments. + if (row["status"] or "active") in BEACON_BARRED_STATUSES: return {"found": False, "error": f"beacon_agent_status:{row['status']}"} pubkey_hex = row["pubkey_hex"] @@ -13952,6 +14346,7 @@ def _limit_governance_vote_requests(): current_slot_fn=current_slot, dual_write=UTXO_DUAL_WRITE, review_gate_fn=wallet_review_gate_response, + is_admin_fn=is_admin, ) except ImportError as e: # Optional module genuinely absent: run without the UTXO layer. diff --git a/node/service_catalog.py b/node/service_catalog.py new file mode 100644 index 000000000..89050a6a5 --- /dev/null +++ b/node/service_catalog.py @@ -0,0 +1,769 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""RustChain RTC service catalog. + +Agents list work they can do, priced in RTC, and other agents order it. +Payment happens after delivery, from the buyer's own wallet, through the +existing ``/wallet/transfer/signed`` endpoint with memo ``svc:``. + +Design rules (see ~/elyan-labs/agent-economy/final.md, roadmap item 5): + +* Non-custodial. This module stores listings and order receipts only. It + never debits, credits, escrows or locks RTC, and takes no fee. Payment + status is *read* from ``pending_ledger``. +* RTC only. Prices are RTC amounts. Request bodies reject unknown fields, + and listing text that quotes a fiat figure is refused, so work is priced + against other work and never in dollars. +* Work, not volume. Provider stats are counts of delivered and accepted + work and distinct buyers. No RTC totals, no volume or earnings rankings. + A deliverable hash can settle only one order, and a provider cannot buy + from itself. + +Auth uses the Beacon canonical request signature (same headers and +message layout as beacon_api), with the agent's Ed25519 public key looked +up in the Beacon Atlas ``relay_agents`` table. + +Registered from wsgi.py via ``register_service_catalog(app, DB_PATH)``. +""" + +import hashlib +import json +import re +import secrets +import sqlite3 +import time +import unicodedata +from contextlib import closing +from decimal import Decimal, DecimalException + +from flask import Blueprint, jsonify, request + +try: + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey +except ImportError: # pragma: no cover - signatures then fail closed + Ed25519PublicKey = None + +UNIT = 1_000_000 # uRTC per RTC, matches ledger amount_i64 +AUTH_WINDOW_SECONDS = 300 +AUTH_MAX_FUTURE_SECONDS = 30 +# Same hard-coded path the node's resolve_bcn_wallet uses, so catalog and +# /wallet/transfer/signed always agree on who is registered. Deliberately +# no env override: the node has none either. +BEACON_ATLAS_DB = "/root/beacon/beacon_atlas.db" + +CATEGORIES = ( + "render", "review", "hw_test", "vision", "compute", + "docs", "translation", "testing", "other", +) +LISTING_STATUSES = ("active", "paused", "retired") +# Administrator-barred Beacon statuses; "alive"/"degraded" come from heartbeats. +BARRED_STATUSES = frozenset({"banned", "suspended", "revoked"}) + +MIN_PRICE_I64 = 1 # 0.000001 RTC +MAX_PRICE_I64 = 100_000 * UNIT # sanity ceiling per unit of work +MAX_ACTIVE_LISTINGS = 25 +MAX_OPEN_ORDERS_PER_BUYER = 20 +MAX_LISTINGS_PER_DAY = 50 +MAX_ORDERS_PER_DAY = 100 +MAX_PAGE = 100 +MAX_OFFSET = 10_000 + +TERMS = ( + "Prices are set by providers in RTC. Pay after delivery from your own " + "wallet via /wallet/transfer/signed with memo svc:. This " + "catalog holds no funds, moves no RTC and takes no fee. RTC is a work " + "credit, not for sale, with no price or redemption." +) + +_CANONICAL_AGENT_ID = re.compile(r"^bcn_[0-9a-f]{12}$") +_SHA256_HEX = re.compile(r"^[0-9a-f]{64}$") +_ID = re.compile(r"^(lst|ord)_[0-9a-f]{16}$") +# Fiat figures in free text: "$5", "5$", "€3", "10 USD", "USD5", "dollars". +# Best effort: the real control is that bodies accept no price field but +# price_rtc. Text is NFKC-normalised first so fullwidth forms match. +_FIAT = re.compile( + r"[$€£¥¢₹₩₽]\s*\d|\d\s*[$€£¥¢₹₩₽]" + r"|(? Decimal(MAX_PRICE_I64) / UNIT: + raise _Reject(400, "price_rtc out of range", + max_rtc=_rtc_from_i64(MAX_PRICE_I64)) + scaled = dec * UNIT + except DecimalException: + raise _Reject(400, "price_rtc must be a number") + if scaled != scaled.to_integral_value(): + raise _Reject(400, "price_rtc supports at most 6 decimal places") + price_i64 = int(scaled) + if not MIN_PRICE_I64 <= price_i64 <= MAX_PRICE_I64: + raise _Reject(400, "price_rtc out of range", + min_rtc=_rtc_from_i64(MIN_PRICE_I64), + max_rtc=_rtc_from_i64(MAX_PRICE_I64)) + return price_i64 + + +def _text(data, field, *, min_len=0, max_len, default=None): + value = data.get(field, default) + if value is None: + if min_len: + raise _Reject(400, f"{field} is required") + return "" + if not isinstance(value, str): + raise _Reject(400, f"{field} must be a string") + value = value.strip() + if len(value) < min_len or len(value) > max_len: + raise _Reject(400, f"{field} must be {min_len}-{max_len} characters") + return value + + +def _no_fiat(field, value): + if value and _FIAT.search(unicodedata.normalize("NFKC", value)): + raise _Reject(400, "fiat_reference_not_allowed", field=field, + hint="Price work in RTC only; do not quote dollar or other fiat figures.") + + +def _json_body(allowed): + raw = request.get_data(cache=True) or b"" + try: + data = json.loads(raw.decode("utf-8")) if raw else {} + except (UnicodeDecodeError, ValueError): + raise _Reject(400, "body must be JSON") + if not isinstance(data, dict): + raise _Reject(400, "body must be a JSON object") + unknown = sorted(set(data) - allowed) + if unknown: + raise _Reject(400, "unknown_fields", fields=unknown, allowed=sorted(allowed)) + return data + + +def _listing_json(row): + return { + "id": row["id"], + "provider": row["provider"], + "title": row["title"], + "description": row["description"], + "category": row["category"], + "price_rtc": _rtc_from_i64(row["price_i64"]), + "unit": row["unit"], + "turnaround_hours": row["turnaround_hours"], + "status": row["status"], + "created_at": row["created_at"], + "updated_at": row["updated_at"], + } + + +def _payment_memo(order_id): + return f"svc:{order_id}" + + +def _payment_status(conn, order): + """Read-only reconciliation against pending_ledger. + + A payment counts when a signed transfer to the provider, from someone + other than the provider, carries this order's memo and covers the + snapshot price. Voided transfers never count. + """ + try: + rows = conn.execute( + """ + SELECT status, tx_hash FROM pending_ledger + WHERE to_miner = ? AND from_miner != ? AND reason = ? + AND amount_i64 >= ? AND status IN ('pending', 'confirmed') + ORDER BY CASE status WHEN 'confirmed' THEN 0 ELSE 1 END, id + """, + (order["provider"], order["provider"], + "signed_transfer:" + _payment_memo(order["id"]), order["price_i64"]), + ).fetchall() # fetchall-ok: bounded-by-schema (exact memo for one order) + except sqlite3.OperationalError: + return {"state": "unknown"} + if not rows: + return {"state": "unpaid"} + return {"state": rows[0]["status"], "tx_hash": rows[0]["tx_hash"]} + + +def _order_public_json(conn, row): + """What anyone holding an order id may see. Order ids appear in ledger + memos, so notes and delivery links stay party-only.""" + out = { + "id": row["id"], + "listing_id": row["listing_id"], + "provider": row["provider"], + "price_rtc": _rtc_from_i64(row["price_i64"]), + "status": row["status"], + "updated_at": row["updated_at"], + } + if row["status"] == "accepted": + out["payment"] = _payment_status(conn, row) + return out + + +def _order_json(conn, row): + """Full view, for the buyer and provider only.""" + out = { + "id": row["id"], + "listing_id": row["listing_id"], + "provider": row["provider"], + "buyer": row["buyer"], + "price_rtc": _rtc_from_i64(row["price_i64"]), + "note": row["note"], + "status": row["status"], + "deliverable_hash": row["deliverable_hash"], + "deliverable_uri": row["deliverable_uri"], + "close_reason": row["close_reason"], + "created_at": row["created_at"], + "updated_at": row["updated_at"], + } + if row["status"] == "accepted": + out["payment"] = _payment_status(conn, row) + out["payment_instructions"] = _payment_instructions(row) + return out + + +def _payment_instructions(row): + return { + "endpoint": "/wallet/transfer/signed", + "to_address": row["provider"], + "amount_rtc": _rtc_from_i64(row["price_i64"]), + "memo": _payment_memo(row["id"]), + "note": ("Send one signed transfer for the full amount from your own wallet. " + "This catalog does not move funds."), + } + + +# --------------------------------------------------------------------------- +# Auth +# --------------------------------------------------------------------------- + +def _atlas_pubkey_resolver(atlas_db_path): + """Return the Atlas pubkey for an active agent, else None. + + Mirrors resolve_bcn_wallet: barred agents (banned, suspended, revoked) are + treated as unregistered. Heartbeat statuses such as "alive" are fine. + """ + def resolve(agent_id): + try: + with closing(sqlite3.connect(atlas_db_path)) as conn: + row = conn.execute( + "SELECT pubkey_hex, status FROM relay_agents WHERE agent_id = ?", + (agent_id,), + ).fetchone() + except sqlite3.Error: + return None + if not row or (row[1] or "active") in BARRED_STATUSES: + return None + return row[0] + return resolve + + +def _id_matches_pubkey(agent_id, pubkey_hex): + try: + key = bytes.fromhex(str(pubkey_hex).strip().removeprefix("0x")) + except ValueError: + return False + return agent_id == "bcn_" + hashlib.sha256(key).hexdigest()[:12] + + +def _canonical_message(agent_id, timestamp, nonce, body_bytes): + """Beacon layout (beacon_api._canonical_agent_request), except the path + includes the query string so signed GET filters can't be altered. For a + request with no query this is byte-identical to Beacon's message.""" + return "\n".join([ + request.method.upper(), + request.full_path.rstrip("?"), + hashlib.sha256(body_bytes or b"").hexdigest(), + str(timestamp), + str(nonce), + str(agent_id), + ]).encode("utf-8") + + +def _verify(pubkey_hex, signature_hex, message): + if Ed25519PublicKey is None: + return False + try: + key = str(pubkey_hex or "").strip() + if key.lower().startswith("0x"): + key = key[2:] + Ed25519PublicKey.from_public_bytes(bytes.fromhex(key)).verify( + bytes.fromhex(str(signature_hex or "").strip()), message) + return True + except Exception: + return False + + +def _authenticate(conn, resolve_pubkey): + agent_id = request.headers.get("X-Agent-Id", "") + timestamp_raw = request.headers.get("X-Agent-Timestamp", "") + nonce = request.headers.get("X-Agent-Nonce", "") + signature = request.headers.get("X-Agent-Signature", "") + if not all([agent_id, timestamp_raw, nonce, signature]): + raise _Reject(401, "Missing Beacon signature headers: X-Agent-Id, " + "X-Agent-Timestamp, X-Agent-Nonce, X-Agent-Signature") + if not _CANONICAL_AGENT_ID.match(agent_id): + raise _Reject(400, "X-Agent-Id must be a canonical bcn_ id") + try: + timestamp = int(timestamp_raw) + except ValueError: + raise _Reject(400, "Invalid X-Agent-Timestamp") + now = int(time.time()) + if timestamp < now - AUTH_WINDOW_SECONDS or timestamp > now + AUTH_MAX_FUTURE_SECONDS: + raise _Reject(401, "Stale Beacon signature timestamp") + if not nonce.strip() or len(nonce) > 128: + raise _Reject(400, "Invalid X-Agent-Nonce") + + pubkey_hex = resolve_pubkey(agent_id) + if not pubkey_hex or not _id_matches_pubkey(agent_id, pubkey_hex): + raise _Reject(403, "agent not registered and active in Beacon Atlas") + message = _canonical_message(agent_id, timestamp, nonce, request.get_data(cache=True)) + if not _verify(pubkey_hex, signature, message): + raise _Reject(401, "Invalid Beacon agent signature") + + # Keep each nonce until its signature can no longer pass the timestamp + # check (created_at = the later of now and the signed timestamp). + conn.execute("DELETE FROM catalog_agent_nonces WHERE created_at < ?", + (now - AUTH_WINDOW_SECONDS,)) + try: + conn.execute( + "INSERT INTO catalog_agent_nonces (agent_id, nonce, created_at) VALUES (?, ?, ?)", + (agent_id, nonce, max(now, timestamp))) + except sqlite3.IntegrityError: + conn.rollback() + raise _Reject(401, "Replay detected for Beacon agent nonce") + # Commit now: a signed request is spent even if the action it asks for + # is refused, so it can't be replayed once the state changes. + conn.commit() + return agent_id + + +# --------------------------------------------------------------------------- +# Routes +# --------------------------------------------------------------------------- + +def create_catalog_blueprint(db_path, pubkey_resolver): + bp = Blueprint("service_catalog", __name__, url_prefix="/catalog") + + def connect(): + conn = sqlite3.connect(db_path, timeout=10) + conn.row_factory = sqlite3.Row + return conn + + def handle(fn): + """Run fn(conn) in one transaction; map _Reject to JSON errors.""" + with closing(connect()) as conn: + try: + result = fn(conn) + conn.commit() + return result + except _Reject as rej: + conn.rollback() + return jsonify(rej.payload), rej.http_status + + def get_order(conn, order_id): + if not _ID.match(order_id or ""): + raise _Reject(404, "order not found") + row = conn.execute("SELECT * FROM catalog_orders WHERE id = ?", (order_id,)).fetchone() + if not row: + raise _Reject(404, "order not found") + return row + + def transition(conn, order, actor_field, agent_id, from_status, to_status, **fields): + if order[actor_field] != agent_id: + raise _Reject(403, f"only the {actor_field} can do this") + sets = ", ".join(f"{k} = ?" for k in fields) + sql = (f"UPDATE catalog_orders SET status = ?, updated_at = ?" + f"{', ' + sets if sets else ''} WHERE id = ? AND status = ?") + try: + cur = conn.execute(sql, (to_status, int(time.time()), *fields.values(), + order["id"], from_status)) + except sqlite3.IntegrityError: + raise _Reject(409, "deliverable_hash already used by another order") + if cur.rowcount != 1: + raise _Reject(409, f"order must be {from_status}", status=order["status"]) + return conn.execute("SELECT * FROM catalog_orders WHERE id = ?", (order["id"],)).fetchone() + + @bp.route("", methods=["GET"]) + def catalog_index(): + return jsonify({"currency": "RTC", "categories": list(CATEGORIES), "terms": TERMS}) + + @bp.route("/listings", methods=["GET"]) + def list_listings(): + clauses, params = ["status = 'active'"], [] + category = request.args.get("category") + if category: + clauses.append("category = ?") + params.append(category) + provider = request.args.get("provider") + if provider: + clauses.append("provider = ?") + params.append(provider) + try: + limit = max(1, min(MAX_PAGE, int(request.args.get("limit", 50)))) + offset = max(0, min(MAX_OFFSET, int(request.args.get("offset", 0)))) + except ValueError: + return jsonify({"error": "limit and offset must be integers"}), 400 + with closing(connect()) as conn: + rows = conn.execute( + f"SELECT * FROM catalog_listings WHERE {' AND '.join(clauses)} " + "ORDER BY created_at DESC, id LIMIT ? OFFSET ?", + (*params, limit, offset)).fetchall() # fetchall-ok: already-paginated (LIMIT <= MAX_PAGE) + return jsonify({"listings": [_listing_json(r) for r in rows], + "limit": limit, "offset": offset, "terms": TERMS}) + + @bp.route("/listings/", methods=["GET"]) + def get_listing(listing_id): + with closing(connect()) as conn: + row = conn.execute("SELECT * FROM catalog_listings WHERE id = ?", + (listing_id,)).fetchone() + if not row: + return jsonify({"error": "listing not found"}), 404 + return jsonify(_listing_json(row)) + + @bp.route("/listings", methods=["POST"]) + def create_listing(): + def run(conn): + data = _json_body(_LISTING_FIELDS) + provider = _authenticate(conn, pubkey_resolver) + title = _text(data, "title", min_len=5, max_len=120) + description = _text(data, "description", max_len=2000) + unit = _text(data, "unit", min_len=1, max_len=32, default="per job") + for field, value in (("title", title), ("description", description), ("unit", unit)): + _no_fiat(field, value) + category = data.get("category", "other") + if category not in CATEGORIES: + raise _Reject(400, "unknown category", allowed=list(CATEGORIES)) + price_i64 = _parse_price_i64(data.get("price_rtc")) + turnaround = data.get("turnaround_hours") + if turnaround is not None and ( + isinstance(turnaround, bool) or not isinstance(turnaround, int) + or not 1 <= turnaround <= 24 * 90): + raise _Reject(400, "turnaround_hours must be an integer 1-2160") + active = conn.execute( + "SELECT COUNT(*) FROM catalog_listings WHERE provider = ? AND status != 'retired'", + (provider,)).fetchone()[0] + if active >= MAX_ACTIVE_LISTINGS: + raise _Reject(429, "too many open listings", max=MAX_ACTIVE_LISTINGS) + recent = conn.execute( + "SELECT COUNT(*) FROM catalog_listings WHERE provider = ? AND created_at > ?", + (provider, int(time.time()) - 86400)).fetchone()[0] + if recent >= MAX_LISTINGS_PER_DAY: + raise _Reject(429, "daily listing limit reached", max=MAX_LISTINGS_PER_DAY) + now = int(time.time()) + listing_id = "lst_" + secrets.token_hex(8) + conn.execute( + "INSERT INTO catalog_listings (id, provider, title, description, category, " + "price_i64, unit, turnaround_hours, status, created_at, updated_at) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, ?)", + (listing_id, provider, title, description, category, price_i64, unit, + turnaround, now, now)) + row = conn.execute("SELECT * FROM catalog_listings WHERE id = ?", + (listing_id,)).fetchone() + return jsonify(_listing_json(row)), 201 + return handle(run) + + @bp.route("/listings//status", methods=["POST"]) + def set_listing_status(listing_id): + # Listings are immutable apart from status: to change a price, retire + # the listing and post a new one. Orders snapshot the price anyway. + def run(conn): + data = _json_body({"status"}) + agent_id = _authenticate(conn, pubkey_resolver) + status = data.get("status") + if status not in LISTING_STATUSES: + raise _Reject(400, "unknown status", allowed=list(LISTING_STATUSES)) + row = conn.execute("SELECT * FROM catalog_listings WHERE id = ?", + (listing_id,)).fetchone() + if not row: + raise _Reject(404, "listing not found") + if row["provider"] != agent_id: + raise _Reject(403, "only the provider can change this listing") + if row["status"] == "retired": + raise _Reject(409, "retired listings cannot be reopened; post a new listing") + conn.execute("UPDATE catalog_listings SET status = ?, updated_at = ? WHERE id = ?", + (status, int(time.time()), listing_id)) + row = conn.execute("SELECT * FROM catalog_listings WHERE id = ?", + (listing_id,)).fetchone() + return jsonify(_listing_json(row)) + return handle(run) + + @bp.route("/orders", methods=["POST"]) + def create_order(): + def run(conn): + data = _json_body(_ORDER_FIELDS) + buyer = _authenticate(conn, pubkey_resolver) + note = _text(data, "note", max_len=2000) + _no_fiat("note", note) + listing = conn.execute("SELECT * FROM catalog_listings WHERE id = ?", + (str(data.get("listing_id", "")),)).fetchone() + if not listing: + raise _Reject(404, "listing not found") + if listing["status"] != "active": + raise _Reject(409, "listing is not active", status=listing["status"]) + if listing["provider"] == buyer: + raise _Reject(400, "self_dealing", hint="A provider cannot order its own listing.") + open_orders = conn.execute( + "SELECT COUNT(*) FROM catalog_orders WHERE buyer = ? " + "AND status IN ('requested', 'delivered')", (buyer,)).fetchone()[0] + if open_orders >= MAX_OPEN_ORDERS_PER_BUYER: + raise _Reject(429, "too many open orders", max=MAX_OPEN_ORDERS_PER_BUYER) + recent = conn.execute( + "SELECT COUNT(*) FROM catalog_orders WHERE buyer = ? AND created_at > ?", + (buyer, int(time.time()) - 86400)).fetchone()[0] + if recent >= MAX_ORDERS_PER_DAY: + raise _Reject(429, "daily order limit reached", max=MAX_ORDERS_PER_DAY) + now = int(time.time()) + order_id = "ord_" + secrets.token_hex(8) + conn.execute( + "INSERT INTO catalog_orders (id, listing_id, provider, buyer, price_i64, note, " + "status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, 'requested', ?, ?)", + (order_id, listing["id"], listing["provider"], buyer, listing["price_i64"], + note, now, now)) + row = conn.execute("SELECT * FROM catalog_orders WHERE id = ?", (order_id,)).fetchone() + return jsonify(_order_json(conn, row)), 201 + return handle(run) + + @bp.route("/orders", methods=["GET"]) + def my_orders(): + """Signed inbox: ?role=provider|buyer&status=... (sign the full path + including the query string, with an empty body).""" + def run(conn): + agent_id = _authenticate(conn, pubkey_resolver) + role = request.args.get("role", "provider") + if role not in ("provider", "buyer"): + raise _Reject(400, "role must be provider or buyer") + clauses, params = [f"{role} = ?"], [agent_id] + status = request.args.get("status") + if status: + clauses.append("status = ?") + params.append(status) + try: + limit = max(1, min(MAX_PAGE, int(request.args.get("limit", 50)))) + offset = max(0, min(MAX_OFFSET, int(request.args.get("offset", 0)))) + except ValueError: + raise _Reject(400, "limit and offset must be integers") + rows = conn.execute( + f"SELECT * FROM catalog_orders WHERE {' AND '.join(clauses)} " + "ORDER BY updated_at DESC, id LIMIT ? OFFSET ?", + (*params, limit, offset)).fetchall() # fetchall-ok: already-paginated (LIMIT <= MAX_PAGE) + return jsonify({"orders": [_order_json(conn, r) for r in rows], + "limit": limit, "offset": offset}) + return handle(run) + + @bp.route("/orders/", methods=["GET"]) + def get_order_route(order_id): + """Public summary; the full view needs a signature from a party.""" + def run(conn): + if not request.headers.get("X-Agent-Id"): + return jsonify(_order_public_json(conn, get_order(conn, order_id))) + agent_id = _authenticate(conn, pubkey_resolver) + order = get_order(conn, order_id) + if agent_id not in (order["buyer"], order["provider"]): + raise _Reject(403, "only the buyer or provider can see the full order") + return jsonify(_order_json(conn, order)) + return handle(run) + + @bp.route("/orders//deliver", methods=["POST"]) + def deliver_order(order_id): + def run(conn): + data = _json_body({"deliverable_hash", "deliverable_uri"}) + agent_id = _authenticate(conn, pubkey_resolver) + digest = str(data.get("deliverable_hash", "")).strip().lower() + if not _SHA256_HEX.match(digest): + raise _Reject(400, "deliverable_hash must be a sha256 hex digest") + uri = _text(data, "deliverable_uri", max_len=500) + if uri and not uri.startswith("https://"): + raise _Reject(400, "deliverable_uri must be https") + order = get_order(conn, order_id) + row = transition(conn, order, "provider", agent_id, "requested", "delivered", + deliverable_hash=digest, deliverable_uri=uri or None) + return jsonify(_order_json(conn, row)) + return handle(run) + + @bp.route("/orders//accept", methods=["POST"]) + def accept_order(order_id): + def run(conn): + _json_body(set()) + agent_id = _authenticate(conn, pubkey_resolver) + row = transition(conn, get_order(conn, order_id), "buyer", agent_id, + "delivered", "accepted") + return jsonify(_order_json(conn, row)) + return handle(run) + + @bp.route("/orders//reject", methods=["POST"]) + def reject_order(order_id): + # Disputes affect standing only. Nothing was paid, so nothing refunds. + def run(conn): + data = _json_body({"reason"}) + agent_id = _authenticate(conn, pubkey_resolver) + reason = _text(data, "reason", min_len=3, max_len=500) + _no_fiat("reason", reason) + row = transition(conn, get_order(conn, order_id), "buyer", agent_id, + "delivered", "rejected", close_reason=reason) + return jsonify(_order_json(conn, row)) + return handle(run) + + @bp.route("/orders//cancel", methods=["POST"]) + def cancel_order(order_id): + def run(conn): + data = _json_body({"reason"}) + agent_id = _authenticate(conn, pubkey_resolver) + reason = _text(data, "reason", max_len=500) + _no_fiat("reason", reason) + order = get_order(conn, order_id) + actor = "buyer" if order["buyer"] == agent_id else "provider" + row = transition(conn, order, actor, agent_id, "requested", "cancelled", + close_reason=reason or None) + return jsonify(_order_json(conn, row)) + return handle(run) + + @bp.route("/providers/", methods=["GET"]) + def provider_record(agent_id): + # Counts of work only. Deliberately no RTC totals and no rankings. + with closing(connect()) as conn: + listings = conn.execute( + "SELECT COUNT(*) FROM catalog_listings WHERE provider = ? AND status = 'active'", + (agent_id,)).fetchone()[0] + counts = {s: 0 for s in ("delivered", "accepted", "rejected", "cancelled")} + for status, n in conn.execute( + "SELECT status, COUNT(*) FROM catalog_orders WHERE provider = ? " + "GROUP BY status", (agent_id,)): + if status in counts: + counts[status] = n + distinct_buyers = conn.execute( + "SELECT COUNT(DISTINCT buyer) FROM catalog_orders " + "WHERE provider = ? AND status = 'accepted'", (agent_id,)).fetchone()[0] + # Acceptance costs a buyer nothing, so it can be faked with extra + # identities. Confirmed payment from someone other than the + # provider is the stronger signal, reported separately. + try: + paid, paying_buyers = conn.execute( + """ + SELECT COUNT(DISTINCT o.id), COUNT(DISTINCT o.buyer) + FROM catalog_orders o JOIN pending_ledger p + ON p.reason = 'signed_transfer:svc:' || o.id + AND p.to_miner = o.provider AND p.from_miner != o.provider + AND p.amount_i64 >= o.price_i64 AND p.status = 'confirmed' + WHERE o.provider = ? AND o.status = 'accepted' + """, (agent_id,)).fetchone() + except sqlite3.OperationalError: + paid = paying_buyers = None + return jsonify({ + "agent_id": agent_id, + "active_listings": listings, + # "delivered" counts every order that reached delivery, whatever + # the buyer decided afterwards. + "orders_delivered": counts["delivered"] + counts["accepted"] + counts["rejected"], + "orders_accepted": counts["accepted"], + "orders_rejected": counts["rejected"], + "orders_cancelled": counts["cancelled"], + "distinct_buyers_accepted": distinct_buyers, + "orders_paid_confirmed": paid, + "distinct_paying_buyers": paying_buyers, + "note": ("accepted counts are reported by buyers; paid counts are " + "confirmed signed transfers from a wallet other than the provider's id"), + }) + + return bp + + +def register_service_catalog(app, db_path, atlas_db_path=None, pubkey_resolver=None): + """Create tables and mount /catalog. Never raises into node startup.""" + try: + init_catalog_tables(db_path) + resolver = pubkey_resolver or _atlas_pubkey_resolver(atlas_db_path or BEACON_ATLAS_DB) + app.register_blueprint(create_catalog_blueprint(db_path, resolver)) + print("[catalog] RTC service catalog registered at /catalog") + return True + except Exception as exc: + print(f"[catalog] registration failed: {exc}") + return False diff --git a/node/sophia_elya_service.py b/node/sophia_elya_service.py index 414456e54..2de40f6ec 100644 --- a/node/sophia_elya_service.py +++ b/node/sophia_elya_service.py @@ -1,12 +1,31 @@ #!/usr/bin/env python3 """ -RustChain v2 - RIP-0005 Epoch Pro-Rata Rewards -Production Anti-Spoof System with Fair Distribution +LEGACY PROTOTYPE -- RustChain v2 RIP-0005 epoch pro-rata rewards (2.1.0-rip5). + +THIS IS NOT THE RUSTCHAIN NODE. The production node is +``node/rustchain_v2_integrated_v2.2.1_rip200.py`` served via ``node/wsgi.py`` +(gunicorn). This standalone Flask app predates RIP-200 and has its OWN epoch +enrollment and settlement writers with none of the node's protections: +unauthenticated ``/attest/submit`` hands out enrollment tickets, and it has no +new-miner probation / Sybil holds, no anti-double-mining, no hardware binding +and no fingerprint validation. + +Because ``DB_PATH`` is the relative ``./rustchain_v2.db`` -- the same filename +the real node uses -- running it from a node's working directory would write +straight into the consensus ``epoch_enroll`` table the real node settles from. + +Its money-writing paths (``inc_epoch_block``, ``enroll_epoch``, +``finalize_epoch``, ``init_db`` and the ``/epoch/enroll`` and +``/api/submit_block`` routes) therefore fail closed unless +``RUSTCHAIN_SOPHIA_ELYA_LEGACY_SETTLEMENT=1`` is set, and they refuse a +database that looks like a consensus node DB even when it is. + Issue #2295: Added WebSocket real-time feed for Block Explorer """ import math import hashlib import json +import os import secrets import sqlite3 import time @@ -43,6 +62,58 @@ DB_PATH = "./rustchain_v2.db" RTC_MICRO_UNITS = 1_000_000 +LEGACY_SETTLEMENT_ENV = "RUSTCHAIN_SOPHIA_ELYA_LEGACY_SETTLEMENT" +REAL_NODE_HINT = ( + "Run the real node instead: node/rustchain_v2_integrated_v2.2.1_rip200.py " + "via node/wsgi.py (gunicorn). Its enrollment and settlement apply " + "probation/holds, anti-double-mining and fingerprint checks; this legacy " + "RIP-0005 prototype applies none of them." +) + + +class LegacySettlementDisabled(RuntimeError): + """Raised when this legacy prototype is asked to enroll miners or settle epochs.""" + + +def _legacy_settlement_enabled(): + return os.environ.get(LEGACY_SETTLEMENT_ENV, "") == "1" + + +def _looks_like_consensus_db(conn): + """True if ``conn`` is a real RustChain node database, not a Sophia sandbox DB.""" + balance_cols = {row[1] for row in conn.execute("PRAGMA table_info(balances)").fetchall()} # fetchall-ok: pragma-result + if balance_cols & {"miner_id", "amount_i64", "coinbase_address"}: + return True + row = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='miner_attest_recent'" + ).fetchone() + return row is not None + + +def _require_legacy_settlement(conn=None): + """Fail closed before any enrollment / settlement / block-accounting write. + + Off unless explicitly opted in, and -- even when opted in -- never against a + database that belongs to a real node. + """ + if not _legacy_settlement_enabled(): + raise LegacySettlementDisabled( + "sophia_elya_service is a legacy RIP-0005 prototype and its epoch " + f"enrollment/settlement is disabled (set {LEGACY_SETTLEMENT_ENV}=1 " + "only for isolated testing). " + REAL_NODE_HINT + ) + if conn is not None and _looks_like_consensus_db(conn): + raise LegacySettlementDisabled( + f"sophia_elya_service refuses to write to {DB_PATH!r}: it looks like a " + "RustChain consensus node database (balances.amount_i64 / " + "miner_attest_recent present). " + REAL_NODE_HINT + ) + + +def _legacy_disabled_response(exc): + return jsonify({"ok": False, "reason": "legacy_settlement_disabled", "detail": str(exc)}), 503 + + def _rtc_to_micro(amount_rtc): """Convert public RTC values to canonical integer micro-RTC units.""" return int( @@ -128,7 +199,9 @@ def _ensure_epoch_state_settlement_schema(conn): def init_db(): """Initialize database with epoch tables""" + _require_legacy_settlement() # before connect: a refusal creates no DB file with sqlite3.connect(DB_PATH) as c: + _require_legacy_settlement(c) # Existing tables c.execute("CREATE TABLE IF NOT EXISTS nonces (nonce TEXT PRIMARY KEY, expires_at INTEGER)") c.execute("CREATE TABLE IF NOT EXISTS tickets (ticket_id TEXT PRIMARY KEY, expires_at INTEGER, commitment TEXT)") @@ -187,7 +260,9 @@ def _finite_float(value, default=1.0): def inc_epoch_block(epoch): """Increment accepted blocks for epoch""" + _require_legacy_settlement() with sqlite3.connect(DB_PATH) as c: + _require_legacy_settlement(c) c.execute("PRAGMA busy_timeout=5000") c.execute("INSERT OR IGNORE INTO epoch_state(epoch, accepted_blocks, finalized, settled) VALUES (?,0,0,0)", (epoch,)) # Do not inflate the block count once the epoch is finalized/settled — @@ -210,12 +285,16 @@ def enroll_epoch(epoch, miner_pk, weight): # this guard protects any internal enrollment path as well. if not math.isfinite(weight) or weight <= 0: return + _require_legacy_settlement() with sqlite3.connect(DB_PATH) as c: + _require_legacy_settlement(c) c.execute("INSERT OR IGNORE INTO epoch_enroll(epoch, miner_pk, weight) VALUES (?,?,?)", (epoch, miner_pk, weight)) def finalize_epoch(epoch, per_block_rtc): """Finalize epoch and distribute rewards""" + _require_legacy_settlement() with sqlite3.connect(DB_PATH) as c: + _require_legacy_settlement(c) c.execute("PRAGMA busy_timeout=5000") c.execute("BEGIN IMMEDIATE") # COALESCE settled so a legacy/shared row whose column was added without @@ -437,13 +516,23 @@ def epoch_enroll(): if not (total_weight > 0): return jsonify({"ok": False, "reason": "invalid_weights"}), 400 + # Fail closed BEFORE consuming the ticket: this legacy prototype must not + # enroll miners unless explicitly opted in (see module docstring). + try: + _require_legacy_settlement() + except LegacySettlementDisabled as exc: + return _legacy_disabled_response(exc) + # Enroll # Consume ticket after all request validation so malformed requests do not # burn a valid ticket before the miner can retry. if not consume_ticket(ticket_id): return jsonify({"ok": False, "reason": "ticket_invalid"}), 400 - enroll_epoch(epoch, miner_pk, total_weight) + try: + enroll_epoch(epoch, miner_pk, total_weight) + except LegacySettlementDisabled as exc: + return _legacy_disabled_response(exc) return jsonify({ "ok": True, @@ -598,12 +687,21 @@ def api_submit_block(): return jsonify({"error": "invalid_slot"}), 400 epoch = slot_to_epoch(slot) + # Fail closed before any epoch rollover (settlement) or block accounting. + try: + _require_legacy_settlement() + except LegacySettlementDisabled as exc: + return _legacy_disabled_response(exc) + if LAST_EPOCH is None: LAST_EPOCH = epoch if epoch != LAST_EPOCH: # Finalize previous epoch - result = finalize_epoch(LAST_EPOCH, PER_BLOCK_RTC) + try: + result = finalize_epoch(LAST_EPOCH, PER_BLOCK_RTC) + except LegacySettlementDisabled as exc: + return _legacy_disabled_response(exc) print(f"Finalized epoch {LAST_EPOCH}: {result}") # Broadcast epoch settlement event via WebSocket (Issue #2295) @@ -621,7 +719,10 @@ def api_submit_block(): LAST_EPOCH = epoch # Add block to current epoch - inc_epoch_block(epoch) + try: + inc_epoch_block(epoch) + except LegacySettlementDisabled as exc: + return _legacy_disabled_response(exc) # Update block hash payload = json.dumps({"header": header, "ext": ext}, sort_keys=True).encode() @@ -677,7 +778,10 @@ def get_hardware_tier(fingerprint): return "Unknown" if __name__ == "__main__": - init_db() + try: + init_db() + except LegacySettlementDisabled as exc: + raise SystemExit(f"[sophia_elya_service] refusing to start: {exc}") print("RustChain v2 RIP-0005 - Epoch Pro-Rata Rewards") print(f"Block Time: {BLOCK_TIME}s, Reward: {PER_BLOCK_RTC} RTC per block") print(f"Epoch Length: {EPOCH_SLOTS} blocks ({EPOCH_SLOTS * BLOCK_TIME // 3600}h)") diff --git a/node/sybil_guard.py b/node/sybil_guard.py new file mode 100644 index 000000000..8f122d467 --- /dev/null +++ b/node/sybil_guard.py @@ -0,0 +1,1217 @@ +# SPDX-License-Identifier: MIT +"""sybil_guard -- new-miner probation for the RIP-200 attestation node. + +Incident 2026-09-24: 120 fresh wallets from 3 source IPs attested as PowerPC G4 +with fingerprint_passed=1. Each was paid the 0.5 RTC welcome bonus on its first +attestation and auto-enrolled at 1.75x (the 2.5x G4 tier, halved by +TEMPORAL_UNVERIFIED_BONUS_FRACTION because it had <3 samples). The existing +temporal review could not stop it: it scores a miner against its OWN history, +and a brand-new identity has none, so "insufficient_history" still paid half +the vintage premium, and the welcome bonus never consulted it at all. + +Design (Scott's intent): trust is EARNED by showing natural, evolving entropy +over time, not by a single snapshot. + + GRANDFATHER Any miner with at least one attestation before + GRANDFATHER_CUTOFF_TS keeps today's behaviour exactly (weight, + bonus rule). Honest legacy clients (Python 2.3/2.5 Macs, the lab + G4 client's constant 0.0123/0/0/2.0) must not be punished. The + only exception is REVIEW below. + ADMISSION A first-seen miner is admitted to probation at most + NEW_MINERS_PER_IP_PER_DAY per source /32 (IPv6 /64) per 24h. + Excess identities are ADMISSION-QUEUED: enrollment weight 0 and + no probation clock until admitted; retried on every attestation. + PROBATION No welcome bonus; enrollment weight capped at + PROBATION_WEIGHT_CAP. Exit needs PROBATION_MIN_ATTESTATIONS + fingerprint-passing attestations over >= PROBATION_MIN_SPAN_HOURS + in >= PROBATION_MIN_DISTINCT_HOURS distinct hours; at least + PROBATION_MIN_VARIED_SUBMISSIONS submissions that moved; every + required metric (judged over the whole window) moved in at least + METRIC_MIN_MOVES submissions; a thermal series that is not a + memoryless redraw; no anomaly in the last + ANOMALY_PROBATION_EXTENSION_HOURS; and not part of a correlated + same-/24 cluster of new identities (RIP-309d). + EXIT CAP At most NEW_MINER_EXITS_PER_PREFIX_PER_HOUR exits per /24 (IPv6 + /48) -- counted on the miner's ADMISSION prefix and on the + current request prefix -- and NEW_MINER_EXITS_GLOBAL_PER_HOUR + overall; excess -> QUEUED. The bonus is paid at exit. + REVIEW A sticky needs_review flag -- set from the live profile, from any + STORED fingerprint-history profile, or from membership in the + operator's incident cohort table -- holds enrollment and + settlement weight at 0 for every state, grandfathered included. + The would-be weight is recorded in sybil_review_escrow. Escrow is + a record of WEIGHT, not reserved funds (see record_review_escrow). + +What this can NOT prove: every metric is self-reported JSON. A careful +adversary can emit a slowly drifting random walk at realistic precision from +many residential IPs and wait out probation. This converts "one POST = 1.75x + +0.5 RTC" into "sustained, varied, non-anomalous behaviour for a day per +identity, throttled per IP, per /24 and per hour" -- a cost, not a proof. + +Schema: tables are created ONCE at node startup (init_schema). Request and +settlement paths never run DDL. Pure-Python and Flask-free. +""" + +import ipaddress +import json +import logging +import math +import os +import sqlite3 +import statistics +import time + +log = logging.getLogger("sybil_guard") + +# --------------------------------------------------------------------------- +# Constants (reasoning for each value is in NOTES.md) +# --------------------------------------------------------------------------- + +#: N -- fingerprint-passing attestations required before probation can end. +PROBATION_MIN_ATTESTATIONS = 8 +#: H -- first-to-latest span. 24h = one diurnal/thermal cycle and one epoch, so +#: a wave cannot reach vintage weight or the bonus in the epoch it appears. +PROBATION_MIN_SPAN_HOURS = 24 +#: Distinct UTC hour-buckets the counted attestations must fall in, so the span +#: cannot be met by one attestation, a 24h wait, then a burst. +PROBATION_MIN_DISTINCT_HOURS = 6 +#: Submissions whose profile moved materially vs the previous submission. +PROBATION_MIN_VARIED_SUBMISSIONS = 3 +#: Distinct metrics that must have moved, capped at the number of metrics the +#: miner reported non-zero at ANY point in its probation window (a clock-only +#: Cobalt Qube cannot move four; dropping metrics on the last sample does not +#: lower the requirement). +PROBATION_MIN_VARIED_METRICS = 2 +#: A metric counts as varied only if it moved in at least this many submissions, +#: so one wiggle is not enough. +METRIC_MIN_MOVES = 2 +#: Relative change that counts as "moved". Honest G5s move cache_hierarchy_ratio +#: by ~5e-5 relative between samples (1e-4 would block 3/12 honest miners); +#: the Sybil generator re-sent byte-identical values. +VARIATION_MIN_REL_CHANGE = 1e-5 +#: An anomalous submission pushes the earliest possible exit this far out. +ANOMALY_PROBATION_EXTENSION_HOURS = 48 + +#: Enrollment weight cap while in probation. 1.0 is the baseline the existing +#: apply_temporal_consistency_to_weight already treats as the floor; min() only, +#: so a miner already below it (x86_64 0.8, aarch64 0.0005) is untouched. +PROBATION_WEIGHT_CAP = 1.0 + +#: Admission: first-time identities per exact source address per rolling 24h. +NEW_MINERS_PER_IP_PER_DAY = 2 +#: Exit caps (the only route to vintage weight + bonus for a new miner). +NEW_MINER_EXITS_PER_PREFIX_PER_HOUR = 2 +NEW_MINER_EXITS_GLOBAL_PER_HOUR = 12 +IPV4_ADMISSION_PREFIX_LEN = 32 +IPV6_ADMISSION_PREFIX_LEN = 64 +IPV4_PREFIX_LEN = 24 +IPV6_PREFIX_LEN = 48 + +#: A graduated (non-grandfathered, non-allowlisted) miner earns a multiplier +#: above PROBATION_WEIGHT_CAP only when its latest attestation carried a +#: RIP-309c measurement binding in state "bound". +#: 2026-09-24: Scott chose False -- probation alone gates new vintage premium. +#: The binding is client-reported (duration_ns) and forgeable, so do not treat +#: "bound" as proof if this is ever re-enabled. +REQUIRE_MEASUREMENT_BINDING_FOR_NEW_PREMIUM = False + +#: 2026-09-24T00:00:00Z -- before the first Sybil submission (18:43Z). ANY +#: attestation before it grandfathers the miner (round-2 decision). +GRANDFATHER_CUTOFF_TS = 1790208000 + +#: Operator-recorded incident cohort (node table). Membership -> needs_review. +#: Optional: if the table is absent, nothing is flagged from it. +INCIDENT_COHORT_TABLE = "sybil_cohort_20260924" +_COHORT_ID_COLUMNS = ("miner", "miner_id", "miner_pk", "wallet", "wallet_id", "address") + +#: Operator escape hatch: comma-separated miner ids that skip probation (e.g. a +#: NEW lab machine running a static-profile legacy client). +PROBATION_ALLOWLIST_ENV = "RC_PROBATION_ALLOWLIST" + +TEMPORAL_METRICS = ( + "clock_drift_cv", + "thermal_variance", + "jitter_cv", + "cache_hierarchy_ratio", +) + +#: Empirical upper bounds from honest_profiles.json (maxima 2.3689 / 3.0611 / +#: 0.6464 / 4.0) plus ~14-30% margin. Upper bounds only: honest miners send 0.0 +#: for what they cannot measure, and the low tails overlap the attack range. +ANOMALY_RANGE_MAX = { + "clock_drift_cv": 3.0, + "thermal_variance": 3.5, + "jitter_cv": 0.8, + "cache_hierarchy_ratio": 5.0, +} + +#: Fixed-precision signature: all four metrics non-zero, none with more than +#: FIXED_PRECISION_MAX_DECIMALS decimals, and at least FIXED_PRECISION_MIN_AT_MAX +#: of them at exactly that many. Honest producers mix precisions. +FIXED_PRECISION_MAX_DECIMALS = 4 +FIXED_PRECISION_MIN_AT_MAX = 1 + +#: 2026-09-24 generator box (min/max of the 136 Sybil rows). With "all +#: non-zero and <= 4 decimals" it is the needs_review signature. +INCIDENT_20260924_BOX = { + # Widened 2026-09-25 to the generator's likely bounds (Scott-approved): + # wave 1 (120 wallets) + wave 2 (24 wallets) observed extremes were + # clock 0.0080-0.0299, thermal 0.8123-5.9022, jitter 0.0153-0.2473, + # cache 1.8034-2.8961; each edge rounded OUTWARD to the nearest plausible + # round(uniform(lo, hi), 4) bound. The old box was fit to wave-1 min/max and + # missed 4/24 wave-2 wallets sitting just outside it. + "clock_drift_cv": (0.008, 0.030), + "thermal_variance": (0.8, 6.0), + "jitter_cv": (0.015, 0.25), + "cache_hierarchy_ratio": (1.8, 2.9), +} + +#: A grandfathered (pre-cutoff) miner is put in needs_review from its stored +#: history only when at least this many stored profiles match the incident +#: signature (round-2 FP guard). Cohort membership flags on its own. New +#: miners flag on a single match. +GRANDFATHERED_MIN_STORED_MATCHES = 2 + +#: Memoryless-redraw test on the slow metric (honest median relative step +#: <= 0.154; independent redraws ~0.38). +SHAPE_MAX_MEDIAN_STEP = {"thermal_variance": 0.25} +SHAPE_MIN_STEPS = 3 + +STATE_GRANDFATHERED = "grandfathered" +STATE_TRUSTED = "trusted" +STATE_PROBATION = "probation" +STATE_QUEUED = "queued" # exit-eligible, over the exit cap +STATE_ADMISSION_QUEUED = "admission_queued" # over the first-seen admission cap +STATE_UNAVAILABLE = "unavailable" # classification failed + +ESTABLISHED_STATES = frozenset({STATE_GRANDFATHERED, STATE_TRUSTED}) + +REVIEW_LIVE = "incident_20260924_signature" +REVIEW_STORED = "incident_20260924_signature_stored_history" +REVIEW_COHORT = "incident_20260924_cohort" + + +class SchemaError(RuntimeError): + """miner_probation / sybil_review_escrow exist but do not match this code.""" + + +# --------------------------------------------------------------------------- +# Pure helpers +# --------------------------------------------------------------------------- + +def _as_float(value): + try: + f = float(value) + except (TypeError, ValueError): + return 0.0 + if not math.isfinite(f): + return 0.0 + return f + + +def normalize_profile(profile): + """Return {metric: float} for the four temporal metrics (missing -> 0.0).""" + p = profile if isinstance(profile, dict) else {} + return {m: _as_float(p.get(m, 0.0)) for m in TEMPORAL_METRICS} + + +def decimal_digits(value): + """Decimal digits in the shortest repr of a float (0.0 -> 0, sci -> 99).""" + s = repr(float(value)) + if "e" in s or "E" in s: + return 99 + if "." not in s: + return 0 + frac = s.split(".", 1)[1] + return 0 if frac == "0" else len(frac) + + +def _all_short_nonzero(p): + return all(p[m] > 0 for m in TEMPORAL_METRICS) and all( + decimal_digits(p[m]) <= FIXED_PRECISION_MAX_DECIMALS for m in TEMPORAL_METRICS) + + +def profile_anomalies(profile): + """Anomaly flags for ONE incoming profile. They extend probation only.""" + p = normalize_profile(profile) + flags = [] + for metric, upper in ANOMALY_RANGE_MAX.items(): + if p[metric] > upper: + flags.append(f"out_of_range:{metric}") + if _all_short_nonzero(p): + at_max = sum(1 for m in TEMPORAL_METRICS + if decimal_digits(p[m]) == FIXED_PRECISION_MAX_DECIMALS) + if at_max >= FIXED_PRECISION_MIN_AT_MAX: + flags.append("fixed_precision_signature") + return flags + + +def matches_incident_signature(profile): + """2026-09-24 generator: all non-zero, <= 4 decimals, inside the box.""" + p = normalize_profile(profile) + if not _all_short_nonzero(p): + return False + return all(lo <= p[m] <= hi for m, (lo, hi) in INCIDENT_20260924_BOX.items()) + + +def varied_metrics(previous, current): + """Metrics that moved by >= VARIATION_MIN_REL_CHANGE between two samples. + A metric that is 0.0 on either side is ignored ("could not measure").""" + if previous is None: + return [] + a, b = normalize_profile(previous), normalize_profile(current) + return [m for m in TEMPORAL_METRICS + if a[m] > 0 and b[m] > 0 + and abs(b[m] - a[m]) / max(a[m], b[m]) >= VARIATION_MIN_REL_CHANGE] + + +def _rel_steps(values): + return [abs(y - x) / max(x, y) for x, y in zip(values, values[1:]) + if x > 0 and y > 0 and x != y] + + +def shape_blockers(profiles): + """Memoryless-redraw test over the retained sequence (probation exit only).""" + seq = [normalize_profile(p) for p in profiles] + out = [] + for metric, limit in SHAPE_MAX_MEDIAN_STEP.items(): + steps = _rel_steps([p[metric] for p in seq]) + if len(steps) >= SHAPE_MIN_STEPS and statistics.median(steps) > limit: + out.append(f"memoryless_redraw:{metric}") + return out + + +def lag1_autocorrelation(values): + xs = [v for v in values if v > 0] + if len(xs) < 4: + return None + mean = sum(xs) / len(xs) + den = sum((x - mean) ** 2 for x in xs) + if den == 0: + return None + return sum((xs[i] - mean) * (xs[i + 1] - mean) for i in range(len(xs) - 1)) / den + + +def _pearson(xs, ys): + n = len(xs) + if n < 4: + return None + mx, my = sum(xs) / n, sum(ys) / n + sxx = sum((x - mx) ** 2 for x in xs) + syy = sum((y - my) ** 2 for y in ys) + if sxx == 0 or syy == 0: + return None + return sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / (sxx * syy) ** 0.5 + + +def shape_scores(profiles): + """Informational only (NOT gates): lag-1 autocorrelation and co-movement. + + The consensus proposed gating on lag-1 autocorrelation in [0.2, 0.95]; on + honest_profiles.json that gate would block most honest miners (NOTES.md). + """ + seq = [normalize_profile(p) for p in profiles] + scores = {} + for m in ("thermal_variance", "clock_drift_cv"): + ac = lag1_autocorrelation([p[m] for p in seq]) + scores[f"lag1_{m}"] = None if ac is None else round(ac, 4) + pairs = [(p["thermal_variance"], p["cache_hierarchy_ratio"]) for p in seq + if p["thermal_variance"] > 0 and p["cache_hierarchy_ratio"] > 0] + corr = _pearson([a for a, _ in pairs], [b for _, b in pairs]) + scores["comove_thermal_cache"] = None if corr is None else round(corr, 4) + return scores + + +def _ip(ip): + try: + addr = ipaddress.ip_address(str(ip or "").strip()) + except ValueError: + return None + if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped: + addr = addr.ipv4_mapped + return addr + + +def _net(ip, v4len, v6len): + addr = _ip(ip) + if addr is None: + return "unknown" + plen = v4len if addr.version == 4 else v6len + return str(ipaddress.ip_network(f"{addr}/{plen}", strict=False)) + + +def source_prefix(ip): + """Group a source address by /24 (IPv4) or /48 (IPv6).""" + return _net(ip, IPV4_PREFIX_LEN, IPV6_PREFIX_LEN) + + +def admission_key(ip): + """Exact source for admission (/32); IPv6 grouped by /64.""" + return _net(ip, IPV4_ADMISSION_PREFIX_LEN, IPV6_ADMISSION_PREFIX_LEN) + + +def probation_allowlist(): + raw = os.environ.get(PROBATION_ALLOWLIST_ENV, "") + return {x.strip() for x in raw.split(",") if x.strip()} + + +def is_in_probation(status): + """True when vintage weight and the welcome bonus must be withheld. + Fail closed: a missing/garbled status counts as probation.""" + if not isinstance(status, dict): + return True + return status.get("state") not in ESTABLISHED_STATES + + +def needs_review(status): + """Sticky incident hold. Applies to every state, grandfathered included.""" + return isinstance(status, dict) and bool(status.get("needs_review")) + + +def should_defer_enrollment(status): + """True only when the database could not even be opened for + classification (fallback_status(None, ...)). Then the enrollment write + would almost certainly fail too; the next attestation retries. + + Round 2b: an error in the establishment QUERY (e.g. a schema surprise) + does NOT defer -- that would turn one bad column into a 503 for every + miner. It falls back to today's (live) weight instead; see + fallback_status.""" + return (isinstance(status, dict) + and status.get("state") == STATE_UNAVAILABLE + and bool(status.get("db_unreachable"))) + + +def enrollment_weight(hw_weight, status): + """Apply the guard to an enrollment weight (already temporal-adjusted). + + needs_review (any state) -> 0.0 (caller records escrow) + grandfathered -> unchanged (today's behaviour) + unavailable, established True or unknown -> unchanged (live behaviour; + never reduce on an error) + admission_queued -> 0.0 (not admitted yet) + probation/queued/other -> min(weight, PROBATION_WEIGHT_CAP) + trusted (graduated) -> unchanged, unless + REQUIRE_MEASUREMENT_BINDING_FOR_NEW_PREMIUM + Never raises a weight. + """ + try: + weight = float(hw_weight) + except (TypeError, ValueError): + return hw_weight + if needs_review(status): + return 0.0 + if not isinstance(status, dict): + return min(weight, PROBATION_WEIGHT_CAP) + state = status.get("state") + if state == STATE_GRANDFATHERED: + return weight + if state == STATE_UNAVAILABLE and status.get("established", False) is not False: + return weight + if state == STATE_ADMISSION_QUEUED: + return 0.0 + if state != STATE_TRUSTED: + return min(weight, PROBATION_WEIGHT_CAP) + if (status.get("reason") != "operator_allowlist" + and REQUIRE_MEASUREMENT_BINDING_FOR_NEW_PREMIUM + and status.get("last_binding_state") != "bound"): + return min(weight, PROBATION_WEIGHT_CAP) + return weight + + +def unguarded_status(status): + """The same status with the review hold removed: used to compute the + would-be weight that is escrowed for a held miner.""" + if not isinstance(status, dict): + return status + out = dict(status) + out["needs_review"] = 0 + return out + + +# --------------------------------------------------------------------------- +# Persistence -- schema is created/verified ONCE at startup (init_schema) +# --------------------------------------------------------------------------- + +_COLUMNS = ( + "miner", "state", "reason", "first_seen", "admitted_at", "admit_key", + "last_seen", "attest_count", "distinct_hours", "last_hour_bucket", + "varied_count", "metric_moves", "metrics_seen", "last_profile_json", + "anomaly_count", "last_anomaly_ts", "last_anomaly_flags", "needs_review", + "review_reason", "first_prefix", "exit_prefix", "exit_current_prefix", "exited_at", + "last_binding_state", "updated_at", +) +_JSON_COLUMNS = {"metric_moves": dict, "metrics_seen": list} +_ESCROW_COLUMNS = ("epoch", "miner", "would_be_weight_units", "reason", "created_at") +SCHEMA_VERSION = 2 + + +def _create_tables(conn): + conn.execute( + """ + CREATE TABLE IF NOT EXISTS miner_probation ( + miner TEXT PRIMARY KEY, + state TEXT NOT NULL, + reason TEXT, + first_seen INTEGER NOT NULL, + admitted_at INTEGER, + admit_key TEXT, + last_seen INTEGER NOT NULL, + attest_count INTEGER NOT NULL DEFAULT 0, + distinct_hours INTEGER NOT NULL DEFAULT 0, + last_hour_bucket INTEGER, + varied_count INTEGER NOT NULL DEFAULT 0, + metric_moves TEXT NOT NULL DEFAULT '{}', + metrics_seen TEXT NOT NULL DEFAULT '[]', + last_profile_json TEXT, + anomaly_count INTEGER NOT NULL DEFAULT 0, + last_anomaly_ts INTEGER, + last_anomaly_flags TEXT, + needs_review INTEGER NOT NULL DEFAULT 0, + review_reason TEXT, + first_prefix TEXT, + exit_prefix TEXT, + exit_current_prefix TEXT, + exited_at INTEGER, + last_binding_state TEXT, + updated_at INTEGER NOT NULL + ) + """ + ) + conn.execute( + """ + CREATE TABLE IF NOT EXISTS sybil_review_escrow ( + epoch INTEGER NOT NULL, + miner TEXT NOT NULL, + would_be_weight_units INTEGER NOT NULL, + reason TEXT, + created_at INTEGER NOT NULL, + PRIMARY KEY (epoch, miner) + ) + """ + ) + + +def _create_indexes(conn): + conn.execute("CREATE INDEX IF NOT EXISTS idx_mp_exit ON miner_probation(exited_at, exit_prefix)") + conn.execute("CREATE INDEX IF NOT EXISTS idx_mp_exit_cur ON miner_probation(exited_at, exit_current_prefix)") + conn.execute("CREATE INDEX IF NOT EXISTS idx_mp_admit ON miner_probation(admit_key, admitted_at)") + conn.execute("CREATE INDEX IF NOT EXISTS idx_mp_prefix ON miner_probation(first_prefix)") + + +def verify_schema(conn): + """Return a list of problems (empty == compatible). Read-only.""" + problems = [] + for table, cols in (("miner_probation", _COLUMNS), ("sybil_review_escrow", _ESCROW_COLUMNS)): + have = {r[1] for r in conn.execute(f"PRAGMA table_info({table})").fetchall()} # fetchall-ok: pragma-result + if not have: + problems.append(f"{table}: missing") + continue + missing = [c for c in cols if c not in have] + if missing: + problems.append(f"{table}: missing columns {missing}") + return problems + + +def init_schema(db_path_or_conn): + """Create (if absent) and verify the guard tables. Call ONCE at startup. + + Raises SchemaError if an existing table is incompatible: CREATE TABLE IF + NOT EXISTS does not upgrade a table, and running the node with a guard + that cannot read its own state would silently degrade (fail loudly). + """ + own = isinstance(db_path_or_conn, str) + conn = sqlite3.connect(db_path_or_conn, timeout=30) if own else db_path_or_conn + try: + _create_tables(conn) + conn.commit() + problems = verify_schema(conn) + if problems: + raise SchemaError("; ".join(problems)) + _create_indexes(conn) + conn.commit() + finally: + if own: + conn.close() + + +def ensure_probation_tables(conn): + """Startup-only (tests/tools): create tables and indexes, no verification.""" + _create_tables(conn) + _create_indexes(conn) + + +def _table_exists(conn, name): + return conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,) + ).fetchone() is not None + + +def has_pre_cutoff_history(conn, miner, cutoff=None): + """True if the miner attested at least once before the cutoff. + + Returns False when the history table does not exist (fresh DB). + Raises on other DB errors so callers can tell "unknown" from "no". + """ + cutoff = GRANDFATHER_CUTOFF_TS if cutoff is None else cutoff + if not _table_exists(conn, "miner_attest_history"): + return False + cols = {r[1] for r in conn.execute("PRAGMA table_info(miner_attest_history)").fetchall()} # fetchall-ok: pragma-result + if not {"miner", "ts_ok"} <= cols: + raise SchemaError(f"miner_attest_history lacks miner/ts_ok (has {sorted(cols)})") + return conn.execute( + "SELECT 1 FROM miner_attest_history WHERE miner = ? AND ts_ok < ? LIMIT 1", + (miner, int(cutoff)), + ).fetchone() is not None + + +# Kept for callers/tests written against round 1. +is_established_before_cutoff = has_pre_cutoff_history + + +class CohortUndeterminable(RuntimeError): + """The cohort table exists but membership cannot be determined.""" + + +def _cohort_members(conn, miners, strict=False): + """Subset of `miners` listed in the incident cohort table. + + Three cases (round 3b): + (a) table ABSENT -> authoritative empty set. POLICY: the cohort table is + a one-off, operator-created record of the 2026-09-24 incident; a DB + that never had it (fresh node, other environments) has no cohort. + Dropping it is an explicit operator decision, not a fault. + (b) table PRESENT with a recognised id column (_COHORT_ID_COLUMNS) -> + normal membership check. + (c) table PRESENT but no recognised id column -> UNDETERMINABLE: + strict=True raises CohortUndeterminable (money paths withhold); + strict=False logs CRITICAL and returns an empty set (callers that can + only ADD holds). Read errors (sqlite3.Error) always propagate. + """ + miners = [m for m in (miners or []) if m] + if not miners or not _table_exists(conn, INCIDENT_COHORT_TABLE): + return set() + cols = [r[1] for r in conn.execute(f"PRAGMA table_info({INCIDENT_COHORT_TABLE})").fetchall()] # fetchall-ok: pragma-result + col = next((c for c in _COHORT_ID_COLUMNS if c in cols), None) + if col is None: + msg = (f"{INCIDENT_COHORT_TABLE} has no recognised id column {list(_COHORT_ID_COLUMNS)} " + f"(has {cols}); cohort membership UNDETERMINABLE") + if strict: + raise CohortUndeterminable(msg) + log.critical("[SYBIL-GUARD] %s", msg) + return set() + out = set() + for i in range(0, len(miners), 500): + chunk = miners[i:i + 500] + rows = conn.execute( + f"SELECT {col} FROM {INCIDENT_COHORT_TABLE} WHERE {col} IN " + f"({', '.join('?' for _ in chunk)})", chunk).fetchall() # fetchall-ok: already-paginated (chunked IN, <=500 ids) + out.update(r[0] for r in rows) + return out + + +def _cohort_member_safe(conn, miner): + """Cohort membership for one miner; absent/unreadable table -> False + (logged). Used on hot paths that must not raise.""" + try: + return bool(_cohort_members(conn, [miner])) + except sqlite3.Error as exc: + log.critical("[SYBIL-GUARD] cohort lookup failed for %s: %s (no cohort flag added)", + str(miner)[:20], exc) + return False + + +def bonus_eligibility_in_txn(conn, miner): + """Authorise the welcome bonus INSIDE the caller's write transaction. + + Re-reads the PERSISTED miner_probation row and the CURRENT incident-cohort + membership on `conn` (which must already hold BEGIN IMMEDIATE), so a hold + committed after the attestation's observation but before payment is seen. + Returns (eligible: bool, state_or_None, why: str). Fails closed: any + uncertainty -> not eligible (the bonus stays unpaid and retryable). + """ + try: + if not _table_exists(conn, "miner_probation"): + return False, None, "no_probation_table" + row = conn.execute( + "SELECT state, needs_review FROM miner_probation WHERE miner = ?", (miner,)).fetchone() + if row is None: + return False, None, "no_probation_row" + state, nr = row[0], int(row[1] or 0) + if nr: + return False, state, "needs_review" + if state not in ESTABLISHED_STATES: + return False, state, f"state:{state}" + # Cohort: absent table -> no cohort (policy, see _cohort_members); + # present-but-malformed or unreadable -> undeterminable -> withhold. + try: + if _cohort_members(conn, [miner], strict=True): + return False, state, "cohort_member" + except (CohortUndeterminable, sqlite3.Error) as exc: + log.critical("[SYBIL-GUARD] welcome bonus WITHHELD for %s: cohort membership " + "undeterminable (%s); retryable", str(miner)[:20], exc) + return False, state, f"cohort_undeterminable:{exc}" + return True, state, "ok" + except Exception as exc: # noqa: BLE001 - cannot determine -> withhold + log.error("[SYBIL-GUARD] bonus eligibility undeterminable for %s: %s", str(miner)[:20], exc) + return False, None, f"undeterminable:{exc}" + + +def fetch_profiles(conn, miner): + if not _table_exists(conn, "miner_fingerprint_history"): + return [] + out = [] + for (pj,) in conn.execute( + "SELECT profile_json FROM miner_fingerprint_history WHERE miner = ? ORDER BY ts ASC, id ASC", + (miner,), + ).fetchall(): # fetchall-ok: bounded-by-schema (<=10 rows/miner, TEMPORAL_HISTORY_LIMIT) + try: + out.append(normalize_profile(json.loads(pj or "{}"))) + except (TypeError, ValueError): + continue + return out + + +def stored_review_reason(conn, miner, grandfathered=False): + """needs_review reason from STORED data (cohort table, stored history), or + None. Cohort membership flags on its own. Stored history flags on one + matching profile for a new miner, on >= GRANDFATHERED_MIN_STORED_MATCHES + for a grandfathered one. Fail-safe: an unreadable cohort table is logged + and skipped.""" + try: + if _cohort_members(conn, [miner]): + return REVIEW_COHORT + except sqlite3.Error as exc: + log.error("[SYBIL-GUARD] cohort lookup failed for %s: %s", str(miner)[:20], exc) + need = GRANDFATHERED_MIN_STORED_MATCHES if grandfathered else 1 + matches = sum(1 for p in fetch_profiles(conn, miner) if matches_incident_signature(p)) + if matches >= need: + return REVIEW_STORED + return None + + +def _set_review(st, reason): + """Set the sticky flag; CRITICAL when it lands on a grandfathered miner + (an established miner going to weight 0 must never be silent).""" + st["needs_review"], st["review_reason"] = 1, reason + if st.get("state") == STATE_GRANDFATHERED: + log.critical("[SYBIL-GUARD] GRANDFATHERED miner %s put in needs_review (%s) -- weight 0 " + "until an operator clears miner_probation.needs_review", st.get("miner"), reason) + + +def _load(conn, miner): + row = conn.execute( + f"SELECT {', '.join(_COLUMNS)} FROM miner_probation WHERE miner = ?", (miner,) + ).fetchone() + if not row: + return None + st = dict(zip(_COLUMNS, row)) + for col, typ in _JSON_COLUMNS.items(): + raw = st.get(col) + try: + val = json.loads(raw) if raw is not None else None + except (TypeError, ValueError): + val = None + if col == "metrics_seen": + # falsegreen fix: NULL/unreadable is "no record", which must NOT + # relax the varied-metric requirement (see required_varied_metrics). + st[col] = val if isinstance(val, list) else None + else: + st[col] = val if isinstance(val, typ) else typ() + return st + + +def _save(conn, st): + cols = [c for c in _COLUMNS if c != "miner"] + vals = [json.dumps(st[c]) if c in _JSON_COLUMNS else st.get(c) for c in cols] + conn.execute( + f"INSERT INTO miner_probation (miner, {', '.join(cols)}) " + f"VALUES (?, {', '.join('?' for _ in cols)}) ON CONFLICT(miner) DO UPDATE SET " + + ", ".join(f"{c}=excluded.{c}" for c in cols), + [st["miner"]] + vals, + ) + + +def _admission_full(conn, key, now): + if key == "unknown": + return False + n = conn.execute( + "SELECT COUNT(*) FROM miner_probation WHERE admit_key = ? AND admitted_at >= ? " + "AND state NOT IN (?, ?)", + (key, int(now) - 86400, STATE_GRANDFATHERED, STATE_ADMISSION_QUEUED), + ).fetchone()[0] + return n >= NEW_MINERS_PER_IP_PER_DAY + + +def required_varied_metrics(st): + """Varied metrics required to exit probation. + + A REAL metrics_seen list relaxes the requirement to what the miner can + measure (a Cobalt Qube reporting only clock -> 1). A missing/None record + is not evidence of a limited device: require the full + PROBATION_MIN_VARIED_METRICS (fail closed; falsegreen FG005 fix). + """ + seen = st.get("metrics_seen") + if not isinstance(seen, list): + return PROBATION_MIN_VARIED_METRICS + return max(1, min(PROBATION_MIN_VARIED_METRICS, len(seen))) + + +def counted_varied_metrics(st): + """Metrics that moved often enough. A missing record counts as NONE moved, + which blocks exit (fail closed), never as a pass.""" + moves = st.get("metric_moves") + if not isinstance(moves, dict): + return [] + return sorted(m for m, n in moves.items() if int(n) >= METRIC_MIN_MOVES) + + +def _exit_blockers(st, now): + blockers = [] + if st["attest_count"] < PROBATION_MIN_ATTESTATIONS: + blockers.append(f"attestations:{st['attest_count']}/{PROBATION_MIN_ATTESTATIONS}") + start = st.get("admitted_at") or st["first_seen"] + span_h = (int(now) - int(start)) / 3600.0 + if span_h < PROBATION_MIN_SPAN_HOURS: + blockers.append(f"span_hours:{span_h:.1f}/{PROBATION_MIN_SPAN_HOURS}") + if int(st.get("distinct_hours") or 0) < PROBATION_MIN_DISTINCT_HOURS: + blockers.append(f"distinct_hours:{st.get('distinct_hours')}/{PROBATION_MIN_DISTINCT_HOURS}") + if st["varied_count"] < PROBATION_MIN_VARIED_SUBMISSIONS: + blockers.append(f"varied_submissions:{st['varied_count']}/{PROBATION_MIN_VARIED_SUBMISSIONS}") + need = required_varied_metrics(st) + have = len(counted_varied_metrics(st)) + if have < need: + blockers.append(f"varied_metrics:{have}/{need}") + if st.get("last_anomaly_ts") is not None: + until = int(st["last_anomaly_ts"]) + ANOMALY_PROBATION_EXTENSION_HOURS * 3600 + if int(now) < until: + blockers.append(f"anomaly_extension_until:{until}") + if st.get("needs_review"): + blockers.append(f"needs_review:{st.get('review_reason')}") + return blockers + + +def _cap_blockers(conn, prefixes, now): + since = int(now) - 3600 + out = [] + for prefix in sorted({p for p in prefixes if p and p != "unknown"}): + # Round 3: an exit is charged to BOTH its admission prefix and the + # prefix it graduated from. OR (not a sum) so an exit whose two + # prefixes are identical is counted once. + n = conn.execute( + "SELECT COUNT(*) FROM miner_probation WHERE exited_at >= ? " + "AND (exit_prefix = ? OR exit_current_prefix = ?)", + (since, prefix, prefix), + ).fetchone()[0] + if n >= NEW_MINER_EXITS_PER_PREFIX_PER_HOUR: + out.append(f"prefix_cap:{prefix}:{n}/{NEW_MINER_EXITS_PER_PREFIX_PER_HOUR}") + global_n = conn.execute( + "SELECT COUNT(*) FROM miner_probation WHERE exited_at >= ? AND exit_prefix IS NOT NULL", + (since,), + ).fetchone()[0] + if global_n >= NEW_MINER_EXITS_GLOBAL_PER_HOUR: + out.append(f"global_cap:{global_n}/{NEW_MINER_EXITS_GLOBAL_PER_HOUR}") + return out + + +def _cluster_blockers(conn, st, cluster_check): + """RIP-309d: new identities from the same /24 must look independent.""" + if cluster_check is None or st.get("first_prefix") in (None, "unknown"): + return [] + peers = [r[0] for r in conn.execute( + "SELECT miner FROM miner_probation WHERE first_prefix = ? AND state != ? " + "AND COALESCE(reason, '') != 'operator_allowlist' ORDER BY first_seen DESC LIMIT 200", + (st["first_prefix"], STATE_GRANDFATHERED), + ).fetchall()] # fetchall-ok: already-paginated (LIMIT 200) + members = list(dict.fromkeys([st["miner"]] + peers)) + try: + verdict = cluster_check(conn, members) + except Exception as exc: + # falsegreen fix: an unavailable check must not ALLOW exit. Blocking + # only delays graduation (weight stays <= PROBATION_WEIGHT_CAP). + log.error("cluster_check failed for %s: %s", st.get("miner"), exc) + return [f"cluster_check_unavailable:{type(exc).__name__}"] + if not isinstance(verdict, dict) or not verdict: + log.error("cluster_check returned no verdict for %s: %r", st.get("miner"), verdict) + return ["cluster_check_unavailable:empty_verdict"] + if verdict.get("state") == "correlated": + return [f"cluster_correlated:{st['first_prefix']}:spread={verdict.get('spread')}"] + return [] + + +def _new_row(conn, miner, prefix, akey, now): + if miner in probation_allowlist(): + state, reason = STATE_TRUSTED, "operator_allowlist" + elif has_pre_cutoff_history(conn, miner): + state, reason = STATE_GRANDFATHERED, "attested_before_cutoff" + elif _admission_full(conn, akey, now): + state, reason = STATE_ADMISSION_QUEUED, f"admission_cap:{akey}" + else: + state, reason = STATE_PROBATION, "new_miner" + review = stored_review_reason(conn, miner, grandfathered=(state == STATE_GRANDFATHERED)) + row = { + "miner": miner, "state": state, "reason": reason, "first_seen": int(now), + "admitted_at": int(now) if state == STATE_PROBATION else None, + "admit_key": akey, "last_seen": int(now), "attest_count": 0, + "distinct_hours": 0, "last_hour_bucket": None, "varied_count": 0, + "metric_moves": {}, "metrics_seen": [], "last_profile_json": None, + "anomaly_count": 0, "last_anomaly_ts": None, "last_anomaly_flags": None, + "needs_review": 0, "review_reason": None, + "first_prefix": prefix, "exit_prefix": None, "exit_current_prefix": None, "exited_at": None, + "last_binding_state": None, "updated_at": int(now), + } + if review: + _set_review(row, review) + return row + + +def observe_attestation(conn, miner, profile, source_ip, now=None, + fingerprint_passed=True, binding_state=None, + cluster_check=None): + """Record one attestation and advance the miner's probation state. + + Call AFTER record_attestation_success (so miner_fingerprint_history holds + this profile) and BEFORE the welcome bonus / auto-enroll. Runs under BEGIN + IMMEDIATE so admission and exit caps are counted atomically across gunicorn + workers; `conn` must be opened with isolation_level=None. No DDL: the + tables must exist (init_schema at startup); a missing table raises and the + caller's error boundary takes over. + + On a miner's first observation, needs_review is seeded from STORED data + (incident cohort table, stored fingerprint history), so an identity cannot + shed the flag by no longer sending the incident profile. + """ + now = int(time.time() if now is None else now) + prof = normalize_profile(profile) + prefix = source_prefix(source_ip) + akey = admission_key(source_ip) + anomalies = profile_anomalies(prof) + incident = matches_incident_signature(prof) + + conn.execute("BEGIN IMMEDIATE") + try: + st = _load(conn, miner) or _new_row(conn, miner, prefix, akey, now) + just_exited = False + blockers = [] + + # Round 3: cohort membership is evaluated on EVERY observation, so a + # wallet added to the cohort table after its row exists is held too. + if not st.get("needs_review") and _cohort_member_safe(conn, miner): + _set_review(st, REVIEW_COHORT) + if not st.get("needs_review"): + if st["state"] == STATE_GRANDFATHERED: + # One live match is not enough for an established miner: it + # must repeat (>= GRANDFATHERED_MIN_STORED_MATCHES stored + # samples; this attestation is already stored) or be in the + # cohort table. + if incident: + review = stored_review_reason(conn, miner, grandfathered=True) + if review: + _set_review(st, review) + elif incident: + _set_review(st, REVIEW_LIVE) + + if st["state"] == STATE_ADMISSION_QUEUED and not _admission_full(conn, st["admit_key"], now): + st["state"], st["reason"], st["admitted_at"] = STATE_PROBATION, "admitted", now + + st["last_binding_state"] = binding_state + if st["state"] in (STATE_PROBATION, STATE_QUEUED): + if fingerprint_passed: + try: + prev = json.loads(st.get("last_profile_json") or "null") + except (TypeError, ValueError): + prev = None + moved = varied_metrics(prev, prof) + st["attest_count"] = int(st["attest_count"]) + 1 + bucket = now // 3600 + if st.get("last_hour_bucket") != bucket: + st["distinct_hours"] = int(st.get("distinct_hours") or 0) + 1 + st["last_hour_bucket"] = bucket + if moved: + st["varied_count"] = int(st["varied_count"]) + 1 + moves = dict(st.get("metric_moves") or {}) + for m in moved: + moves[m] = int(moves.get(m, 0)) + 1 + st["metric_moves"] = moves + st["metrics_seen"] = sorted(set(st.get("metrics_seen") or ()) + | {m for m in TEMPORAL_METRICS if prof[m] > 0}) + st["last_profile_json"] = json.dumps(prof, separators=(",", ":")) + if anomalies: + st["anomaly_count"] = int(st.get("anomaly_count") or 0) + 1 + st["last_anomaly_ts"] = now + st["last_anomaly_flags"] = json.dumps(anomalies) + + blockers = _exit_blockers(st, now) + if not fingerprint_passed: + blockers.append("fingerprint_failed") + if not blockers: + blockers = shape_blockers(fetch_profiles(conn, miner)) + if not blockers: + blockers = _cluster_blockers(conn, st, cluster_check) + if not blockers: + cap = _cap_blockers(conn, [st.get("first_prefix"), prefix], now) + if cap: + st["state"], st["reason"] = STATE_QUEUED, cap[0] + blockers = cap + else: + st["state"], st["reason"] = STATE_TRUSTED, "probation_exit" + # Exit is charged to the ADMISSION prefix, so leaving from a + # different /24 does not dodge that prefix's cap. + st["exited_at"] = now + st["exit_prefix"] = st.get("first_prefix") or prefix + st["exit_current_prefix"] = prefix + just_exited = True + else: + st["reason"] = blockers[0] + if st["state"] == STATE_QUEUED: + st["state"] = STATE_PROBATION + elif st["state"] == STATE_ADMISSION_QUEUED: + blockers = [st["reason"]] + else: + # Grandfathered / trusted: today's behaviour; just track. + st["attest_count"] = int(st["attest_count"]) + 1 + if st.get("needs_review"): + blockers = [f"needs_review:{st.get('review_reason')}"] + + st["last_seen"] = st["updated_at"] = now + _save(conn, st) + conn.execute("COMMIT") + except Exception: + conn.execute("ROLLBACK") + raise + + st.update({ + "in_probation": st["state"] not in ESTABLISHED_STATES, + "just_exited": just_exited, + "anomalies": anomalies, + "incident_signature": incident, + "blockers": blockers, + }) + return st + + +def get_probation_status(conn, miner, now=None): + """Read-only status for /epoch/enroll. Never writes. + + A miner without a row is classified on the fly (allowlist, pre-cutoff + history, stored-data review) so a Sybil that enrolls without attesting + after deploy is still held. Unknown new miner -> probation (fail closed). + """ + if _table_exists(conn, "miner_probation"): + st = _load(conn, miner) + if st is not None: + st["in_probation"] = st["state"] not in ESTABLISHED_STATES + # Round 3: pick up cohort membership added after the row existed + # (read-only; the next attestation persists it). + if not st.get("needs_review") and _cohort_member_safe(conn, miner): + st["needs_review"], st["review_reason"] = 1, REVIEW_COHORT + if st["state"] == STATE_GRANDFATHERED: + log.critical("[SYBIL-GUARD] GRANDFATHERED miner %s held at enrollment (%s)", + miner, REVIEW_COHORT) + return st + if miner in probation_allowlist(): + state, reason = STATE_TRUSTED, "operator_allowlist" + elif has_pre_cutoff_history(conn, miner): + state, reason = STATE_GRANDFATHERED, "attested_before_cutoff" + else: + state, reason = STATE_PROBATION, "no_probation_row" + review = stored_review_reason(conn, miner, grandfathered=(state == STATE_GRANDFATHERED)) + if review and state == STATE_GRANDFATHERED: + log.critical("[SYBIL-GUARD] GRANDFATHERED miner %s held at enrollment (%s)", miner, review) + return {"miner": miner, "state": state, "reason": reason, + "needs_review": 1 if review else 0, "review_reason": review, + "in_probation": state not in ESTABLISHED_STATES} + + +def fallback_status(conn, miner): + """Status to use when observe_attestation / get_probation_status failed. + + Never raises. Enrollment never REDUCES an established miner's weight + because of an error: + established True -> today's (live) weight + established False -> probation cap (a known-new miner) + established None -> the history query failed: today's (live) weight, + logged CRITICAL (fail to live behaviour, not to a + 503 for every miner) + conn None -> database unreachable: enrollment deferred + Stored-data review (cohort / stored history) is still applied if readable. + """ + if conn is None: + return {"miner": miner, "state": STATE_UNAVAILABLE, "reason": "db_unreachable", + "established": None, "db_unreachable": True, "in_probation": True} + try: + established = has_pre_cutoff_history(conn, miner) + except Exception as exc: # noqa: BLE001 - classification must never raise + log.critical("[SYBIL-GUARD] establishment check failed for %s (%s): using LIVE " + "weight behaviour for this enrollment", str(miner)[:20], exc) + established = None + review = None + try: + review = stored_review_reason(conn, miner, grandfathered=established is not False) + except Exception as exc: # noqa: BLE001 + log.error("[SYBIL-GUARD] stored review lookup failed for %s: %s", str(miner)[:20], exc) + return {"miner": miner, "state": STATE_UNAVAILABLE, "reason": "classification_failed", + "established": established, "db_unreachable": False, + "needs_review": 1 if review else 0, "review_reason": review, "in_probation": True} + + +def record_review_escrow(conn, epoch, miner, would_be_weight_units, reason, now=None): + """Record what a held miner would have been weighted at (first wins). + + ESCROW IS A RECORD OF WEIGHT, NOT RESERVED FUNDS. The held miner's share of + the epoch pot is redistributed to the other miners at settlement; nothing + is set aside. Restoring a wrongly-held miner means an operator transfer + from a founder/ops wallet sized from these rows -- a manual payment, not a + release. No DDL here (table created at startup). + """ + conn.execute( + "INSERT OR IGNORE INTO sybil_review_escrow " + "(epoch, miner, would_be_weight_units, reason, created_at) VALUES (?, ?, ?, ?, ?)", + (int(epoch), miner, int(would_be_weight_units), reason, + int(time.time() if now is None else now)), + ) + + +def record_review_escrow_safe(conn, epoch, miner, would_be_weight_units, reason, now=None): + """record_review_escrow inside a SAVEPOINT; never raises (settlement path). + + The escrow row is an audit record: failing to write it must not abort or + poison the caller's settlement transaction.""" + try: + conn.execute("SAVEPOINT sybil_escrow") + except Exception as exc: # noqa: BLE001 + log.error("[SYBIL-GUARD] escrow savepoint failed for %s: %s", str(miner)[:20], exc) + return False + try: + record_review_escrow(conn, epoch, miner, would_be_weight_units, reason, now=now) + conn.execute("RELEASE sybil_escrow") + return True + except Exception as exc: # noqa: BLE001 + try: + conn.execute("ROLLBACK TO sybil_escrow") + conn.execute("RELEASE sybil_escrow") + except Exception: # noqa: BLE001 + pass + log.error("[SYBIL-GUARD] escrow write failed for %s epoch %s: %s", + str(miner)[:20], epoch, exc) + return False + + +def hold_for_settlement(conn, epoch, miners, weights=None, record=True, + reason="settlement_hold"): + """Held subset of `miners` for this settlement; optionally escrows each + held miner's positive would-be weight on `conn` (the settlement + transaction). Never raises. + + `weights`: {miner: weight_units}, or a zero-argument callable returning + one. A callable is evaluated INSIDE this guard: if the weight read fails, + the hold is still applied (held miners still settle at 0) and only the + escrow record is skipped, logged. The caller's PAYOUT weights are read + separately and stay fail-loud.""" + held = settlement_held_miners(conn, miners, epoch) + if record and held and callable(weights): + try: + weights = weights() + except Exception as exc: # noqa: BLE001 + log.error("[SYBIL-GUARD] epoch %s: escrow weight read failed (%s); hold applied, " + "escrow rows NOT written", epoch, exc) + weights = None + record = False + if record and held: + for m in held: + w = (weights or {}).get(m) + try: + units = int(w) if w is not None else 0 + except (TypeError, ValueError): + units = 0 + if units > 0: + record_review_escrow_safe(conn, epoch, m, units, reason) + if held: + log.warning("[SYBIL-GUARD] epoch %s: %d needs_review miner(s) held at 0", epoch, len(held)) + return held + + +def review_held_miners(conn, miners): + """Subset of `miners` flagged needs_review in miner_probation or listed in + the incident cohort table. Read-only. Raises on DB errors; settlement code + must use settlement_held_miners, which never raises.""" + miners = [m for m in (miners or []) if m] + if not miners: + return set() + held = set() + if _table_exists(conn, "miner_probation"): + for i in range(0, len(miners), 500): + chunk = miners[i:i + 500] + rows = conn.execute( + "SELECT miner FROM miner_probation WHERE needs_review = 1 " + f"AND miner IN ({', '.join('?' for _ in chunk)})", + chunk, + ).fetchall() # fetchall-ok: already-paginated (chunked IN, <=500 ids) + held.update(r[0] for r in rows) + else: + log.critical("[SYBIL-GUARD] miner_probation table does not exist -- no probation holds " + "applied (expected only before the guarded node has started once)") + # Round 3b: a malformed/unreadable cohort table must not discard the + # needs_review holds already collected above (it can only ADD holds). + try: + held |= _cohort_members(conn, miners) + except sqlite3.Error as exc: + log.critical("[SYBIL-GUARD] cohort table unreadable at settlement (%s); " + "applying miner_probation holds only", exc) + return held + + +def settlement_held_miners(conn, miners, epoch=None): + """Settlement-safe hold lookup. NEVER raises. + + Order of evidence: + 1. miner_probation needs_review + incident cohort (review_held_miners). + 2. On a DB error: miners with a sybil_review_escrow row for this epoch + (written when the hold was applied at enrollment). + 3. If that fails too: empty set, logged CRITICAL. Settlement then pays + the stored epoch_enroll weights, which are already 0 for every miner + held at enrollment time; only a miner flagged after enrolling (at a + probation-capped weight) would be paid. Settlement is never halted. + """ + try: + return review_held_miners(conn, miners) + except Exception as exc: # noqa: BLE001 + log.critical("[SYBIL-GUARD] settlement hold lookup failed (%s); falling back to escrow rows", exc) + try: + if epoch is None: + return set() + miners = [m for m in (miners or []) if m] + held = set() + for i in range(0, len(miners), 500): + chunk = miners[i:i + 500] + rows = conn.execute( + "SELECT miner FROM sybil_review_escrow WHERE epoch = ? " + f"AND miner IN ({', '.join('?' for _ in chunk)})", + [int(epoch)] + chunk, + ).fetchall() # fetchall-ok: already-paginated (chunked IN, <=500 ids) + held.update(r[0] for r in rows) + return held + except Exception as exc: # noqa: BLE001 + log.critical("[SYBIL-GUARD] escrow fallback failed too (%s); settling on stored " + "enrollment weights only", exc) + return set() + + +def public_status(status): + """Compact, non-sensitive view for the /attest/submit response.""" + if not isinstance(status, dict): + return {"state": STATE_UNAVAILABLE} + return { + "state": status.get("state"), + "attestations": status.get("attest_count"), + "varied_submissions": status.get("varied_count"), + "blockers": list(status.get("blockers") or [])[:6], + "requirements": { + "attestations": PROBATION_MIN_ATTESTATIONS, + "span_hours": PROBATION_MIN_SPAN_HOURS, + "distinct_hours": PROBATION_MIN_DISTINCT_HOURS, + "varied_submissions": PROBATION_MIN_VARIED_SUBMISSIONS, + "varied_metrics": PROBATION_MIN_VARIED_METRICS, + "moves_per_metric": METRIC_MIN_MOVES, + }, + } diff --git a/node/test_c8_adm_double_credit_poc.py b/node/test_c8_adm_double_credit_poc.py index 1ece270fc..5f79a9ce2 100644 --- a/node/test_c8_adm_double_credit_poc.py +++ b/node/test_c8_adm_double_credit_poc.py @@ -1,20 +1,12 @@ #!/usr/bin/env python3 # SPDX-License-Identifier: MIT """ -PoC: Epoch settlement double-credit bug (C8) - -Demonstrates that when anti-double-mining settlement writes rewards but -then raises an exception, the fallback to standard rewards on the same -database connection results in double-crediting miners. - -Bug chain in rewards_implementation_rip200.py settle_epoch_rip200(): -1. Calls settle_epoch_with_anti_double_mining(existing_conn=db) -2. That function writes rewards + marks epoch_state on the SHARED conn -3. If it crashes AFTER writing rewards (e.g. in telemetry or metadata), - the exception is caught at line 175 -4. NO rollback is issued on the shared conn -5. Standard rewards fallback writes miners AGAIN on the same conn -6. Both sets committed at db.commit() → double-credit +Regression Test: Epoch settlement double-credit on ADM failure (C8) + +Demonstrates and verifies that when anti-double-mining settlement writes +partial rewards on the shared connection and then raises an exception, +settle_epoch_rip200() issues a db.rollback() before proceeding to the +standard fallback path, preventing duplicate credit to miners. """ import os @@ -30,9 +22,6 @@ sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) -# We'll construct the scenario manually since importing the live module -# requires Flask and database setup - class TestEpochSettlementDoubleCredit(unittest.TestCase): """Verify that ADM failure fallback does NOT double-credit miners.""" @@ -81,49 +70,83 @@ def _init_db(self): def test_double_credit_on_adm_fallback(self): """ - Simulate: anti-double-mining writes rewards, then raises. - Standard fallback writes rewards on same connection. - Result should be a SINGLE credit per miner, not double. + Verify settle_epoch_rip200 rolls back partial ADM writes before standard fallback. + When ADM writes partial rewards on the shared connection and then raises, + settle_epoch_rip200 must roll back those uncommitted writes so that the + standard path produces a single credit, not double. """ PER_EPOCH_URTC = 1_500_000 - - conn = sqlite3.connect(self.db_path) - conn.execute("BEGIN IMMEDIATE") - - # Phase 1: Simulate ADM writes (rewards credited) - conn.execute( - "INSERT INTO balances (miner_id, amount_i64) VALUES (?, ?) " - "ON CONFLICT(miner_id) DO UPDATE SET amount_i64 = amount_i64 + ?", - ("RTC_miner_a", PER_EPOCH_URTC, PER_EPOCH_URTC), - ) - # Mark epoch_state (ADM writes this) - conn.execute( - "UPDATE epoch_state SET settled = 1, settled_ts = ? WHERE epoch = ?", - (int(time.time()), 1), - ) - - # ADM crashes AFTER writes (before telemetry/metadata lines) - # We simulate this by raising - the caller catches and falls through - - # Phase 2: Standard rewards fallback (same connection, no rollback) - conn.execute( - "INSERT INTO balances (miner_id, amount_i64) VALUES (?, ?) " - "ON CONFLICT(miner_id) DO UPDATE SET amount_i64 = amount_i64 + ?", - ("RTC_miner_a", PER_EPOCH_URTC, PER_EPOCH_URTC), - ) - - bal = conn.execute( - "SELECT amount_i64 FROM balances WHERE miner_id = ?", - ("RTC_miner_a",), - ).fetchone() - conn.close() - - # BUG: If both writes took effect, balance = 2 * PER_EPOCH_URTC - self.assertEqual( - bal[0], PER_EPOCH_URTC, - f"BALANCE: {bal[0]} uRTC — expected {PER_EPOCH_URTC} uRTC" - f"\n{'🔴 BUG: DOUBLE CREDIT — fallback wrote on top of ADM writes!' if bal[0] != PER_EPOCH_URTC else '✅ Single credit only'}" - ) + EPOCH = 0 + + import node.rewards_implementation_rip200 as rip200 + + orig_adm_avail = rip200.ANTI_DOUBLE_MINING_AVAILABLE + orig_adm_fn = getattr(rip200, "settle_epoch_with_anti_double_mining", None) + orig_calc = rip200.calculate_epoch_rewards_time_aged + orig_age = rip200.get_chain_age_years + orig_mult = rip200.get_time_aged_multiplier + + rip200.ANTI_DOUBLE_MINING_AVAILABLE = True + + def crashing_adm(db_path, epoch, budget, current_slot, existing_conn=None): + # Simulate ADM writing partial rewards to the shared connection, then crashing + conn = existing_conn if existing_conn is not None else sqlite3.connect(db_path) + conn.execute( + "INSERT INTO balances (miner_id, amount_i64) VALUES (?, ?) " + "ON CONFLICT(miner_id) DO UPDATE SET amount_i64 = amount_i64 + ?", + ("RTC_miner_a", PER_EPOCH_URTC, PER_EPOCH_URTC), + ) + conn.execute( + "INSERT INTO ledger (ts, epoch, miner_id, delta_i64, reason) VALUES (?, ?, ?, ?, ?)", + (int(time.time()), epoch, "RTC_miner_a", PER_EPOCH_URTC, "adm_partial_write"), + ) + raise RuntimeError("simulated ADM crash after partial write") + + rip200.settle_epoch_with_anti_double_mining = crashing_adm + rip200.calculate_epoch_rewards_time_aged = lambda *_a, **_k: {"RTC_miner_a": PER_EPOCH_URTC} + rip200.get_chain_age_years = lambda *_a, **_k: 1.0 + rip200.get_time_aged_multiplier = lambda *_a, **_k: 1.0 + + try: + # Under RC_REQUIRE_ADM=0 (fallback enabled), settle_epoch_rip200 must rollback + # the crashing ADM partial write and credit exactly once via standard path. + old_req = os.environ.get("RC_REQUIRE_ADM") + os.environ["RC_REQUIRE_ADM"] = "0" + try: + res = rip200.settle_epoch_rip200(self.db_path, epoch=EPOCH) + finally: + if old_req is None: + os.environ.pop("RC_REQUIRE_ADM", None) + else: + os.environ["RC_REQUIRE_ADM"] = old_req + + self.assertTrue(res.get("ok"), f"settlement failed: {res}") + + conn = sqlite3.connect(self.db_path) + bal = conn.execute( + "SELECT amount_i64 FROM balances WHERE miner_id = ?", + ("RTC_miner_a",), + ).fetchone() + ledger_rows = conn.execute( + "SELECT delta_i64, reason FROM ledger WHERE epoch = ?", + (EPOCH,), + ).fetchall() + conn.close() + + self.assertIsNotNone(bal, "miner balance row missing") + self.assertEqual( + bal[0], PER_EPOCH_URTC, + f"BALANCE: {bal[0]} uRTC — expected {PER_EPOCH_URTC} uRTC (single credit only)", + ) + # Ensure the ADM partial ledger write was rolled back and only standard remains + self.assertEqual(len(ledger_rows), 1, f"expected 1 ledger row, got {ledger_rows}") + self.assertEqual(ledger_rows[0][1], f"epoch_{EPOCH}_reward") + finally: + rip200.ANTI_DOUBLE_MINING_AVAILABLE = orig_adm_avail + rip200.settle_epoch_with_anti_double_mining = orig_adm_fn + rip200.calculate_epoch_rewards_time_aged = orig_calc + rip200.get_chain_age_years = orig_age + rip200.get_time_aged_multiplier = orig_mult if __name__ == '__main__': diff --git a/node/test_rollback_atomicity.py b/node/test_rollback_atomicity.py index 46d497976..ab377c079 100644 --- a/node/test_rollback_atomicity.py +++ b/node/test_rollback_atomicity.py @@ -443,5 +443,65 @@ def test_10_rollback_refuses_after_non_genesis_state_exists(self): conn.close() + +class TestRollbackClearsMirrorProvenance(unittest.TestCase): + """#2819 (Ondrej Nad): rollback must also remove account_mirror_boxes rows.""" + + setUp = TestRollbackAtomicity.setUp + tearDown = TestRollbackAtomicity.tearDown + + def _mirror_count(self): + conn = sqlite3.connect(self.db_path) + try: + return conn.execute("SELECT COUNT(*) FROM account_mirror_boxes").fetchone()[0] + finally: + conn.close() + + def test_rollback_removes_mirror_rows(self): + migrate(self.db_path, dry_run=False) + self.assertGreater(self._mirror_count(), 0) + rollback_genesis(self.db_path, admin_key=self.admin_key) + self.assertEqual(self._mirror_count(), 0) + + def test_rollback_also_clears_preexisting_orphans(self): + migrate(self.db_path, dry_run=False) + conn = sqlite3.connect(self.db_path) + conn.execute( + "INSERT INTO account_mirror_boxes (box_id, account_wallet, value_nrtc, created_epoch) " + "VALUES ('stale-box-from-earlier-run', 'wallet_a', 1, 0)" + ) + conn.commit(); conn.close() + rollback_genesis(self.db_path, admin_key=self.admin_key) + self.assertEqual(self._mirror_count(), 0) + + def test_rollback_without_genesis_leaves_mirror_rows_alone(self): + migrate(self.db_path, dry_run=False) + rollback_genesis(self.db_path, admin_key=self.admin_key) + conn = sqlite3.connect(self.db_path) + conn.execute( + "INSERT INTO account_mirror_boxes (box_id, account_wallet, value_nrtc, created_epoch) " + "VALUES ('live-dual-write-box', 'wallet_a', 1, 5)" + ) + conn.commit(); conn.close() + rollback_genesis(self.db_path, admin_key=self.admin_key) # no genesis now + self.assertEqual(self._mirror_count(), 1) + + def test_remigration_after_balance_change_leaves_no_orphans(self): + migrate(self.db_path, dry_run=False) + rollback_genesis(self.db_path, admin_key=self.admin_key) + conn = sqlite3.connect(self.db_path) + conn.execute("UPDATE balances SET amount_i64 = amount_i64 + 1") + conn.commit(); conn.close() + migrate(self.db_path, dry_run=False) + conn = sqlite3.connect(self.db_path) + try: + orphans = conn.execute( + "SELECT COUNT(*) FROM account_mirror_boxes m " + "WHERE NOT EXISTS (SELECT 1 FROM utxo_boxes b WHERE b.box_id = m.box_id)" + ).fetchone()[0] + finally: + conn.close() + self.assertEqual(orphans, 0) + if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/node/test_utxo_db.py b/node/test_utxo_db.py index d6564ba7d..063c5b335 100644 --- a/node/test_utxo_db.py +++ b/node/test_utxo_db.py @@ -659,6 +659,45 @@ def test_integrity_mismatch(self): self.assertFalse(result['ok']) self.assertFalse(result['models_agree']) + def test_integrity_flags_non_positive_box_despite_matching_total(self): + self.db.add_box({ + 'box_id': 'good', 'value_nrtc': 200 * UNIT, 'proposition': '00', + 'owner_address': 'alice', 'creation_height': 1, + 'transaction_id': '11' * 32, 'output_index': 1, + }) + insert = """INSERT INTO utxo_boxes + (box_id, value_nrtc, proposition, owner_address, + creation_height, transaction_id, output_index, created_at) + VALUES (?, ?, '00', 'alice', 1, ?, ?, 0)""" + conn = self.db._conn() + conn.execute(insert, ('neg', -50 * UNIT, '11' * 32, 0)) + conn.commit() + result = self.db.integrity_check(expected_total=150 * UNIT) + self.assertTrue(result['models_agree']) + self.assertFalse(result['ok']) + self.assertEqual(result['invalid_value_boxes'], 1) + + conn.execute(insert, ('frac', 1.5, '11' * 32, 2)) + conn.commit() + conn.close() + self.assertEqual(self.db.integrity_check()['invalid_value_boxes'], 2) + + def test_add_box_rejects_invalid_value(self): + base = { + 'proposition': '00', 'owner_address': 'alice', + 'creation_height': 1, 'transaction_id': '11' * 32, + } + for i, bad in enumerate([-50, 0, '100', 1.5, True, 2 ** 63]): + with self.subTest(value=bad): + with self.assertRaises(ValueError): + self.db.add_box({**base, 'box_id': f'bad{i}', + 'value_nrtc': bad, 'output_index': i}) + self.assertEqual(self.db.get_balance('alice'), 0) + self.db.add_box({**base, 'box_id': 'good', + 'value_nrtc': 200, 'output_index': 99}) + self.assertEqual(self.db.get_balance('alice'), 200) + self.assertTrue(self.db.integrity_check(expected_total=200)['ok']) + # -- mempool ------------------------------------------------------------- def test_mempool_add_and_remove(self): @@ -2165,6 +2204,42 @@ def test_invalid_tx_type_rejected(self): self.assertEqual(self.db.get_balance('alice'), 100 * UNIT) self.assertEqual(self.db.get_balance('bob'), 0) + def test_mempool_rejects_duplicate_inputs(self): + """Mempool must cleanly reject transactions with duplicate input box_ids.""" + self._apply_coinbase('alice', 100 * UNIT) + boxes = self.db.get_unspent_for_address('alice') + box_id = boxes[0]['box_id'] + + tx = { + 'tx_id': 'dupe' * 16, + 'tx_type': 'transfer', + 'inputs': [{'box_id': box_id}, {'box_id': box_id}], + 'outputs': [{'address': 'bob', 'value_nrtc': 100 * UNIT}], + 'fee_nrtc': 0, + } + ok = self.db.mempool_add(tx) + self.assertFalse(ok) + # Verify no inputs or transactions were orphaned into mempool tables + self.assertFalse(self.db.mempool_check_double_spend(box_id)) + self.assertEqual(len(self.db.mempool_get_block_candidates()), 0) + + def test_mempool_rejects_invalid_timestamp_with_rollback(self): + """Mempool must rollback when rejecting an invalid negative timestamp.""" + self._apply_coinbase('alice', 100 * UNIT) + boxes = self.db.get_unspent_for_address('alice') + + tx = { + 'tx_id': 'time' * 16, + 'tx_type': 'transfer', + 'inputs': [{'box_id': boxes[0]['box_id']}], + 'outputs': [{'address': 'bob', 'value_nrtc': 100 * UNIT}], + 'fee_nrtc': 0, + 'timestamp': -1, + } + ok = self.db.mempool_add(tx) + self.assertFalse(ok) + self.assertFalse(self.db.mempool_check_double_spend(boxes[0]['box_id'])) + class TestCoinSelect(unittest.TestCase): diff --git a/node/test_utxo_dualwrite_receiver_provenance.py b/node/test_utxo_dualwrite_receiver_provenance.py new file mode 100644 index 000000000..ab15a0fac --- /dev/null +++ b/node/test_utxo_dualwrite_receiver_provenance.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Regression test for the danaher-j #2819 RECEIVER-provenance double-spend. + +Under UTXO_DUAL_WRITE=1, `balances` (account) is the primary ledger and UTXO +boxes are its shadow; `account_mirror_boxes` records which boxes back account +value, with the invariant `mirror <= balance`. A /utxo/transfer credits the +receiver's account balance AND creates a spendable UTXO output box for the +receiver. If that output is NOT registered as account-mirror provenance, the +same value is spendable via BOTH models (UTXO + account) = double spend. + +Fix: the dual-write path registers the transfer's output boxes into +account_mirror_boxes, so the unconditional mirror-input exclusion blocks +re-spending them via the UTXO path (value must move via the account path). +""" +import os +import sqlite3 +import sys +import tempfile +import time +import unittest + +from flask import Flask + +NODE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) +if NODE_DIR not in sys.path: + sys.path.insert(0, NODE_DIR) + +import utxo_endpoints +from utxo_db import UtxoDB, UNIT +from utxo_endpoints import ( + register_utxo_blueprint, + _selected_account_mirror_boxes, + _spendable_utxo_candidates, +) + + +# Canonical recipient: /utxo/transfer format-checks to_address (lower-case RTC + 40 hex) +# since #8396/#8465, so a bare name like 'bob' is now rejected with 400. +RECIPIENT = 'RTC' + 'b' * 40 + +def _mock_verify_sig(pubkey_hex, message, sig_hex): + return True + + +def _mock_addr_from_pk(pubkey_hex): + return 'RTC_test_aabbccdd' + + +def _mock_current_slot(): + return 42 + + +class TestDualWriteReceiverProvenance(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.NamedTemporaryFile(suffix='.db', delete=False) + self.tmp.close() + self.db_path = self.tmp.name + + conn = sqlite3.connect(self.db_path) + conn.execute("CREATE TABLE IF NOT EXISTS balances (miner_id TEXT PRIMARY KEY, amount_i64 INTEGER DEFAULT 0)") + conn.execute("CREATE TABLE IF NOT EXISTS ledger (ts INTEGER, epoch INTEGER, miner_id TEXT, delta_i64 INTEGER, reason TEXT)") + conn.commit() + conn.close() + + self.utxo_db = UtxoDB(self.db_path) + self.utxo_db.init_tables() + + self.app = Flask(__name__) + self.app.config['TESTING'] = True + register_utxo_blueprint( + self.app, self.utxo_db, self.db_path, + verify_sig_fn=_mock_verify_sig, + addr_from_pk_fn=_mock_addr_from_pk, + current_slot_fn=_mock_current_slot, + dual_write=True, + ) + self.client = self.app.test_client() + + def tearDown(self): + try: + os.unlink(self.db_path) + except OSError: + pass + + def _seed(self, address, rtc): + """Give `address` both a spendable UTXO box and a matching account balance + (a fully-migrated wallet: mirror == balance is maintained elsewhere; here + the seeded box is independent UTXO, i.e. NOT yet a mirror).""" + self.utxo_db.apply_transaction({ + 'tx_type': 'mining_reward', 'inputs': [], + 'outputs': [{'address': address, 'value_nrtc': rtc * UNIT}], + 'timestamp': int(time.time()), '_allow_minting': True, + }, block_height=1) + conn = sqlite3.connect(self.db_path) + conn.execute("INSERT INTO balances (miner_id, amount_i64) VALUES (?, ?)", + (address, rtc * utxo_endpoints.ACCOUNT_UNIT)) + conn.commit() + conn.close() + + def _transfer(self, sender, recipient, amount_rtc, nonce): + return self.client.post('/utxo/transfer', json={ + 'from_address': sender, 'to_address': recipient, + 'amount_rtc': amount_rtc, 'public_key': 'aabbccdd' * 8, + 'signature': 'sig' * 22, 'nonce': nonce, 'memo': 'x', + }) + + def test_receiver_output_is_registered_as_mirror(self): + sender, recipient = 'RTC_test_aabbccdd', RECIPIENT + self._seed(sender, 100) + + r = self._transfer(sender, recipient, 10.0, 700001) + self.assertEqual(r.status_code, 200, r.get_json()) + + conn = sqlite3.connect(self.db_path) + conn.row_factory = sqlite3.Row + try: + # Receiver account credited (the single spendable form). + bal = conn.execute("SELECT amount_i64 FROM balances WHERE miner_id=?", (recipient,)).fetchone() + self.assertIsNotNone(bal) + self.assertEqual(bal['amount_i64'], 10 * utxo_endpoints.ACCOUNT_UNIT) + + # Receiver's NEW output box must now be account-mirror provenance. + recv_boxes = conn.execute( + "SELECT box_id, value_nrtc FROM utxo_boxes WHERE owner_address=? AND spent_at IS NULL", + (recipient,), + ).fetchall() + self.assertEqual(len(recv_boxes), 1) + mirror = conn.execute( + "SELECT box_id FROM account_mirror_boxes WHERE account_wallet=?", (recipient,) + ).fetchall() + mirror_ids = {m['box_id'] for m in mirror} + self.assertIn(recv_boxes[0]['box_id'], mirror_ids, + "receiver output box was NOT registered as account-mirror (danaher #2819 residual)") + + # Therefore it is excluded from UTXO coin-selection (cannot be UTXO-spent). + excluded = _selected_account_mirror_boxes(conn, [dict(box_id=recv_boxes[0]['box_id'])]) + self.assertEqual(excluded, [recv_boxes[0]['box_id']]) + finally: + conn.close() + + def test_receiver_box_is_not_utxo_spendable(self): + """The value the receiver got is spendable via the ACCOUNT path only: its + UTXO output box is now mirror-tagged, so UTXO coin-selection excludes it + entirely — the receiver cannot re-spend it through /utxo/transfer, which + is exactly what closes the double-spend.""" + sender, recipient = 'RTC_test_aabbccdd', RECIPIENT + self._seed(sender, 100) + self.assertEqual(self._transfer(sender, recipient, 10.0, 700001).status_code, 200) + + conn = sqlite3.connect(self.db_path) + conn.row_factory = sqlite3.Row + try: + recv_boxes = [dict(r) for r in conn.execute( + "SELECT * FROM utxo_boxes WHERE owner_address=? AND spent_at IS NULL", + (recipient,), + ).fetchall()] + self.assertEqual(len(recv_boxes), 1) + spendable, mirrored = _spendable_utxo_candidates(conn, recv_boxes) + self.assertEqual(spendable, [], "receiver box is UTXO-spendable — double-spend open") + self.assertEqual(mirrored, [recv_boxes[0]['box_id']]) + finally: + conn.close() + + def test_invariant_holds_after_transfer(self): + sender, recipient = 'RTC_test_aabbccdd', RECIPIENT + self._seed(sender, 100) + self.assertEqual(self._transfer(sender, recipient, 10.0, 700001).status_code, 200) + + conn = sqlite3.connect(self.db_path) + try: + nrtc_per_account = UNIT // utxo_endpoints.ACCOUNT_UNIT + for w in (sender, recipient): + mirror = conn.execute( + "SELECT COALESCE(SUM(b.value_nrtc),0) FROM utxo_boxes b " + "JOIN account_mirror_boxes m ON m.box_id=b.box_id " + "WHERE m.account_wallet=? AND b.spent_at IS NULL", (w,)).fetchone()[0] + brow = conn.execute("SELECT amount_i64 FROM balances WHERE miner_id=?", (w,)).fetchone() + bal_nrtc = (brow[0] if brow else 0) * nrtc_per_account + self.assertLessEqual(int(mirror), bal_nrtc, f"mirror>balance for {w} (double-spend condition)") + finally: + conn.close() + + +if __name__ == '__main__': + unittest.main() diff --git a/node/test_utxo_dualwrite_reward_provenance.py b/node/test_utxo_dualwrite_reward_provenance.py new file mode 100644 index 000000000..f6a2e5652 --- /dev/null +++ b/node/test_utxo_dualwrite_reward_provenance.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: MIT +"""Regression coverage for the epoch mining-reward mirror-provenance fix +(danaher-j #2819, same class as the /utxo/transfer receiver residual). + +Under UTXO_DUAL_WRITE=1, epoch settlement credits each miner's ACCOUNT balance +AND mints a UTXO reward box for them. If that box is not registered in +account_mirror_boxes, the same reward is spendable via BOTH models (UTXO box + +account balance) = double spend. The fix (a) makes account_mirror_boxes canonical +UTXO schema, and (b) registers each reward box in finalize_epoch's dual-write +batch loop. + +These tests avoid the expensive full-settlement harness (as the existing +test_epoch_utxo_dual_write_guard.py does for finalize_epoch) and instead cover: + 1. init_tables now creates account_mirror_boxes (schema), + 2. a registered reward box is excluded from UTXO spendable candidates + (the mechanism that closes the double-spend), and + 3. finalize_epoch wires the registration into the dual-write path (source/AST). +""" +import ast +import os +import sqlite3 +import sys +import tempfile +import time +import unittest +from pathlib import Path + +NODE_DIR = os.path.abspath(os.path.dirname(__file__)) +if NODE_DIR not in sys.path: + sys.path.insert(0, NODE_DIR) + +from utxo_db import UtxoDB, UNIT +from utxo_endpoints import _spendable_utxo_candidates + +SERVER_PATH = Path(NODE_DIR) / "rustchain_v2_integrated_v2.2.1_rip200.py" + + +class TestRewardProvenanceSchemaAndMechanism(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.NamedTemporaryFile(suffix='.db', delete=False) + self.tmp.close() + self.db_path = self.tmp.name + self.db = UtxoDB(self.db_path) + self.db.init_tables() + + def tearDown(self): + try: + os.unlink(self.db_path) + except OSError: + pass + + def test_init_tables_creates_account_mirror_boxes(self): + conn = sqlite3.connect(self.db_path) + try: + row = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='account_mirror_boxes'" + ).fetchone() + self.assertIsNotNone(row, "init_tables must create account_mirror_boxes (canonical schema)") + finally: + conn.close() + + def test_registered_reward_box_is_not_utxo_spendable(self): + """A minted reward box that IS registered as mirror provenance must be + excluded from UTXO coin-selection — so the reward can only move via the + account path, closing the double-spend.""" + miner = 'miner-reward-1' + height = 42 * 144 # epoch*EPOCH_SLOTS style height + # Mint a reward box exactly as finalize_epoch does (mining_reward, minting). + self.db.apply_transaction({ + 'tx_type': 'mining_reward', 'inputs': [], + 'outputs': [{'address': miner, 'value_nrtc': 5 * UNIT}], + 'timestamp': int(time.time()), '_allow_minting': True, + }, block_height=height) + + conn = sqlite3.connect(self.db_path) + conn.row_factory = sqlite3.Row + try: + # Register exactly as the fix does: every box at this creation_height. + for r in conn.execute( + "SELECT box_id, owner_address, value_nrtc FROM utxo_boxes WHERE creation_height = ?", + (height,), + ).fetchall(): + conn.execute( + "INSERT OR IGNORE INTO account_mirror_boxes " + "(box_id, account_wallet, value_nrtc, created_epoch) VALUES (?,?,?,?)", + (r['box_id'], r['owner_address'], r['value_nrtc'], 42), + ) + conn.commit() + + boxes = [dict(r) for r in conn.execute( + "SELECT * FROM utxo_boxes WHERE owner_address=? AND spent_at IS NULL", (miner,) + ).fetchall()] + self.assertEqual(len(boxes), 1) + spendable, mirrored = _spendable_utxo_candidates(conn, boxes) + self.assertEqual(spendable, [], "reward box is UTXO-spendable — double-spend open") + self.assertEqual(mirrored, [boxes[0]['box_id']]) + finally: + conn.close() + + def test_unregistered_reward_box_would_be_spendable(self): + """Control: WITHOUT registration the reward box IS UTXO-spendable — this is + the double-spend the fix closes (and proves the mechanism test is meaningful).""" + miner = 'miner-reward-2' + self.db.apply_transaction({ + 'tx_type': 'mining_reward', 'inputs': [], + 'outputs': [{'address': miner, 'value_nrtc': 5 * UNIT}], + 'timestamp': int(time.time()), '_allow_minting': True, + }, block_height=99) + conn = sqlite3.connect(self.db_path) + conn.row_factory = sqlite3.Row + try: + boxes = [dict(r) for r in conn.execute( + "SELECT * FROM utxo_boxes WHERE owner_address=? AND spent_at IS NULL", (miner,) + ).fetchall()] + spendable, mirrored = _spendable_utxo_candidates(conn, boxes) + self.assertEqual(len(spendable), 1) + self.assertEqual(mirrored, []) + finally: + conn.close() + + +class TestFinalizeEpochWiresRewardProvenance(unittest.TestCase): + """Source-level: finalize_epoch registers reward boxes as mirror provenance + inside its dual-write batch loop (same convention as test_epoch_utxo_dual_write_guard).""" + + def _finalize_source(self): + source = SERVER_PATH.read_text(encoding='utf-8') + tree = ast.parse(source) + for node in tree.body: + if isinstance(node, ast.FunctionDef) and node.name == 'finalize_epoch': + return ast.get_source_segment(source, node) + raise AssertionError('finalize_epoch() not found') + + def test_finalize_epoch_registers_reward_mirror_provenance(self): + src = self._finalize_source() + self.assertIn("INSERT OR IGNORE INTO account_mirror_boxes", src, + "finalize_epoch must register reward boxes as mirror provenance") + self.assertIn("creation_height = ?", src, + "reward boxes must be located by their batch creation_height") + # Registration must live inside the UTXO_DUAL_WRITE block. + gate = src.index("if UTXO_DUAL_WRITE and utxo_reward_outputs") + reg = src.index("INSERT OR IGNORE INTO account_mirror_boxes") + self.assertGreater(reg, gate, "registration must be inside the dual-write block") + + +if __name__ == '__main__': + unittest.main() diff --git a/node/test_utxo_endpoints.py b/node/test_utxo_endpoints.py index 610bd77a2..b29f839f9 100644 --- a/node/test_utxo_endpoints.py +++ b/node/test_utxo_endpoints.py @@ -1065,6 +1065,29 @@ def test_dual_write_rejects_sub_micro_amounts(self): 100 * utxo_endpoints.ACCOUNT_UNIT, ) + def test_dual_write_rejects_sub_micro_fee(self): + """dual_write cannot safely mirror nanoRTC fee values below 1 microRTC.""" + sender = 'RTC_test_aabbccdd' + self._seed_sender(sender, rtc_amount=100) + + r = self.client.post('/utxo/transfer', json={ + 'from_address': sender, + 'to_address': ('RTC' + 'b' * 40), + 'amount_rtc': 10.0, + 'fee_rtc': '0.00000001', + 'public_key': 'aabbccdd' * 8, + 'signature': 'sig' * 22, + 'nonce': int(time.time() * 1000), + }) + + self.assertEqual(r.status_code, 400) + self.assertIn('dual-write', r.get_json()['error']) + self.assertEqual(self.utxo_db.get_balance(('RTC' + 'b' * 40)), 0) + self.assertEqual( + self._account_balance(sender), + 100 * utxo_endpoints.ACCOUNT_UNIT, + ) + def test_dual_write_shadow_insufficient_rolls_back_utxo_state(self): """A shadow-balance failure must not leave a committed UTXO transfer. diff --git a/node/tests/sybil_guard/conftest.py b/node/tests/sybil_guard/conftest.py new file mode 100644 index 000000000..cbe281bf2 --- /dev/null +++ b/node/tests/sybil_guard/conftest.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: MIT +"""Fixtures for the sybil_guard suite. Helpers live in sg_helpers.py (importing +from `conftest` is ambiguous with node/tests/conftest.py). No network: P2P sync +is stubbed while the node is imported (sg_helpers.load_node).""" +import pytest + +from sg_helpers import load_json # noqa: F401 (also puts node/ on sys.path) + + +@pytest.fixture(scope="session") +def sybil_rows(): + return load_json("sybil_profiles.json") + + +@pytest.fixture(scope="session") +def honest_rows(): + return load_json("honest_profiles.json") + + +@pytest.fixture(autouse=True) +def _standard_settlement_path_allowed(monkeypatch): + """main defaults RC_REQUIRE_ADM to ON in production runtimes (#8352), which + refuses the standard (non-ADM) settlement path outright. These tests + exercise the hold on BOTH paths, so allow the standard path explicitly; + tests that need ADM to be mandatory set RC_REQUIRE_ADM=1 themselves.""" + monkeypatch.setenv("RC_REQUIRE_ADM", "0") diff --git a/node/tests/sybil_guard/fixtures/honest_profiles.json b/node/tests/sybil_guard/fixtures/honest_profiles.json new file mode 100644 index 000000000..9c9da2bbf --- /dev/null +++ b/node/tests/sybil_guard/fixtures/honest_profiles.json @@ -0,0 +1,2090 @@ +[ +{ +"miner": "honest-aarch64-029", +"ts": 1789120726, +"profile_json": "{\"clock_drift_cv\":0.200827,\"thermal_variance\":0.9178,\"jitter_cv\":0.017740450724105752,\"cache_hierarchy_ratio\":1.005}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-aarch64-029", +"ts": 1789121331, +"profile_json": "{\"clock_drift_cv\":0.200827,\"thermal_variance\":0.9178,\"jitter_cv\":0.017740450724105752,\"cache_hierarchy_ratio\":1.005}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-aarch64-029", +"ts": 1789121936, +"profile_json": "{\"clock_drift_cv\":0.200827,\"thermal_variance\":0.9178,\"jitter_cv\":0.017740450724105752,\"cache_hierarchy_ratio\":1.005}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-aarch64-029", +"ts": 1789122541, +"profile_json": "{\"clock_drift_cv\":0.200827,\"thermal_variance\":0.9178,\"jitter_cv\":0.017740450724105752,\"cache_hierarchy_ratio\":1.005}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-aarch64-029", +"ts": 1789123146, +"profile_json": "{\"clock_drift_cv\":0.200827,\"thermal_variance\":0.9178,\"jitter_cv\":0.017740450724105752,\"cache_hierarchy_ratio\":1.005}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-x86-64-069", +"ts": 1789129499, +"profile_json": "{\"clock_drift_cv\":0.0,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "x86_64" +}, +{ +"miner": "honest-g5-043", +"ts": 1789132285, +"profile_json": "{\"clock_drift_cv\":0.0,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-032", +"ts": 1789132502, +"profile_json": "{\"clock_drift_cv\":0.00894935210210751,\"thermal_variance\":0.363834814814572,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.219182}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-031", +"ts": 1789132540, +"profile_json": "{\"clock_drift_cv\":0.0119954,\"thermal_variance\":0.49755,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.41392}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-039", +"ts": 1789132545, +"profile_json": "{\"clock_drift_cv\":0.0069418,\"thermal_variance\":0.23302,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.14224}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-046", +"ts": 1789132552, +"profile_json": "{\"clock_drift_cv\":0.009376402423763934,\"thermal_variance\":0.3896295945805975,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.31194}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-018", +"ts": 1789132556, +"profile_json": "{\"clock_drift_cv\":0.007939224883296455,\"thermal_variance\":0.2902556384653898,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.165678}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-052", +"ts": 1789132568, +"profile_json": "{\"clock_drift_cv\":0.0054962,\"thermal_variance\":0.1744,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.047515}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-010", +"ts": 1789132896, +"profile_json": "{\"clock_drift_cv\":0.007607795522105148,\"thermal_variance\":0.29331,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.189009}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-010", +"ts": 1789133050, +"profile_json": "{\"clock_drift_cv\":0.0043836,\"thermal_variance\":0.125847,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.024494}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133204, +"profile_json": "{\"clock_drift_cv\":0.0111681,\"thermal_variance\":0.46196,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.36283}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133220, +"profile_json": "{\"clock_drift_cv\":0.01118130761229217,\"thermal_variance\":0.46196,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.362961131765088}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133220, +"profile_json": "{\"clock_drift_cv\":0.01138543480564177,\"thermal_variance\":0.4716615530466878,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.372572}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133241, +"profile_json": "{\"clock_drift_cv\":0.0111945,\"thermal_variance\":0.46196,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.36309188938219}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133273, +"profile_json": "{\"clock_drift_cv\":0.01120764660498244,\"thermal_variance\":0.46196,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.36322}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133323, +"profile_json": "{\"clock_drift_cv\":0.0090279,\"thermal_variance\":0.350504,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.254488}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133383, +"profile_json": "{\"clock_drift_cv\":0.0112749,\"thermal_variance\":0.46939,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.3697}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133417, +"profile_json": "{\"clock_drift_cv\":0.0112881,\"thermal_variance\":0.46939,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.3698}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133439, +"profile_json": "{\"clock_drift_cv\":0.0113013,\"thermal_variance\":0.46939,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.36996}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-041", +"ts": 1789133487, +"profile_json": "{\"clock_drift_cv\":0.0113144,\"thermal_variance\":0.46939,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.37009}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-048", +"ts": 1789133501, +"profile_json": "{\"clock_drift_cv\":0.012246542399245724,\"thermal_variance\":0.53,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.37397}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-048", +"ts": 1789133531, +"profile_json": "{\"clock_drift_cv\":0.0122592900212483,\"thermal_variance\":0.53,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.3741}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-048", +"ts": 1789133545, +"profile_json": "{\"clock_drift_cv\":0.01227203764325088,\"thermal_variance\":0.53,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.37423}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-048", +"ts": 1789133569, +"profile_json": "{\"clock_drift_cv\":0.012284785265253458,\"thermal_variance\":0.53,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.37436}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-037", +"ts": 1789133595, +"profile_json": "{\"clock_drift_cv\":0.0115921,\"thermal_variance\":0.45120615841544837,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.3436}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-037", +"ts": 1789133607, +"profile_json": "{\"clock_drift_cv\":0.011605531857655801,\"thermal_variance\":0.45120615841544837,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.34368}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-037", +"ts": 1789133623, +"profile_json": "{\"clock_drift_cv\":0.0116189,\"thermal_variance\":0.45120615841544837,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.34381}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-037", +"ts": 1789133639, +"profile_json": "{\"clock_drift_cv\":0.011632302607367376,\"thermal_variance\":0.45120615841544837,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.34394}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-021", +"ts": 1789133665, +"profile_json": "{\"clock_drift_cv\":0.013698659258844394,\"thermal_variance\":0.5625717973409302,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.523075}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-021", +"ts": 1789133675, +"profile_json": "{\"clock_drift_cv\":0.0137118,\"thermal_variance\":0.5625717973409302,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.523208}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-021", +"ts": 1789133684, +"profile_json": "{\"clock_drift_cv\":0.0137249,\"thermal_variance\":0.5625717973409302,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.52334}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-021", +"ts": 1789133695, +"profile_json": "{\"clock_drift_cv\":0.013738,\"thermal_variance\":0.5625717973409302,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.523472}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-038", +"ts": 1789136406, +"profile_json": "{\"clock_drift_cv\":0.1357866,\"thermal_variance\":0.3,\"jitter_cv\":0.1993993,\"cache_hierarchy_ratio\":2.816049551980771}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-038", +"ts": 1789136726, +"profile_json": "{\"clock_drift_cv\":0.11567,\"thermal_variance\":0.3,\"jitter_cv\":0.1698587,\"cache_hierarchy_ratio\":2.398857}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-038", +"ts": 1789137042, +"profile_json": "{\"clock_drift_cv\":0.12573,\"thermal_variance\":0.3,\"jitter_cv\":0.18463,\"cache_hierarchy_ratio\":2.60745}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-038", +"ts": 1789137366, +"profile_json": "{\"clock_drift_cv\":0.1357866,\"thermal_variance\":0.3,\"jitter_cv\":0.1993993,\"cache_hierarchy_ratio\":2.816049551980771}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-038", +"ts": 1789137728, +"profile_json": "{\"clock_drift_cv\":0.11567,\"thermal_variance\":0.3,\"jitter_cv\":0.1698587,\"cache_hierarchy_ratio\":2.398857}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-038", +"ts": 1789138029, +"profile_json": "{\"clock_drift_cv\":0.12573,\"thermal_variance\":0.3,\"jitter_cv\":0.18463,\"cache_hierarchy_ratio\":2.60745}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-038", +"ts": 1789138570, +"profile_json": "{\"clock_drift_cv\":0.1357866,\"thermal_variance\":0.333,\"jitter_cv\":0.1993993,\"cache_hierarchy_ratio\":2.816049551980771}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-038", +"ts": 1789140258, +"profile_json": "{\"clock_drift_cv\":0.11567,\"thermal_variance\":0.284,\"jitter_cv\":0.1698587,\"cache_hierarchy_ratio\":2.398857}", +"device_arch": "G5" +}, +{ +"miner": "honest-aarch64-070", +"ts": 1789143508, +"profile_json": "{\"clock_drift_cv\":0.02,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-g5-038", +"ts": 1789144644, +"profile_json": "{\"clock_drift_cv\":0.12573,\"thermal_variance\":0.3,\"jitter_cv\":0.18463,\"cache_hierarchy_ratio\":2.60745}", +"device_arch": "G5" +}, +{ +"miner": "honest-g5-038", +"ts": 1789144663, +"profile_json": "{\"clock_drift_cv\":0.1357866,\"thermal_variance\":0.333,\"jitter_cv\":0.1993993,\"cache_hierarchy_ratio\":2.816049551980771}", +"device_arch": "G5" +}, +{ +"miner": "honest-aarch64-070", +"ts": 1789144872, +"profile_json": "{\"clock_drift_cv\":0.02,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-aarch64-071", +"ts": 1789145279, +"profile_json": "{\"clock_drift_cv\":0.041,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-g5-022", +"ts": 1789145665, +"profile_json": "{\"clock_drift_cv\":0.123,\"thermal_variance\":0.3,\"jitter_cv\":0.182,\"cache_hierarchy_ratio\":2.57}", +"device_arch": "G5" +}, +{ +"miner": "honest-g4-072", +"ts": 1789146617, +"profile_json": "{\"clock_drift_cv\":0.0123,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.0}", +"device_arch": "G4" +}, +{ +"miner": "honest-386-073", +"ts": 1789147803, +"profile_json": "{\"clock_drift_cv\":0.0124,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "386" +}, +{ +"miner": "honest-g5-074", +"ts": 1789148954, +"profile_json": "{\"clock_drift_cv\":0.0218,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.0}", +"device_arch": "G5" +}, +{ +"miner": "honest-nes-6502-075", +"ts": 1789148972, +"profile_json": "{\"clock_drift_cv\":0.0,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "nes_6502" +}, +{ +"miner": "honest-default-076", +"ts": 1789150215, +"profile_json": "{\"clock_drift_cv\":0.004,\"thermal_variance\":0.0,\"jitter_cv\":0.02,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "default" +}, +{ +"miner": "honest-default-076", +"ts": 1789150291, +"profile_json": "{\"clock_drift_cv\":0.004,\"thermal_variance\":0.0,\"jitter_cv\":0.02,\"cache_hierarchy_ratio\":4.0}", +"device_arch": "default" +}, +{ +"miner": "honest-g4-072", +"ts": 1789154207, +"profile_json": "{\"clock_drift_cv\":0.0126,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.0}", +"device_arch": "G4" +}, +{ +"miner": "honest-aarch64-077", +"ts": 1789156899, +"profile_json": "{\"clock_drift_cv\":0.02,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-g4-078", +"ts": 1789157048, +"profile_json": "{\"clock_drift_cv\":0.0125,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.0}", +"device_arch": "G4" +}, +{ +"miner": "honest-g4-079", +"ts": 1789162932, +"profile_json": "{\"clock_drift_cv\":0.0121,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":2.0}", +"device_arch": "G4" +}, +{ +"miner": "honest-g4-083", +"ts": 1789162987, +"profile_json": "{\"clock_drift_cv\":0.0124,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "G4" +}, +{ +"miner": "honest-386-084", +"ts": 1789163013, +"profile_json": "{\"clock_drift_cv\":0.012,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "386" +}, +{ +"miner": "honest-aarch64-000", +"ts": 1789218142, +"profile_json": "{\"clock_drift_cv\":0.04263,\"thermal_variance\":1.0483,\"jitter_cv\":0.045375513769839074,\"cache_hierarchy_ratio\":1.017}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-arm2-053", +"ts": 1789309337, +"profile_json": "{\"clock_drift_cv\":0.021,\"thermal_variance\":1.2,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.16}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-053", +"ts": 1789316128, +"profile_json": "{\"clock_drift_cv\":0.020626418720345006,\"thermal_variance\":1.1788754923274072,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.1572029331040845}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-036", +"ts": 1789316136, +"profile_json": "{\"clock_drift_cv\":0.022256061360095863,\"thermal_variance\":1.207795606032869,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.3025067752710946}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-034", +"ts": 1789316145, +"profile_json": "{\"clock_drift_cv\":0.023666102246517155,\"thermal_variance\":1.214076159592142,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.348300574026945}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-028", +"ts": 1789316154, +"profile_json": "{\"clock_drift_cv\":0.025749207175723578,\"thermal_variance\":1.228599273385013,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.357027209615553}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-017", +"ts": 1789316162, +"profile_json": "{\"clock_drift_cv\":0.028058858728727747,\"thermal_variance\":1.2546418914495845,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.3280233578485494}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-024", +"ts": 1789316171, +"profile_json": "{\"clock_drift_cv\":0.029571194579982005,\"thermal_variance\":1.2575517458800196,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.2135110823399873}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-047", +"ts": 1789316179, +"profile_json": "{\"clock_drift_cv\":0.03119682254403238,\"thermal_variance\":1.3069162712278357,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.3995159723451325}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-001", +"ts": 1789316188, +"profile_json": "{\"clock_drift_cv\":0.03210781691234259,\"thermal_variance\":1.337650780714241,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.2357842511109807}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-011", +"ts": 1789316196, +"profile_json": "{\"clock_drift_cv\":0.0353642590828415,\"thermal_variance\":1.3703765415905111,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.4081214190535114}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-023", +"ts": 1789316205, +"profile_json": "{\"clock_drift_cv\":0.03651895282602455,\"thermal_variance\":1.3355575751115574,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.435570134732577}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-015", +"ts": 1789316213, +"profile_json": "{\"clock_drift_cv\":0.03870471653965016,\"thermal_variance\":1.3758797265264873,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.4194249202886753}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-051", +"ts": 1789316222, +"profile_json": "{\"clock_drift_cv\":0.03980191857294064,\"thermal_variance\":1.3931001979400834,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.334119760288473}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-014", +"ts": 1789316230, +"profile_json": "{\"clock_drift_cv\":0.04261687350901837,\"thermal_variance\":1.4665232614423147,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.443727879671471}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-045", +"ts": 1789316239, +"profile_json": "{\"clock_drift_cv\":0.04214437229857436,\"thermal_variance\":1.4138959692152375,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.3726869093816183}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-053", +"ts": 1789319789, +"profile_json": "{\"clock_drift_cv\":0.02058505110435002,\"thermal_variance\":1.1790769021290062,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.1595389549469926}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-003", +"ts": 1789319791, +"profile_json": "{\"clock_drift_cv\":0.026796006660420344,\"thermal_variance\":1.2892826455114508,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.233084669939401}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-006", +"ts": 1789319791, +"profile_json": "{\"clock_drift_cv\":0.024303810860731714,\"thermal_variance\":1.2396667738494929,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.272692495696009}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-009", +"ts": 1789319791, +"profile_json": "{\"clock_drift_cv\":0.031382640204304875,\"thermal_variance\":1.3180677327988963,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.2822641013414655}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-016", +"ts": 1789319791, +"profile_json": "{\"clock_drift_cv\":0.033572344326929356,\"thermal_variance\":1.3260823186361608,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.39720959319538}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-030", +"ts": 1789319791, +"profile_json": "{\"clock_drift_cv\":0.029089806172765978,\"thermal_variance\":1.324433112948901,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.2518252534261447}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-042", +"ts": 1789319791, +"profile_json": "{\"clock_drift_cv\":0.035136408455821555,\"thermal_variance\":1.3875876812166865,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.2543177275413395}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-044", +"ts": 1789319791, +"profile_json": "{\"clock_drift_cv\":0.02788092303328988,\"thermal_variance\":1.289951826071399,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.364761701427179}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-054", +"ts": 1789319791, +"profile_json": "{\"clock_drift_cv\":0.022672918293355594,\"thermal_variance\":1.1938751421722371,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.1934151085463105}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-013", +"ts": 1789319793, +"profile_json": "{\"clock_drift_cv\":0.03529580716574705,\"thermal_variance\":1.3641485882595143,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.388619847869211}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-012", +"ts": 1789319859, +"profile_json": "{\"clock_drift_cv\":0.039120600149892805,\"thermal_variance\":1.3875627199374794,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.2743725766470213}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-020", +"ts": 1789319859, +"profile_json": "{\"clock_drift_cv\":0.04006293554489442,\"thermal_variance\":1.409805858010213,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.3907100238528343}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-035", +"ts": 1789319859, +"profile_json": "{\"clock_drift_cv\":0.042340325252225745,\"thermal_variance\":1.466853260609063,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.302210951661236}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-040", +"ts": 1789319859, +"profile_json": "{\"clock_drift_cv\":0.04212500994365954,\"thermal_variance\":1.4477749169663636,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.4296526609740257}", +"device_arch": "arm2" +}, +{ +"miner": "honest-arm2-050", +"ts": 1789319859, +"profile_json": "{\"clock_drift_cv\":0.04410336719757928,\"thermal_variance\":1.4423839645651713,\"jitter_cv\":0.04,\"cache_hierarchy_ratio\":3.373946178097246}", +"device_arch": "arm2" +}, +{ +"miner": "honest-default-055", +"ts": 1789351346, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-default-055", +"ts": 1789351933, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-default-055", +"ts": 1789352516, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-default-055", +"ts": 1789353099, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-default-055", +"ts": 1789353682, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-default-055", +"ts": 1789354273, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-default-055", +"ts": 1789354862, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-default-055", +"ts": 1789355447, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-default-055", +"ts": 1789356031, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-default-055", +"ts": 1789356622, +"profile_json": "{\"clock_drift_cv\":0.3523,\"thermal_variance\":0.9333,\"jitter_cv\":0.035504113977094076,\"cache_hierarchy_ratio\":0.995}", +"device_arch": "default" +}, +{ +"miner": "honest-modern-057", +"ts": 1789563903, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-057", +"ts": 1789564510, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-057", +"ts": 1789565117, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-057", +"ts": 1789565724, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-057", +"ts": 1789566330, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-057", +"ts": 1789566937, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-057", +"ts": 1789567544, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-057", +"ts": 1789568150, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-057", +"ts": 1789568756, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-057", +"ts": 1789569364, +"profile_json": "{\"clock_drift_cv\":0.11291,\"thermal_variance\":1.0681,\"jitter_cv\":0.16369080547928283,\"cache_hierarchy_ratio\":1.112}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789638335, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789638941, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789639545, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789640151, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789640765, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789641370, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789641975, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789642584, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789643196, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-027", +"ts": 1789643820, +"profile_json": "{\"clock_drift_cv\":0.010593,\"thermal_variance\":0.9472,\"jitter_cv\":0.21855489904970868,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789690525, +"profile_json": "{\"clock_drift_cv\":0.007139,\"thermal_variance\":1.0057,\"jitter_cv\":0.021381768670776572,\"cache_hierarchy_ratio\":1.024}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789690853, +"profile_json": "{\"clock_drift_cv\":0.01208,\"thermal_variance\":0.9642,\"jitter_cv\":0.010227584443322372,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789691454, +"profile_json": "{\"clock_drift_cv\":0.01208,\"thermal_variance\":0.9642,\"jitter_cv\":0.010227584443322372,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789692056, +"profile_json": "{\"clock_drift_cv\":0.01208,\"thermal_variance\":0.9642,\"jitter_cv\":0.010227584443322372,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789692657, +"profile_json": "{\"clock_drift_cv\":0.01208,\"thermal_variance\":0.9642,\"jitter_cv\":0.010227584443322372,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789693258, +"profile_json": "{\"clock_drift_cv\":0.01208,\"thermal_variance\":0.9642,\"jitter_cv\":0.010227584443322372,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789693859, +"profile_json": "{\"clock_drift_cv\":0.01208,\"thermal_variance\":0.9642,\"jitter_cv\":0.010227584443322372,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789694460, +"profile_json": "{\"clock_drift_cv\":0.01208,\"thermal_variance\":0.9642,\"jitter_cv\":0.010227584443322372,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789695062, +"profile_json": "{\"clock_drift_cv\":0.01208,\"thermal_variance\":0.9642,\"jitter_cv\":0.010227584443322372,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-066", +"ts": 1789695663, +"profile_json": "{\"clock_drift_cv\":0.01208,\"thermal_variance\":0.9642,\"jitter_cv\":0.010227584443322372,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-intel64-family-6-model-1-049", +"ts": 1789765045, +"profile_json": "{\"clock_drift_cv\":0.0201,\"thermal_variance\":3.04,\"jitter_cv\":0.03149535110790892,\"cache_hierarchy_ratio\":1.079}", +"device_arch": "Intel64 Family 6 Model 183 Stepping 1, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-049", +"ts": 1789771262, +"profile_json": "{\"clock_drift_cv\":0.038084,\"thermal_variance\":1.0078,\"jitter_cv\":0.047566352228196336,\"cache_hierarchy_ratio\":1.042}", +"device_arch": "Intel64 Family 6 Model 183 Stepping 1, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-049", +"ts": 1789771793, +"profile_json": "{\"clock_drift_cv\":0.031271,\"thermal_variance\":1.0101,\"jitter_cv\":0.053738583058713076,\"cache_hierarchy_ratio\":1.062}", +"device_arch": "Intel64 Family 6 Model 183 Stepping 1, GenuineIntel" +}, +{ +"miner": "honest-modern-061", +"ts": 1789889020, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-061", +"ts": 1789889622, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-061", +"ts": 1789890223, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-061", +"ts": 1789890824, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-061", +"ts": 1789891458, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-061", +"ts": 1789892059, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-061", +"ts": 1789892660, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-061", +"ts": 1789893261, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-061", +"ts": 1789893863, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-061", +"ts": 1789894464, +"profile_json": "{\"clock_drift_cv\":0.271722,\"thermal_variance\":0.8592,\"jitter_cv\":0.2365170012071107,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-amd64-family-16-model-4--026", +"ts": 1789923811, +"profile_json": "{\"clock_drift_cv\":0.020132,\"thermal_variance\":1.0042,\"jitter_cv\":0.03574158632699975,\"cache_hierarchy_ratio\":1.037}", +"device_arch": "AMD64 Family 16 Model 4 Stepping 3, AuthenticAMD" +}, +{ +"miner": "honest-amd64-family-16-model-4--026", +"ts": 1789924185, +"profile_json": "{\"clock_drift_cv\":0.017447,\"thermal_variance\":1.0757,\"jitter_cv\":0.08376861540957801,\"cache_hierarchy_ratio\":1.035}", +"device_arch": "AMD64 Family 16 Model 4 Stepping 3, AuthenticAMD" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790070570, +"profile_json": "{\"clock_drift_cv\":0.24703,\"thermal_variance\":1.1752,\"jitter_cv\":0.28311692440491365,\"cache_hierarchy_ratio\":1.005}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790071110, +"profile_json": "{\"clock_drift_cv\":0.152327,\"thermal_variance\":0.9379,\"jitter_cv\":0.40639274252979657,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790071642, +"profile_json": "{\"clock_drift_cv\":0.246525,\"thermal_variance\":1.0824,\"jitter_cv\":0.25797719910709704,\"cache_hierarchy_ratio\":1.115}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790072182, +"profile_json": "{\"clock_drift_cv\":0.210208,\"thermal_variance\":1.1329,\"jitter_cv\":0.21353707265838276,\"cache_hierarchy_ratio\":1.059}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790072713, +"profile_json": "{\"clock_drift_cv\":0.230377,\"thermal_variance\":1.0834,\"jitter_cv\":0.22734352848350464,\"cache_hierarchy_ratio\":0.837}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790073252, +"profile_json": "{\"clock_drift_cv\":0.233728,\"thermal_variance\":1.0054,\"jitter_cv\":0.1380659675116954,\"cache_hierarchy_ratio\":1.207}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790073784, +"profile_json": "{\"clock_drift_cv\":0.232869,\"thermal_variance\":1.3171,\"jitter_cv\":0.2081182446050274,\"cache_hierarchy_ratio\":1.106}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790074314, +"profile_json": "{\"clock_drift_cv\":0.189195,\"thermal_variance\":0.8114,\"jitter_cv\":0.23909364754185636,\"cache_hierarchy_ratio\":1.337}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790074844, +"profile_json": "{\"clock_drift_cv\":0.167153,\"thermal_variance\":0.9303,\"jitter_cv\":0.3057351402039381,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-007", +"ts": 1790075384, +"profile_json": "{\"clock_drift_cv\":0.22266,\"thermal_variance\":1.0262,\"jitter_cv\":0.13469279412015858,\"cache_hierarchy_ratio\":1.217}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-amd64-002", +"ts": 1790082604, +"profile_json": "{\"clock_drift_cv\":0.104006,\"thermal_variance\":1.0424,\"jitter_cv\":0.23919888435574158,\"cache_hierarchy_ratio\":1.049}", +"device_arch": "AMD64" +}, +{ +"miner": "honest-amd64-002", +"ts": 1790082647, +"profile_json": "{\"clock_drift_cv\":0.0,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "AMD64" +}, +{ +"miner": "honest-x86-64-056", +"ts": 1790127171, +"profile_json": "{\"clock_drift_cv\":0.0,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "x86_64" +}, +{ +"miner": "honest-modern-064", +"ts": 1790140450, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-064", +"ts": 1790141051, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-064", +"ts": 1790141652, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-064", +"ts": 1790142253, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-064", +"ts": 1790142854, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-064", +"ts": 1790143467, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-064", +"ts": 1790144068, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-064", +"ts": 1790144669, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-064", +"ts": 1790145270, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-064", +"ts": 1790146580, +"profile_json": "{\"clock_drift_cv\":0.030709,\"thermal_variance\":1.0144,\"jitter_cv\":0.04859588575099213,\"cache_hierarchy_ratio\":0.985}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-063", +"ts": 1790166918, +"profile_json": "{\"clock_drift_cv\":0.039561,\"thermal_variance\":0.9807,\"jitter_cv\":0.004469766321687669,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-063", +"ts": 1790167040, +"profile_json": "{\"clock_drift_cv\":0.010883,\"thermal_variance\":1.0174,\"jitter_cv\":0.005619113838141636,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-063", +"ts": 1790167525, +"profile_json": "{\"clock_drift_cv\":0.039561,\"thermal_variance\":0.9807,\"jitter_cv\":0.004469766321687669,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-063", +"ts": 1790167645, +"profile_json": "{\"clock_drift_cv\":0.010883,\"thermal_variance\":1.0174,\"jitter_cv\":0.005619113838141636,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-063", +"ts": 1790168131, +"profile_json": "{\"clock_drift_cv\":0.039561,\"thermal_variance\":0.9807,\"jitter_cv\":0.004469766321687669,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-063", +"ts": 1790168250, +"profile_json": "{\"clock_drift_cv\":0.010883,\"thermal_variance\":1.0174,\"jitter_cv\":0.005619113838141636,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-063", +"ts": 1790168735, +"profile_json": "{\"clock_drift_cv\":0.039561,\"thermal_variance\":0.9807,\"jitter_cv\":0.004469766321687669,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-063", +"ts": 1790168854, +"profile_json": "{\"clock_drift_cv\":0.010883,\"thermal_variance\":1.0174,\"jitter_cv\":0.005619113838141636,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "modern" +}, +{ +"miner": "honest-retro-058", +"ts": 1790265215, +"profile_json": "{\"clock_drift_cv\":0.001698,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-modern-082", +"ts": 1790266028, +"profile_json": "{\"clock_drift_cv\":0.08887094245958535,\"thermal_variance\":0.9976,\"jitter_cv\":0.16469560544891995,\"cache_hierarchy_ratio\":1.19}", +"device_arch": "modern" +}, +{ +"miner": "honest-retro-058", +"ts": 1790267016, +"profile_json": "{\"clock_drift_cv\":0.001705,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-modern-082", +"ts": 1790267828, +"profile_json": "{\"clock_drift_cv\":0.007915850065460816,\"thermal_variance\":0.9982,\"jitter_cv\":0.029959753939042478,\"cache_hierarchy_ratio\":1.015}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-082", +"ts": 1790269628, +"profile_json": "{\"clock_drift_cv\":0.029643216599503888,\"thermal_variance\":0.9988,\"jitter_cv\":0.009901162155861716,\"cache_hierarchy_ratio\":1.034}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-082", +"ts": 1790271429, +"profile_json": "{\"clock_drift_cv\":0.05172652718935393,\"thermal_variance\":0.9961,\"jitter_cv\":0.0431077947299461,\"cache_hierarchy_ratio\":1.024}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-082", +"ts": 1790273229, +"profile_json": "{\"clock_drift_cv\":0.05581278931678008,\"thermal_variance\":1.0541,\"jitter_cv\":0.09157335991564648,\"cache_hierarchy_ratio\":1.034}", +"device_arch": "modern" +}, +{ +"miner": "honest-retro-058", +"ts": 1790275012, +"profile_json": "{\"clock_drift_cv\":0.001703,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-modern-082", +"ts": 1790275029, +"profile_json": "{\"clock_drift_cv\":0.01088715662209625,\"thermal_variance\":0.9971,\"jitter_cv\":0.010826308599385926,\"cache_hierarchy_ratio\":1.023}", +"device_arch": "modern" +}, +{ +"miner": "honest-retro-058", +"ts": 1790276813, +"profile_json": "{\"clock_drift_cv\":0.00187,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-modern-082", +"ts": 1790276829, +"profile_json": "{\"clock_drift_cv\":0.013140109367091183,\"thermal_variance\":1.0016,\"jitter_cv\":0.006857859758627535,\"cache_hierarchy_ratio\":1.017}", +"device_arch": "modern" +}, +{ +"miner": "honest-retro-058", +"ts": 1790278613, +"profile_json": "{\"clock_drift_cv\":0.001705,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-retro-058", +"ts": 1790280414, +"profile_json": "{\"clock_drift_cv\":0.001704,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-retro-058", +"ts": 1790282215, +"profile_json": "{\"clock_drift_cv\":0.001711,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790283563, +"profile_json": "{\"clock_drift_cv\":0.022329,\"thermal_variance\":1.0064,\"jitter_cv\":0.03964039901703559,\"cache_hierarchy_ratio\":1.02}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-retro-058", +"ts": 1790284015, +"profile_json": "{\"clock_drift_cv\":0.001704,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-modern-082", +"ts": 1790284026, +"profile_json": "{\"clock_drift_cv\":0.12079454300503606,\"thermal_variance\":0.9939,\"jitter_cv\":0.007491274035793039,\"cache_hierarchy_ratio\":1.0}", +"device_arch": "modern" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790284101, +"profile_json": "{\"clock_drift_cv\":0.023244,\"thermal_variance\":0.9884,\"jitter_cv\":0.03499970788593141,\"cache_hierarchy_ratio\":1.024}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790284519, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790284640, +"profile_json": "{\"clock_drift_cv\":0.12201,\"thermal_variance\":1.0093,\"jitter_cv\":0.03824095212609347,\"cache_hierarchy_ratio\":1.037}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790285177, +"profile_json": "{\"clock_drift_cv\":0.032581,\"thermal_variance\":0.9896,\"jitter_cv\":0.05379502388828837,\"cache_hierarchy_ratio\":1.044}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790285399, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790285715, +"profile_json": "{\"clock_drift_cv\":0.023852,\"thermal_variance\":0.9838,\"jitter_cv\":0.04597562716341902,\"cache_hierarchy_ratio\":1.003}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-retro-058", +"ts": 1790285816, +"profile_json": "{\"clock_drift_cv\":0.00171,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-modern-082", +"ts": 1790285825, +"profile_json": "{\"clock_drift_cv\":0.008832109845462397,\"thermal_variance\":1.0102,\"jitter_cv\":0.09223218635321698,\"cache_hierarchy_ratio\":1.014}", +"device_arch": "modern" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790286253, +"profile_json": "{\"clock_drift_cv\":0.025631,\"thermal_variance\":0.9963,\"jitter_cv\":0.027045553584974395,\"cache_hierarchy_ratio\":1.004}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790286741, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790286790, +"profile_json": "{\"clock_drift_cv\":0.029974,\"thermal_variance\":0.9991,\"jitter_cv\":0.02237719787054168,\"cache_hierarchy_ratio\":1.011}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790286820, +"profile_json": "{\"clock_drift_cv\":0.006618,\"thermal_variance\":0.9881,\"jitter_cv\":0.00836481707594592,\"cache_hierarchy_ratio\":1.026}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-modern-085", +"ts": 1790286951, +"profile_json": "{\"clock_drift_cv\":0.117826,\"thermal_variance\":0.9959,\"jitter_cv\":0.07160136882239097,\"cache_hierarchy_ratio\":1.031}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-019", +"ts": 1790287295, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790287328, +"profile_json": "{\"clock_drift_cv\":0.102447,\"thermal_variance\":1.0135,\"jitter_cv\":0.026686628904024724,\"cache_hierarchy_ratio\":0.983}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790287455, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790287467, +"profile_json": "{\"clock_drift_cv\":0.006529,\"thermal_variance\":0.9812,\"jitter_cv\":0.005805301520522408,\"cache_hierarchy_ratio\":1.03}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-modern-081", +"ts": 1790287494, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-004", +"ts": 1790287498, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-modern-080", +"ts": 1790287541, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-085", +"ts": 1790287564, +"profile_json": "{\"clock_drift_cv\":0.119391,\"thermal_variance\":0.9832,\"jitter_cv\":0.026419636166872575,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-033", +"ts": 1790287577, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-retro-058", +"ts": 1790287617, +"profile_json": "{\"clock_drift_cv\":0.002092,\"thermal_variance\":0.0,\"jitter_cv\":0.0,\"cache_hierarchy_ratio\":0.0}", +"device_arch": "retro" +}, +{ +"miner": "honest-modern-082", +"ts": 1790287626, +"profile_json": "{\"clock_drift_cv\":0.002253770284071094,\"thermal_variance\":0.9973,\"jitter_cv\":0.04537059484146286,\"cache_hierarchy_ratio\":1.018}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-062", +"ts": 1790287660, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790287866, +"profile_json": "{\"clock_drift_cv\":0.160209,\"thermal_variance\":0.9924,\"jitter_cv\":0.024403828751650883,\"cache_hierarchy_ratio\":1.013}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790287872, +"profile_json": "{\"clock_drift_cv\":0.03803,\"thermal_variance\":0.9775,\"jitter_cv\":0.04694234537334146,\"cache_hierarchy_ratio\":1.004}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-m2-019", +"ts": 1790287881, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790288004, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790288057, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-m2-004", +"ts": 1790288090, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-modern-081", +"ts": 1790288109, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-080", +"ts": 1790288142, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790288158, +"profile_json": "{\"clock_drift_cv\":0.002679,\"thermal_variance\":0.9841,\"jitter_cv\":0.004901135745795869,\"cache_hierarchy_ratio\":1.027}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-modern-085", +"ts": 1790288178, +"profile_json": "{\"clock_drift_cv\":0.160589,\"thermal_variance\":0.9857,\"jitter_cv\":0.23197720641665467,\"cache_hierarchy_ratio\":0.754}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-033", +"ts": 1790288188, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-062", +"ts": 1790288262, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790288398, +"profile_json": "{\"clock_drift_cv\":0.026523,\"thermal_variance\":0.9763,\"jitter_cv\":0.022902776474493885,\"cache_hierarchy_ratio\":1.03}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-intel64-family-6-model-1-059", +"ts": 1790288403, +"profile_json": "{\"clock_drift_cv\":0.025787,\"thermal_variance\":0.9814,\"jitter_cv\":0.05942274314233302,\"cache_hierarchy_ratio\":1.0}", +"device_arch": "Intel64 Family 6 Model 158 Stepping 10, GenuineIntel" +}, +{ +"miner": "honest-modern-008", +"ts": 1790288419, +"profile_json": "{\"clock_drift_cv\":0.071071,\"thermal_variance\":0.4693,\"jitter_cv\":0.026837382750966275,\"cache_hierarchy_ratio\":0.956}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-019", +"ts": 1790288469, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790288647, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790288658, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-m2-004", +"ts": 1790288682, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-modern-081", +"ts": 1790288725, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-080", +"ts": 1790288744, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-085", +"ts": 1790288790, +"profile_json": "{\"clock_drift_cv\":0.187967,\"thermal_variance\":0.9293,\"jitter_cv\":0.07100921045338776,\"cache_hierarchy_ratio\":1.057}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-033", +"ts": 1790288798, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790288805, +"profile_json": "{\"clock_drift_cv\":0.007742,\"thermal_variance\":0.992,\"jitter_cv\":0.006150646408169271,\"cache_hierarchy_ratio\":1.03}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-modern-062", +"ts": 1790288863, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790288924, +"profile_json": "{\"clock_drift_cv\":0.0309,\"thermal_variance\":0.9771,\"jitter_cv\":0.05412050063251857,\"cache_hierarchy_ratio\":0.946}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-modern-008", +"ts": 1790289021, +"profile_json": "{\"clock_drift_cv\":0.071071,\"thermal_variance\":0.4693,\"jitter_cv\":0.026837382750966275,\"cache_hierarchy_ratio\":0.956}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-019", +"ts": 1790289051, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790289260, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-m2-004", +"ts": 1790289273, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790289286, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-modern-081", +"ts": 1790289341, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-080", +"ts": 1790289346, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-085", +"ts": 1790289409, +"profile_json": "{\"clock_drift_cv\":0.206471,\"thermal_variance\":1.02,\"jitter_cv\":0.2359561957777919,\"cache_hierarchy_ratio\":0.96}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-033", +"ts": 1790289410, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790289420, +"profile_json": "{\"clock_drift_cv\":0.022308,\"thermal_variance\":0.979,\"jitter_cv\":0.003820629869248802,\"cache_hierarchy_ratio\":1.028}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790289451, +"profile_json": "{\"clock_drift_cv\":0.02923,\"thermal_variance\":0.9756,\"jitter_cv\":0.020776356089811033,\"cache_hierarchy_ratio\":0.998}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-modern-062", +"ts": 1790289464, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-008", +"ts": 1790289624, +"profile_json": "{\"clock_drift_cv\":0.071071,\"thermal_variance\":0.4693,\"jitter_cv\":0.026837382750966275,\"cache_hierarchy_ratio\":0.956}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-019", +"ts": 1790289641, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-m4-005", +"ts": 1790289801, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790289862, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-m2-004", +"ts": 1790289865, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-modern-080", +"ts": 1790289948, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-081", +"ts": 1790289953, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790289980, +"profile_json": "{\"clock_drift_cv\":0.073482,\"thermal_variance\":1.8325,\"jitter_cv\":0.16373947202592115,\"cache_hierarchy_ratio\":0.994}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-modern-033", +"ts": 1790290020, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-085", +"ts": 1790290028, +"profile_json": "{\"clock_drift_cv\":0.157374,\"thermal_variance\":0.8922,\"jitter_cv\":0.0711966285941691,\"cache_hierarchy_ratio\":0.891}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-062", +"ts": 1790290066, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-m4-005", +"ts": 1790290109, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790290127, +"profile_json": "{\"clock_drift_cv\":0.008103,\"thermal_variance\":1.0074,\"jitter_cv\":0.008883891371423923,\"cache_hierarchy_ratio\":1.029}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-modern-008", +"ts": 1790290226, +"profile_json": "{\"clock_drift_cv\":0.071071,\"thermal_variance\":0.4693,\"jitter_cv\":0.026837382750966275,\"cache_hierarchy_ratio\":0.956}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-019", +"ts": 1790290228, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-m4-005", +"ts": 1790290418, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +}, +{ +"miner": "honest-m2-004", +"ts": 1790290456, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790290464, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790290507, +"profile_json": "{\"clock_drift_cv\":0.031571,\"thermal_variance\":0.9825,\"jitter_cv\":0.055460643268029464,\"cache_hierarchy_ratio\":1.03}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-modern-080", +"ts": 1790290550, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-081", +"ts": 1790290568, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-033", +"ts": 1790290631, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-062", +"ts": 1790290667, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-m4-005", +"ts": 1790290721, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790290723, +"profile_json": "{\"clock_drift_cv\":0.006247,\"thermal_variance\":0.9817,\"jitter_cv\":0.023234831027716642,\"cache_hierarchy_ratio\":1.032}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-modern-068", +"ts": 1790290804, +"profile_json": "{\"clock_drift_cv\":0.16203,\"thermal_variance\":0.8429,\"jitter_cv\":0.16271161610633658,\"cache_hierarchy_ratio\":1.004}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-019", +"ts": 1790290816, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-modern-008", +"ts": 1790290828, +"profile_json": "{\"clock_drift_cv\":0.071071,\"thermal_variance\":0.4693,\"jitter_cv\":0.026837382750966275,\"cache_hierarchy_ratio\":0.956}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-068", +"ts": 1790290845, +"profile_json": "{\"clock_drift_cv\":0.075551,\"thermal_variance\":0.9959,\"jitter_cv\":0.14009500150849574,\"cache_hierarchy_ratio\":1.028}", +"device_arch": "modern" +}, +{ +"miner": "honest-m4-005", +"ts": 1790291029, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790291033, +"profile_json": "{\"clock_drift_cv\":0.027032,\"thermal_variance\":0.9794,\"jitter_cv\":0.027957844070454665,\"cache_hierarchy_ratio\":0.959}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-m2-004", +"ts": 1790291048, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790291065, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-modern-068", +"ts": 1790291112, +"profile_json": "{\"clock_drift_cv\":0.16203,\"thermal_variance\":0.8429,\"jitter_cv\":0.16271161610633658,\"cache_hierarchy_ratio\":1.004}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-080", +"ts": 1790291152, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-085", +"ts": 1790291158, +"profile_json": "{\"clock_drift_cv\":0.889131,\"thermal_variance\":0.9786,\"jitter_cv\":0.07961606409690251,\"cache_hierarchy_ratio\":1.051}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-081", +"ts": 1790291184, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790291207, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-modern-033", +"ts": 1790291241, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-062", +"ts": 1790291269, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790291383, +"profile_json": "{\"clock_drift_cv\":0.009193,\"thermal_variance\":1.0015,\"jitter_cv\":0.006861846149964414,\"cache_hierarchy_ratio\":1.01}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-m2-019", +"ts": 1790291403, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-modern-068", +"ts": 1790291427, +"profile_json": "{\"clock_drift_cv\":0.16203,\"thermal_variance\":0.8429,\"jitter_cv\":0.16271161610633658,\"cache_hierarchy_ratio\":1.004}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-008", +"ts": 1790291430, +"profile_json": "{\"clock_drift_cv\":0.071071,\"thermal_variance\":0.4693,\"jitter_cv\":0.026837382750966275,\"cache_hierarchy_ratio\":0.956}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-068", +"ts": 1790291482, +"profile_json": "{\"clock_drift_cv\":0.075551,\"thermal_variance\":0.9959,\"jitter_cv\":0.14009500150849574,\"cache_hierarchy_ratio\":1.028}", +"device_arch": "modern" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790291559, +"profile_json": "{\"clock_drift_cv\":0.026012,\"thermal_variance\":0.9787,\"jitter_cv\":0.01989671988438791,\"cache_hierarchy_ratio\":1.031}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-m2-004", +"ts": 1790291639, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790291667, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-modern-068", +"ts": 1790291734, +"profile_json": "{\"clock_drift_cv\":0.16203,\"thermal_variance\":0.8429,\"jitter_cv\":0.16271161610633658,\"cache_hierarchy_ratio\":1.004}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-080", +"ts": 1790291754, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-085", +"ts": 1790291776, +"profile_json": "{\"clock_drift_cv\":0.082445,\"thermal_variance\":0.7139,\"jitter_cv\":0.014217121313989185,\"cache_hierarchy_ratio\":1.055}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-081", +"ts": 1790291800, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790291810, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-modern-033", +"ts": 1790291851, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-m4-005", +"ts": 1790291862, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +}, +{ +"miner": "honest-modern-062", +"ts": 1790291870, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-019", +"ts": 1790291990, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-modern-008", +"ts": 1790292033, +"profile_json": "{\"clock_drift_cv\":0.071071,\"thermal_variance\":0.4693,\"jitter_cv\":0.026837382750966275,\"cache_hierarchy_ratio\":0.956}", +"device_arch": "modern" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790292087, +"profile_json": "{\"clock_drift_cv\":0.061174,\"thermal_variance\":0.9858,\"jitter_cv\":0.02785758802475464,\"cache_hierarchy_ratio\":0.98}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790292089, +"profile_json": "{\"clock_drift_cv\":0.00791,\"thermal_variance\":0.9899,\"jitter_cv\":0.00747848950476507,\"cache_hierarchy_ratio\":1.025}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-modern-068", +"ts": 1790292099, +"profile_json": "{\"clock_drift_cv\":0.075551,\"thermal_variance\":0.9959,\"jitter_cv\":0.14009500150849574,\"cache_hierarchy_ratio\":1.028}", +"device_arch": "modern" +}, +{ +"miner": "honest-m4-005", +"ts": 1790292173, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +}, +{ +"miner": "honest-m2-004", +"ts": 1790292231, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790292269, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-modern-080", +"ts": 1790292356, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790292397, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-modern-081", +"ts": 1790292414, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-085", +"ts": 1790292419, +"profile_json": "{\"clock_drift_cv\":0.139441,\"thermal_variance\":1.0116,\"jitter_cv\":0.19603991213576194,\"cache_hierarchy_ratio\":1.053}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-033", +"ts": 1790292462, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-062", +"ts": 1790292471, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-m4-005", +"ts": 1790292475, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +}, +{ +"miner": "honest-modern-068", +"ts": 1790292561, +"profile_json": "{\"clock_drift_cv\":0.16203,\"thermal_variance\":0.8429,\"jitter_cv\":0.16271161610633658,\"cache_hierarchy_ratio\":1.004}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-019", +"ts": 1790292577, +"profile_json": "{\"clock_drift_cv\":0.416583,\"thermal_variance\":1.0285,\"jitter_cv\":0.6351680661756434,\"cache_hierarchy_ratio\":1.146}", +"device_arch": "M2" +}, +{ +"miner": "honest-amd64-family-25-model-97-065", +"ts": 1790292614, +"profile_json": "{\"clock_drift_cv\":0.04072,\"thermal_variance\":0.9688,\"jitter_cv\":0.03837636269812703,\"cache_hierarchy_ratio\":1.007}", +"device_arch": "AMD64 Family 25 Model 97 Stepping 2, AuthenticAMD" +}, +{ +"miner": "honest-modern-008", +"ts": 1790292635, +"profile_json": "{\"clock_drift_cv\":0.071071,\"thermal_variance\":0.4693,\"jitter_cv\":0.026837382750966275,\"cache_hierarchy_ratio\":0.956}", +"device_arch": "modern" +}, +{ +"miner": "honest-broadwell-067", +"ts": 1790292682, +"profile_json": "{\"clock_drift_cv\":0.007079,\"thermal_variance\":0.9891,\"jitter_cv\":0.0038993110911627704,\"cache_hierarchy_ratio\":1.026}", +"device_arch": "broadwell" +}, +{ +"miner": "honest-modern-085", +"ts": 1790292769, +"profile_json": "{\"clock_drift_cv\":0.144332,\"thermal_variance\":0.7528,\"jitter_cv\":0.062442181466563364,\"cache_hierarchy_ratio\":0.856}", +"device_arch": "modern" +}, +{ +"miner": "honest-m4-005", +"ts": 1790292780, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +}, +{ +"miner": "honest-modern-068", +"ts": 1790292806, +"profile_json": "{\"clock_drift_cv\":0.075551,\"thermal_variance\":0.9959,\"jitter_cv\":0.14009500150849574,\"cache_hierarchy_ratio\":1.028}", +"device_arch": "modern" +}, +{ +"miner": "honest-m2-004", +"ts": 1790292822, +"profile_json": "{\"clock_drift_cv\":0.514547,\"thermal_variance\":1.006,\"jitter_cv\":0.05092521874007235,\"cache_hierarchy_ratio\":0.99}", +"device_arch": "M2" +}, +{ +"miner": "honest-modern-068", +"ts": 1790292868, +"profile_json": "{\"clock_drift_cv\":0.16203,\"thermal_variance\":0.8429,\"jitter_cv\":0.16271161610633658,\"cache_hierarchy_ratio\":1.004}", +"device_arch": "modern" +}, +{ +"miner": "honest-aarch64-060", +"ts": 1790292870, +"profile_json": "{\"clock_drift_cv\":0.005009,\"thermal_variance\":0.998,\"jitter_cv\":0.007090360411765843,\"cache_hierarchy_ratio\":0.988}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-modern-080", +"ts": 1790292958, +"profile_json": "{\"clock_drift_cv\":0.427971,\"thermal_variance\":0.9685,\"jitter_cv\":0.3923040143320424,\"cache_hierarchy_ratio\":0.857}", +"device_arch": "modern" +}, +{ +"miner": "honest-aarch64-025", +"ts": 1790293005, +"profile_json": "{\"clock_drift_cv\":0.86725,\"thermal_variance\":1.229,\"jitter_cv\":0.38217577837959993,\"cache_hierarchy_ratio\":1.84}", +"device_arch": "aarch64" +}, +{ +"miner": "honest-modern-081", +"ts": 1790293030, +"profile_json": "{\"clock_drift_cv\":0.270864,\"thermal_variance\":0.8688,\"jitter_cv\":0.054061915991534364,\"cache_hierarchy_ratio\":0.991}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-033", +"ts": 1790293073, +"profile_json": "{\"clock_drift_cv\":0.452453,\"thermal_variance\":0.9851,\"jitter_cv\":0.03815999918264478,\"cache_hierarchy_ratio\":1.067}", +"device_arch": "modern" +}, +{ +"miner": "honest-modern-062", +"ts": 1790293073, +"profile_json": "{\"clock_drift_cv\":2.386849,\"thermal_variance\":0.9879,\"jitter_cv\":0.0442768907339667,\"cache_hierarchy_ratio\":1.019}", +"device_arch": "modern" +}, +{ +"miner": "honest-m4-005", +"ts": 1790293091, +"profile_json": "{\"clock_drift_cv\":0.152137,\"thermal_variance\":1.0359,\"jitter_cv\":0.06891609025287015,\"cache_hierarchy_ratio\":0.968}", +"device_arch": "M4" +} +] \ No newline at end of file diff --git a/node/tests/sybil_guard/fixtures/sybil_profiles.json b/node/tests/sybil_guard/fixtures/sybil_profiles.json new file mode 100644 index 000000000..c3e411285 --- /dev/null +++ b/node/tests/sybil_guard/fixtures/sybil_profiles.json @@ -0,0 +1,954 @@ +[ +{ +"miner": "RTCaf5b745bba356cda6f34a25c4e5ba7c67f2ee382", +"ts": 1790275507, +"profile_json": "{\"clock_drift_cv\":0.0085,\"thermal_variance\":5.1316,\"jitter_cv\":0.1925,\"cache_hierarchy_ratio\":2.0821}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC6a63ea02f6863152ab9b084ba1b8aafbd928dd78", +"ts": 1790275706, +"profile_json": "{\"clock_drift_cv\":0.0299,\"thermal_variance\":3.1217,\"jitter_cv\":0.1665,\"cache_hierarchy_ratio\":2.6652}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC8b1a736365ad9c02356be7670bd5377a7e423c30", +"ts": 1790275857, +"profile_json": "{\"clock_drift_cv\":0.0105,\"thermal_variance\":0.8515,\"jitter_cv\":0.2092,\"cache_hierarchy_ratio\":2.2763}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC0a5aee7551721b7ca0d8c0c11a636318d8bc07ce", +"ts": 1790276042, +"profile_json": "{\"clock_drift_cv\":0.0248,\"thermal_variance\":5.9022,\"jitter_cv\":0.1186,\"cache_hierarchy_ratio\":2.5918}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC36cdadf2dbb0a31735fc7354f5113e04b7cdcb79", +"ts": 1790276209, +"profile_json": "{\"clock_drift_cv\":0.0134,\"thermal_variance\":5.6258,\"jitter_cv\":0.0153,\"cache_hierarchy_ratio\":1.8368}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCfd02bac18e67a85ac08e6b5f5305fe6f58d357b7", +"ts": 1790276300, +"profile_json": "{\"clock_drift_cv\":0.009,\"thermal_variance\":3.586,\"jitter_cv\":0.2473,\"cache_hierarchy_ratio\":2.2199}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC277528748bc77ae29f39d4eab6a39c3e9a1c3f90", +"ts": 1790276413, +"profile_json": "{\"clock_drift_cv\":0.0131,\"thermal_variance\":2.9835,\"jitter_cv\":0.022,\"cache_hierarchy_ratio\":1.8034}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCff53f4467db180c5415f45db0172bdb657dbdbba", +"ts": 1790276619, +"profile_json": "{\"clock_drift_cv\":0.0179,\"thermal_variance\":3.3557,\"jitter_cv\":0.0694,\"cache_hierarchy_ratio\":2.8961}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCaf5b745bba356cda6f34a25c4e5ba7c67f2ee382", +"ts": 1790276707, +"profile_json": "{\"clock_drift_cv\":0.0085,\"thermal_variance\":5.1316,\"jitter_cv\":0.1925,\"cache_hierarchy_ratio\":2.0821}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC7838ed02c0beedabdc88c32d6cfbe6e4837eff2c", +"ts": 1790276777, +"profile_json": "{\"clock_drift_cv\":0.0132,\"thermal_variance\":3.1728,\"jitter_cv\":0.0825,\"cache_hierarchy_ratio\":1.8269}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC9b840c5d162548ed8e45df7d6db3d9e7c29ed112", +"ts": 1790276889, +"profile_json": "{\"clock_drift_cv\":0.0264,\"thermal_variance\":3.662,\"jitter_cv\":0.1643,\"cache_hierarchy_ratio\":2.0065}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC5796f238e863e12b52f0f2faaa8b9afd20f6eec0", +"ts": 1790277021, +"profile_json": "{\"clock_drift_cv\":0.0297,\"thermal_variance\":5.1948,\"jitter_cv\":0.0433,\"cache_hierarchy_ratio\":2.1669}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC8937a6b74550532e6a239821b999a50bdf87caec", +"ts": 1790277108, +"profile_json": "{\"clock_drift_cv\":0.0239,\"thermal_variance\":4.4435,\"jitter_cv\":0.2326,\"cache_hierarchy_ratio\":2.2646}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCda93e09e70656a1f58ce5080568775209426b888", +"ts": 1790277174, +"profile_json": "{\"clock_drift_cv\":0.0263,\"thermal_variance\":4.237,\"jitter_cv\":0.0857,\"cache_hierarchy_ratio\":2.4454}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCcb4375ce2eb6555dc49427b3daf34abbe449961e", +"ts": 1790277264, +"profile_json": "{\"clock_drift_cv\":0.0274,\"thermal_variance\":5.1254,\"jitter_cv\":0.1325,\"cache_hierarchy_ratio\":2.447}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC0f6979d82b098d5cc1a1a467e7f52c8f265740bc", +"ts": 1790277469, +"profile_json": "{\"clock_drift_cv\":0.0092,\"thermal_variance\":2.0775,\"jitter_cv\":0.2003,\"cache_hierarchy_ratio\":2.2561}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCd3fddde88fee7b22ce3d488e3d968a269a62e813", +"ts": 1790277532, +"profile_json": "{\"clock_drift_cv\":0.0122,\"thermal_variance\":3.6233,\"jitter_cv\":0.1784,\"cache_hierarchy_ratio\":2.5404}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCc167dea420da0012e3836fdc8f92729238d952d3", +"ts": 1790277731, +"profile_json": "{\"clock_drift_cv\":0.0165,\"thermal_variance\":3.0686,\"jitter_cv\":0.1333,\"cache_hierarchy_ratio\":2.654}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCff53f4467db180c5415f45db0172bdb657dbdbba", +"ts": 1790277819, +"profile_json": "{\"clock_drift_cv\":0.0179,\"thermal_variance\":3.3557,\"jitter_cv\":0.0694,\"cache_hierarchy_ratio\":2.8961}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC49fc41c7dfc8c0b85689ad2836f2b091e22f6e09", +"ts": 1790277866, +"profile_json": "{\"clock_drift_cv\":0.0196,\"thermal_variance\":2.8377,\"jitter_cv\":0.1289,\"cache_hierarchy_ratio\":1.8357}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCaf5b745bba356cda6f34a25c4e5ba7c67f2ee382", +"ts": 1790277907, +"profile_json": "{\"clock_drift_cv\":0.0085,\"thermal_variance\":5.1316,\"jitter_cv\":0.1925,\"cache_hierarchy_ratio\":2.0821}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC5b195156d0b14ca787a56bf786326570128ea3a6", +"ts": 1790278098, +"profile_json": "{\"clock_drift_cv\":0.0094,\"thermal_variance\":4.4041,\"jitter_cv\":0.2434,\"cache_hierarchy_ratio\":2.4516}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC9a81117d336f765074d836ff4af88659afde2370", +"ts": 1790278324, +"profile_json": "{\"clock_drift_cv\":0.0169,\"thermal_variance\":1.7119,\"jitter_cv\":0.1318,\"cache_hierarchy_ratio\":2.8765}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCbb715d1a21c3cfea22b808b8fc1286aebe56538b", +"ts": 1790278418, +"profile_json": "{\"clock_drift_cv\":0.025,\"thermal_variance\":3.5769,\"jitter_cv\":0.2149,\"cache_hierarchy_ratio\":2.0571}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC15bcdfa72666734786d7a455488bc786e09508d5", +"ts": 1790278497, +"profile_json": "{\"clock_drift_cv\":0.0195,\"thermal_variance\":5.6621,\"jitter_cv\":0.1493,\"cache_hierarchy_ratio\":2.3051}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC0f6979d82b098d5cc1a1a467e7f52c8f265740bc", +"ts": 1790278669, +"profile_json": "{\"clock_drift_cv\":0.0092,\"thermal_variance\":2.0775,\"jitter_cv\":0.2003,\"cache_hierarchy_ratio\":2.2561}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC3978703c37b9ecdb39101496f00e7bcbc2e559e1", +"ts": 1790278685, +"profile_json": "{\"clock_drift_cv\":0.0143,\"thermal_variance\":3.6193,\"jitter_cv\":0.2374,\"cache_hierarchy_ratio\":1.8096}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCbe2662ad47ac1d1dbfac0695b04d1c62c37cf9dc", +"ts": 1790278840, +"profile_json": "{\"clock_drift_cv\":0.0253,\"thermal_variance\":4.9955,\"jitter_cv\":0.2209,\"cache_hierarchy_ratio\":2.6125}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCff53f4467db180c5415f45db0172bdb657dbdbba", +"ts": 1790279019, +"profile_json": "{\"clock_drift_cv\":0.0179,\"thermal_variance\":3.3557,\"jitter_cv\":0.0694,\"cache_hierarchy_ratio\":2.8961}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC45ca8effefdeb5d8bdfcdd6be88a76bcbfaaa3ca", +"ts": 1790279046, +"profile_json": "{\"clock_drift_cv\":0.0258,\"thermal_variance\":3.4712,\"jitter_cv\":0.1455,\"cache_hierarchy_ratio\":2.269}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC712a770f3f9b558c3b92563a4f994cd7ef865e53", +"ts": 1790279185, +"profile_json": "{\"clock_drift_cv\":0.0097,\"thermal_variance\":5.2457,\"jitter_cv\":0.1475,\"cache_hierarchy_ratio\":2.0218}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC5728099f64adb6afb381d63f87c15481020059de", +"ts": 1790279356, +"profile_json": "{\"clock_drift_cv\":0.0193,\"thermal_variance\":3.3007,\"jitter_cv\":0.0981,\"cache_hierarchy_ratio\":2.1816}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCeef02f38c54abac9a169ca005204c262c9326f14", +"ts": 1790279544, +"profile_json": "{\"clock_drift_cv\":0.02,\"thermal_variance\":4.0006,\"jitter_cv\":0.1574,\"cache_hierarchy_ratio\":2.304}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC15bcdfa72666734786d7a455488bc786e09508d5", +"ts": 1790279697, +"profile_json": "{\"clock_drift_cv\":0.0195,\"thermal_variance\":5.6621,\"jitter_cv\":0.1493,\"cache_hierarchy_ratio\":2.3051}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC49514292857680c682eb80df744955276b9d2491", +"ts": 1790279777, +"profile_json": "{\"clock_drift_cv\":0.0091,\"thermal_variance\":2.0112,\"jitter_cv\":0.0564,\"cache_hierarchy_ratio\":2.442}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC0f6979d82b098d5cc1a1a467e7f52c8f265740bc", +"ts": 1790279869, +"profile_json": "{\"clock_drift_cv\":0.0092,\"thermal_variance\":2.0775,\"jitter_cv\":0.2003,\"cache_hierarchy_ratio\":2.2561}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC9337f4a13f7e437f1c3436eaba3b4f27509bef1f", +"ts": 1790279928, +"profile_json": "{\"clock_drift_cv\":0.0269,\"thermal_variance\":4.8842,\"jitter_cv\":0.2002,\"cache_hierarchy_ratio\":2.6955}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC3a9ac6e23b85a0d06460d04aa0b0d3be1cdaac11", +"ts": 1790280123, +"profile_json": "{\"clock_drift_cv\":0.014,\"thermal_variance\":5.1029,\"jitter_cv\":0.1715,\"cache_hierarchy_ratio\":1.8943}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCe2e9341d53c125210763173b287cac7c193de5d3", +"ts": 1790280265, +"profile_json": "{\"clock_drift_cv\":0.0089,\"thermal_variance\":0.925,\"jitter_cv\":0.1906,\"cache_hierarchy_ratio\":2.0761}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC75082cc0c1176212070bca45ec55f4d49f5fdd07", +"ts": 1790280325, +"profile_json": "{\"clock_drift_cv\":0.0108,\"thermal_variance\":4.0072,\"jitter_cv\":0.0952,\"cache_hierarchy_ratio\":1.8794}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC84b79b60887e414671f890d9501633a208707a32", +"ts": 1790280416, +"profile_json": "{\"clock_drift_cv\":0.0119,\"thermal_variance\":3.5151,\"jitter_cv\":0.0543,\"cache_hierarchy_ratio\":2.1016}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCd115c7f7ed247fcda74e607b0ae2764768ef85b2", +"ts": 1790280589, +"profile_json": "{\"clock_drift_cv\":0.0237,\"thermal_variance\":3.1481,\"jitter_cv\":0.09,\"cache_hierarchy_ratio\":2.3211}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCaef1c90db7ab6db5b2b0e961a08009d9fb5d4b12", +"ts": 1790280764, +"profile_json": "{\"clock_drift_cv\":0.009,\"thermal_variance\":2.8039,\"jitter_cv\":0.113,\"cache_hierarchy_ratio\":2.0089}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC15bcdfa72666734786d7a455488bc786e09508d5", +"ts": 1790280897, +"profile_json": "{\"clock_drift_cv\":0.0195,\"thermal_variance\":5.6621,\"jitter_cv\":0.1493,\"cache_hierarchy_ratio\":2.3051}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCa66b0fcfd92ff9df13a72a67451f9c0711e7ae5c", +"ts": 1790280913, +"profile_json": "{\"clock_drift_cv\":0.0108,\"thermal_variance\":5.3962,\"jitter_cv\":0.1336,\"cache_hierarchy_ratio\":2.0319}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC49514292857680c682eb80df744955276b9d2491", +"ts": 1790280977, +"profile_json": "{\"clock_drift_cv\":0.0091,\"thermal_variance\":2.0112,\"jitter_cv\":0.0564,\"cache_hierarchy_ratio\":2.442}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCeeb4473611ca8d8e1cd98b193fc0110f73f5f1ae", +"ts": 1790281051, +"profile_json": "{\"clock_drift_cv\":0.0215,\"thermal_variance\":4.9781,\"jitter_cv\":0.0201,\"cache_hierarchy_ratio\":1.8229}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC1432bed68b5e4fb7c4fb056d5668ab57cbb1e9b5", +"ts": 1790281249, +"profile_json": "{\"clock_drift_cv\":0.0116,\"thermal_variance\":4.4821,\"jitter_cv\":0.0525,\"cache_hierarchy_ratio\":2.5733}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC2f88fa83f61ef1202d9f9dbad0c1d2f7ac1cb730", +"ts": 1790281411, +"profile_json": "{\"clock_drift_cv\":0.023,\"thermal_variance\":3.6026,\"jitter_cv\":0.0665,\"cache_hierarchy_ratio\":2.8694}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC5cc4f1a8a9d93d6c41847ee0177595905da298a0", +"ts": 1790281557, +"profile_json": "{\"clock_drift_cv\":0.0256,\"thermal_variance\":3.4607,\"jitter_cv\":0.0671,\"cache_hierarchy_ratio\":2.512}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC0b3ffa0f6b65bd8cf173c09d348a822af6f45a0f", +"ts": 1790281791, +"profile_json": "{\"clock_drift_cv\":0.017,\"thermal_variance\":3.7599,\"jitter_cv\":0.0898,\"cache_hierarchy_ratio\":2.4928}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCaef1c90db7ab6db5b2b0e961a08009d9fb5d4b12", +"ts": 1790281964, +"profile_json": "{\"clock_drift_cv\":0.009,\"thermal_variance\":2.8039,\"jitter_cv\":0.113,\"cache_hierarchy_ratio\":2.0089}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCa1dc4cd5b3d81a084c83d67bf4660fb62695b647", +"ts": 1790281997, +"profile_json": "{\"clock_drift_cv\":0.0098,\"thermal_variance\":2.3597,\"jitter_cv\":0.2399,\"cache_hierarchy_ratio\":2.7601}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC49514292857680c682eb80df744955276b9d2491", +"ts": 1790282177, +"profile_json": "{\"clock_drift_cv\":0.0091,\"thermal_variance\":2.0112,\"jitter_cv\":0.0564,\"cache_hierarchy_ratio\":2.442}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC7cd55b71d9987599edceaa62196b51b68050c72f", +"ts": 1790282183, +"profile_json": "{\"clock_drift_cv\":0.0151,\"thermal_variance\":5.1876,\"jitter_cv\":0.0873,\"cache_hierarchy_ratio\":2.8298}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCf3ca83ef310846d083427ce6b55c2cd7c6b51b53", +"ts": 1790282271, +"profile_json": "{\"clock_drift_cv\":0.0244,\"thermal_variance\":2.9535,\"jitter_cv\":0.0738,\"cache_hierarchy_ratio\":1.8127}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC048bbdc9122fdd695eebd51016af7e17dc675c8d", +"ts": 1790282496, +"profile_json": "{\"clock_drift_cv\":0.0273,\"thermal_variance\":1.043,\"jitter_cv\":0.2054,\"cache_hierarchy_ratio\":2.8548}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCee06a7954a80965ed7b3aa7f129cc6dbf09200b7", +"ts": 1790282652, +"profile_json": "{\"clock_drift_cv\":0.0207,\"thermal_variance\":1.7178,\"jitter_cv\":0.2166,\"cache_hierarchy_ratio\":2.8674}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCa631ab2b749075fc6060e56f4e75c17122f2c9a3", +"ts": 1790282809, +"profile_json": "{\"clock_drift_cv\":0.0236,\"thermal_variance\":3.4217,\"jitter_cv\":0.103,\"cache_hierarchy_ratio\":2.1825}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCf43a7dc14329b835d0f45b4ec9dbc8809796ada9", +"ts": 1790282921, +"profile_json": "{\"clock_drift_cv\":0.0129,\"thermal_variance\":4.2564,\"jitter_cv\":0.1157,\"cache_hierarchy_ratio\":2.0155}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCfc5c81d42f95f7de20301c5eece7d4d71d4ad3f9", +"ts": 1790283123, +"profile_json": "{\"clock_drift_cv\":0.0107,\"thermal_variance\":4.2151,\"jitter_cv\":0.084,\"cache_hierarchy_ratio\":2.3495}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCaef1c90db7ab6db5b2b0e961a08009d9fb5d4b12", +"ts": 1790283164, +"profile_json": "{\"clock_drift_cv\":0.009,\"thermal_variance\":2.8039,\"jitter_cv\":0.113,\"cache_hierarchy_ratio\":2.0089}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC8ef5de373e70f974d637c83f0cfbe10dfa8de2ed", +"ts": 1790283183, +"profile_json": "{\"clock_drift_cv\":0.0155,\"thermal_variance\":5.2538,\"jitter_cv\":0.224,\"cache_hierarchy_ratio\":1.8232}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCa1dc4cd5b3d81a084c83d67bf4660fb62695b647", +"ts": 1790283197, +"profile_json": "{\"clock_drift_cv\":0.0098,\"thermal_variance\":2.3597,\"jitter_cv\":0.2399,\"cache_hierarchy_ratio\":2.7601}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC74c30651c7621a4cd7c5b41c731885f8c4dd18e0", +"ts": 1790283314, +"profile_json": "{\"clock_drift_cv\":0.0128,\"thermal_variance\":2.5068,\"jitter_cv\":0.2443,\"cache_hierarchy_ratio\":2.6587}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC6e943dcfd9e9aedc45cdb972c62e027d1c3ac23f", +"ts": 1790283536, +"profile_json": "{\"clock_drift_cv\":0.0158,\"thermal_variance\":1.9274,\"jitter_cv\":0.1718,\"cache_hierarchy_ratio\":2.7188}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCb6d8e67df9777e13d923dab1ae22ae1fb211f207", +"ts": 1790283749, +"profile_json": "{\"clock_drift_cv\":0.0284,\"thermal_variance\":2.5882,\"jitter_cv\":0.22,\"cache_hierarchy_ratio\":2.5542}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC569e112ad4963c6bb79086c924ea07ffd5ae9f50", +"ts": 1790283939, +"profile_json": "{\"clock_drift_cv\":0.0189,\"thermal_variance\":5.829,\"jitter_cv\":0.0697,\"cache_hierarchy_ratio\":2.5961}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCad5ebde93fc0780a8610bcefb11d01d8ad5deada", +"ts": 1790284049, +"profile_json": "{\"clock_drift_cv\":0.0103,\"thermal_variance\":1.7086,\"jitter_cv\":0.2266,\"cache_hierarchy_ratio\":2.0361}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC0e62bb8c049d071f1460319169cf8a3259f3203f", +"ts": 1790284227, +"profile_json": "{\"clock_drift_cv\":0.0247,\"thermal_variance\":3.883,\"jitter_cv\":0.2104,\"cache_hierarchy_ratio\":2.2056}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCfc5c81d42f95f7de20301c5eece7d4d71d4ad3f9", +"ts": 1790284323, +"profile_json": "{\"clock_drift_cv\":0.0107,\"thermal_variance\":4.2151,\"jitter_cv\":0.084,\"cache_hierarchy_ratio\":2.3495}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCa1dc4cd5b3d81a084c83d67bf4660fb62695b647", +"ts": 1790284397, +"profile_json": "{\"clock_drift_cv\":0.0098,\"thermal_variance\":2.3597,\"jitter_cv\":0.2399,\"cache_hierarchy_ratio\":2.7601}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC71d709f38fbc2c79371d17b806efaa8bc453e771", +"ts": 1790284440, +"profile_json": "{\"clock_drift_cv\":0.0158,\"thermal_variance\":2.3223,\"jitter_cv\":0.2165,\"cache_hierarchy_ratio\":2.4634}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCecfcfbcfd6845627a7bc8cc6c2fc1cfafbf5712e", +"ts": 1790284632, +"profile_json": "{\"clock_drift_cv\":0.0289,\"thermal_variance\":5.3328,\"jitter_cv\":0.0467,\"cache_hierarchy_ratio\":2.4057}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTCbca0af25e98fb1b75f9274d6ae2026236ae804cf", +"ts": 1790284796, +"profile_json": "{\"clock_drift_cv\":0.0107,\"thermal_variance\":1.0492,\"jitter_cv\":0.0323,\"cache_hierarchy_ratio\":2.7499}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC6b2c509406752f7ac03f0480a5c965234265487c", +"ts": 1790284934, +"profile_json": "{\"clock_drift_cv\":0.0254,\"thermal_variance\":5.036,\"jitter_cv\":0.0944,\"cache_hierarchy_ratio\":2.4756}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC52098cb47e4e81cc4e088a2f439685fb807a6b25", +"ts": 1790285173, +"profile_json": "{\"clock_drift_cv\":0.0252,\"thermal_variance\":2.7609,\"jitter_cv\":0.1477,\"cache_hierarchy_ratio\":2.0479}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC065f73f2840eee3e90c96b9066692edf9bea7979", +"ts": 1790285276, +"profile_json": "{\"clock_drift_cv\":0.0102,\"thermal_variance\":2.1986,\"jitter_cv\":0.222,\"cache_hierarchy_ratio\":2.4202}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCeb56c43a48d6874588ec555acdc9b397ada08a18", +"ts": 1790285451, +"profile_json": "{\"clock_drift_cv\":0.0283,\"thermal_variance\":3.1636,\"jitter_cv\":0.0796,\"cache_hierarchy_ratio\":2.6634}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCfc5c81d42f95f7de20301c5eece7d4d71d4ad3f9", +"ts": 1790285523, +"profile_json": "{\"clock_drift_cv\":0.0107,\"thermal_variance\":4.2151,\"jitter_cv\":0.084,\"cache_hierarchy_ratio\":2.3495}", +"source_ip": "203.0.113.10", +"device_arch": "G4" +}, +{ +"miner": "RTC54e60fbc77d9f8473c514bf7d722d52356d02698", +"ts": 1790285669, +"profile_json": "{\"clock_drift_cv\":0.0262,\"thermal_variance\":0.914,\"jitter_cv\":0.1708,\"cache_hierarchy_ratio\":1.9036}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC032b8ba07d46898a229c38eae14c0363c7333397", +"ts": 1790285900, +"profile_json": "{\"clock_drift_cv\":0.011,\"thermal_variance\":5.3217,\"jitter_cv\":0.0246,\"cache_hierarchy_ratio\":2.0652}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC086a089026f341bf0922a7906a0dbffab647ae40", +"ts": 1790286095, +"profile_json": "{\"clock_drift_cv\":0.0296,\"thermal_variance\":2.9779,\"jitter_cv\":0.0421,\"cache_hierarchy_ratio\":1.9863}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC9c8901d9acad1aae925a20e425337a3c1dc29a7a", +"ts": 1790286205, +"profile_json": "{\"clock_drift_cv\":0.0137,\"thermal_variance\":4.6093,\"jitter_cv\":0.0392,\"cache_hierarchy_ratio\":2.7986}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCb87226437e133ba9da5914f2dfa84ab7319eaecd", +"ts": 1790286357, +"profile_json": "{\"clock_drift_cv\":0.0166,\"thermal_variance\":5.752,\"jitter_cv\":0.2262,\"cache_hierarchy_ratio\":2.1247}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC899d97c08bed6c82c198f979cf27668604350329", +"ts": 1790286551, +"profile_json": "{\"clock_drift_cv\":0.0139,\"thermal_variance\":3.2607,\"jitter_cv\":0.0385,\"cache_hierarchy_ratio\":2.5159}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC60e4858af9cf254168d3032773f38bc46ebb2665", +"ts": 1790286611, +"profile_json": "{\"clock_drift_cv\":0.0093,\"thermal_variance\":0.9046,\"jitter_cv\":0.2433,\"cache_hierarchy_ratio\":2.1263}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC287ad6d568edc4e4214f97167e32cf4ebb381584", +"ts": 1790286844, +"profile_json": "{\"clock_drift_cv\":0.0213,\"thermal_variance\":3.1235,\"jitter_cv\":0.088,\"cache_hierarchy_ratio\":1.8722}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCd9ecf02fc562f14f9c4bd292460e6c0d67f374d5", +"ts": 1790287003, +"profile_json": "{\"clock_drift_cv\":0.028,\"thermal_variance\":5.7497,\"jitter_cv\":0.2403,\"cache_hierarchy_ratio\":1.9251}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC2c5054a8d6548c097f018cea395b085cf215179f", +"ts": 1790287211, +"profile_json": "{\"clock_drift_cv\":0.0131,\"thermal_variance\":3.9719,\"jitter_cv\":0.2426,\"cache_hierarchy_ratio\":2.3966}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC5c616069e125a5cbdf14da8acf51a8037b2a8742", +"ts": 1790287380, +"profile_json": "{\"clock_drift_cv\":0.0232,\"thermal_variance\":4.1942,\"jitter_cv\":0.0754,\"cache_hierarchy_ratio\":2.3952}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCe9ee116b6ca0172f25155946b843810ea29f9779", +"ts": 1790287543, +"profile_json": "{\"clock_drift_cv\":0.0151,\"thermal_variance\":2.0959,\"jitter_cv\":0.0342,\"cache_hierarchy_ratio\":2.1102}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC12677170bc3eee64b288b51fb8dd288264674503", +"ts": 1790287689, +"profile_json": "{\"clock_drift_cv\":0.0295,\"thermal_variance\":3.1137,\"jitter_cv\":0.1666,\"cache_hierarchy_ratio\":2.5065}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCee241985e0f2ee04942f5a10764a59117f695916", +"ts": 1790287908, +"profile_json": "{\"clock_drift_cv\":0.0286,\"thermal_variance\":2.8237,\"jitter_cv\":0.0865,\"cache_hierarchy_ratio\":2.161}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC44ffd09c89a9c9438c9281df141dd38570f0f387", +"ts": 1790288117, +"profile_json": "{\"clock_drift_cv\":0.0153,\"thermal_variance\":5.1301,\"jitter_cv\":0.2226,\"cache_hierarchy_ratio\":2.1343}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC9e1730039edd38df989a57b13fca83e0268654f8", +"ts": 1790288356, +"profile_json": "{\"clock_drift_cv\":0.0157,\"thermal_variance\":3.6002,\"jitter_cv\":0.1496,\"cache_hierarchy_ratio\":2.4546}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCf3a9da9dd67bd464bbae18c13583890c14e5b81a", +"ts": 1790288433, +"profile_json": "{\"clock_drift_cv\":0.0137,\"thermal_variance\":0.9544,\"jitter_cv\":0.0719,\"cache_hierarchy_ratio\":1.8824}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCb7c89d01f5abef18feb1f4e44db47e854d2a5349", +"ts": 1790288619, +"profile_json": "{\"clock_drift_cv\":0.0203,\"thermal_variance\":1.2097,\"jitter_cv\":0.0327,\"cache_hierarchy_ratio\":2.4977}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC0d53e3b68bf1c9a6bd344b52e8815e3ad2cbcc4c", +"ts": 1790288742, +"profile_json": "{\"clock_drift_cv\":0.0147,\"thermal_variance\":4.8526,\"jitter_cv\":0.1297,\"cache_hierarchy_ratio\":2.746}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC30239409d78aeb0cd04ec31105c6c6c653ce4b95", +"ts": 1790288965, +"profile_json": "{\"clock_drift_cv\":0.0118,\"thermal_variance\":3.3841,\"jitter_cv\":0.1997,\"cache_hierarchy_ratio\":1.8877}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC9cd19b51c3c58e93990b7c04ce7e41c9058ad371", +"ts": 1790289191, +"profile_json": "{\"clock_drift_cv\":0.0288,\"thermal_variance\":1.7265,\"jitter_cv\":0.1954,\"cache_hierarchy_ratio\":2.8796}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCbcfdc1de5ccf9ed05a6590b86149361592daa58d", +"ts": 1790289325, +"profile_json": "{\"clock_drift_cv\":0.0261,\"thermal_variance\":2.4666,\"jitter_cv\":0.0401,\"cache_hierarchy_ratio\":2.3654}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC3225699505920fb9b064f8443dad5964027e8f07", +"ts": 1790289546, +"profile_json": "{\"clock_drift_cv\":0.0282,\"thermal_variance\":2.3338,\"jitter_cv\":0.2227,\"cache_hierarchy_ratio\":1.9582}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC834cbe55452ab786f3b85c449b888cf935613da0", +"ts": 1790289611, +"profile_json": "{\"clock_drift_cv\":0.028,\"thermal_variance\":1.0119,\"jitter_cv\":0.0886,\"cache_hierarchy_ratio\":2.7902}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCfe6c67fb996dc67d99072a02da0f1c954215f77b", +"ts": 1790289775, +"profile_json": "{\"clock_drift_cv\":0.0257,\"thermal_variance\":5.4333,\"jitter_cv\":0.2103,\"cache_hierarchy_ratio\":2.6188}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC3ff9e1d17798d98199ea03c42831dc12b9a2c8d1", +"ts": 1790289996, +"profile_json": "{\"clock_drift_cv\":0.0233,\"thermal_variance\":1.7513,\"jitter_cv\":0.1157,\"cache_hierarchy_ratio\":1.9759}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCe291740b62fb4fb11fc52120aff033424f6aecb4", +"ts": 1790290095, +"profile_json": "{\"clock_drift_cv\":0.0238,\"thermal_variance\":4.2243,\"jitter_cv\":0.0739,\"cache_hierarchy_ratio\":1.8738}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC954e7ac516b4cf773961f67ad3f3c88b6419b99c", +"ts": 1790290317, +"profile_json": "{\"clock_drift_cv\":0.0291,\"thermal_variance\":4.9337,\"jitter_cv\":0.1427,\"cache_hierarchy_ratio\":2.395}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC06ad58b068acdcbb958926526475a5523acb5378", +"ts": 1790290478, +"profile_json": "{\"clock_drift_cv\":0.0267,\"thermal_variance\":3.141,\"jitter_cv\":0.1071,\"cache_hierarchy_ratio\":2.1735}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCe62c960558eb595e63252d30ac373c7ad0f34da6", +"ts": 1790290607, +"profile_json": "{\"clock_drift_cv\":0.014,\"thermal_variance\":0.9748,\"jitter_cv\":0.1653,\"cache_hierarchy_ratio\":2.2587}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC01c9a1429c1cb97efed26d897edf8fabefb90017", +"ts": 1790290712, +"profile_json": "{\"clock_drift_cv\":0.0207,\"thermal_variance\":1.1663,\"jitter_cv\":0.0976,\"cache_hierarchy_ratio\":1.9545}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCd1d1c1d6e1bd14ce7aceb598e8c8bf236d96be28", +"ts": 1790290790, +"profile_json": "{\"clock_drift_cv\":0.0112,\"thermal_variance\":2.1602,\"jitter_cv\":0.2076,\"cache_hierarchy_ratio\":2.2381}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCc11f7d5d5a13566a5549da64777065ed6c843b4e", +"ts": 1790291004, +"profile_json": "{\"clock_drift_cv\":0.0171,\"thermal_variance\":3.9448,\"jitter_cv\":0.0695,\"cache_hierarchy_ratio\":1.8116}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC7cc581dca67665c6ca1ec764140e3d7a8681524d", +"ts": 1790291066, +"profile_json": "{\"clock_drift_cv\":0.0198,\"thermal_variance\":3.3814,\"jitter_cv\":0.1658,\"cache_hierarchy_ratio\":2.2823}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC4176c97922bf7140eb18882d0d08753d3eeea2a2", +"ts": 1790291215, +"profile_json": "{\"clock_drift_cv\":0.0232,\"thermal_variance\":4.5457,\"jitter_cv\":0.0706,\"cache_hierarchy_ratio\":2.3444}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC6f840af10b0f91ba400ab601d6bbefa670fce621", +"ts": 1790291342, +"profile_json": "{\"clock_drift_cv\":0.0187,\"thermal_variance\":1.9882,\"jitter_cv\":0.1109,\"cache_hierarchy_ratio\":2.4158}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC19948cfc1bdbb989567d1b64147e4093788e306b", +"ts": 1790291507, +"profile_json": "{\"clock_drift_cv\":0.0279,\"thermal_variance\":5.4866,\"jitter_cv\":0.0792,\"cache_hierarchy_ratio\":2.5097}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC760704240ab61bc28e972aee965f4c3da78ff82d", +"ts": 1790291742, +"profile_json": "{\"clock_drift_cv\":0.0095,\"thermal_variance\":1.2129,\"jitter_cv\":0.134,\"cache_hierarchy_ratio\":2.7622}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTCbccb40f2ad900e9d10cf82be2a26402aaaf35292", +"ts": 1790291941, +"profile_json": "{\"clock_drift_cv\":0.0119,\"thermal_variance\":4.7205,\"jitter_cv\":0.2202,\"cache_hierarchy_ratio\":2.1441}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC3744642e306cfd52262f2ffd74008af78a438dfc", +"ts": 1790292078, +"profile_json": "{\"clock_drift_cv\":0.0233,\"thermal_variance\":5.1395,\"jitter_cv\":0.1015,\"cache_hierarchy_ratio\":2.5697}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC97b5bb89da2b5ca6aa2c99a8cf59222e38224f68", +"ts": 1790292176, +"profile_json": "{\"clock_drift_cv\":0.0243,\"thermal_variance\":3.8545,\"jitter_cv\":0.214,\"cache_hierarchy_ratio\":2.7831}", +"source_ip": "198.51.100.20", +"device_arch": "G4" +}, +{ +"miner": "RTC294f0fc129b741cfc2ebe9c74dfb0a4e6cedbcee", +"ts": 1790292354, +"profile_json": "{\"clock_drift_cv\":0.029,\"thermal_variance\":3.7366,\"jitter_cv\":0.0562,\"cache_hierarchy_ratio\":2.0772}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC9a9e9fad5e523b37eec321f0bc905ddac314875f", +"ts": 1790292480, +"profile_json": "{\"clock_drift_cv\":0.0132,\"thermal_variance\":3.728,\"jitter_cv\":0.1911,\"cache_hierarchy_ratio\":1.8604}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTCae5c5b79df7cdc2301bf7b6854060eb6eb345fa3", +"ts": 1790292664, +"profile_json": "{\"clock_drift_cv\":0.0231,\"thermal_variance\":4.4736,\"jitter_cv\":0.096,\"cache_hierarchy_ratio\":2.3662}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTCd51d689c4e8e7c85dadb4b9812413d198d7eccae", +"ts": 1790292767, +"profile_json": "{\"clock_drift_cv\":0.012,\"thermal_variance\":4.538,\"jitter_cv\":0.0247,\"cache_hierarchy_ratio\":2.8756}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC5c492135ec1cbf328e642ce09b419d71ae1bffbf", +"ts": 1790292946, +"profile_json": "{\"clock_drift_cv\":0.0258,\"thermal_variance\":4.0256,\"jitter_cv\":0.0774,\"cache_hierarchy_ratio\":2.8009}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC3c062866fc89d8519af0153becf1b22af84b0325", +"ts": 1790293136, +"profile_json": "{\"clock_drift_cv\":0.029,\"thermal_variance\":1.5542,\"jitter_cv\":0.1953,\"cache_hierarchy_ratio\":2.7234}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC417552d59baac33b7fa8998ddcdbe569f22da47d", +"ts": 1790293207, +"profile_json": "{\"clock_drift_cv\":0.0226,\"thermal_variance\":4.389,\"jitter_cv\":0.1186,\"cache_hierarchy_ratio\":2.8134}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC6ab7afb258967efaedc70fcd9db8d2f3efd71d48", +"ts": 1790293336, +"profile_json": "{\"clock_drift_cv\":0.0293,\"thermal_variance\":2.7827,\"jitter_cv\":0.2015,\"cache_hierarchy_ratio\":2.2765}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC66017003b8ea03b46c7836d7f618039c3a086769", +"ts": 1790293526, +"profile_json": "{\"clock_drift_cv\":0.012,\"thermal_variance\":2.4953,\"jitter_cv\":0.0446,\"cache_hierarchy_ratio\":2.7965}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC6e6271ba90169f6798d4034e6bbe913e2d4c37c6", +"ts": 1790293611, +"profile_json": "{\"clock_drift_cv\":0.029,\"thermal_variance\":1.4535,\"jitter_cv\":0.1547,\"cache_hierarchy_ratio\":2.2495}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC4230f6b0717c049c905295a49b6e97cf3674bf96", +"ts": 1790293822, +"profile_json": "{\"clock_drift_cv\":0.011,\"thermal_variance\":2.3439,\"jitter_cv\":0.0729,\"cache_hierarchy_ratio\":2.6225}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC3bc8cdc02b4585ba371ca7fd4c5002ab50ecb41c", +"ts": 1790293990, +"profile_json": "{\"clock_drift_cv\":0.0086,\"thermal_variance\":1.8103,\"jitter_cv\":0.1171,\"cache_hierarchy_ratio\":1.8264}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTCbe7ffe677c62b8fee8b8f044ba4f5d2d77180dbb", +"ts": 1790294067, +"profile_json": "{\"clock_drift_cv\":0.0219,\"thermal_variance\":3.9103,\"jitter_cv\":0.2091,\"cache_hierarchy_ratio\":2.0292}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTC583b3514ddfb06f477e4bbb375e4047875c98b6e", +"ts": 1790294217, +"profile_json": "{\"clock_drift_cv\":0.0146,\"thermal_variance\":3.5907,\"jitter_cv\":0.0787,\"cache_hierarchy_ratio\":2.4434}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +}, +{ +"miner": "RTCd99fd936b2075f5f23709613de5659dff11dfbe4", +"ts": 1790294294, +"profile_json": "{\"clock_drift_cv\":0.0139,\"thermal_variance\":4.3038,\"jitter_cv\":0.1988,\"cache_hierarchy_ratio\":2.687}", +"source_ip": "198.51.100.21", +"device_arch": "G4" +} +] \ No newline at end of file diff --git a/node/tests/sybil_guard/fixtures/wave2_profiles.json b/node/tests/sybil_guard/fixtures/wave2_profiles.json new file mode 100644 index 000000000..83e550dc9 --- /dev/null +++ b/node/tests/sybil_guard/fixtures/wave2_profiles.json @@ -0,0 +1,122 @@ +[ +{ +"miner": "RTCfd664ecfa1607b38e3cbeea0e28d18a1ddabc857", +"profile_json": "{\"clock_drift_cv\":0.029,\"thermal_variance\":5.6387,\"jitter_cv\":0.0284,\"cache_hierarchy_ratio\":1.8961}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTC52ae6f9953e1fe743f4008358752eec46aaec3ce", +"profile_json": "{\"clock_drift_cv\":0.0264,\"thermal_variance\":4.5687,\"jitter_cv\":0.1707,\"cache_hierarchy_ratio\":2.1401}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTCe1c83bc98fa6ceae834b8f390a376ad7726fd09d", +"profile_json": "{\"clock_drift_cv\":0.0215,\"thermal_variance\":3.9163,\"jitter_cv\":0.1501,\"cache_hierarchy_ratio\":1.9765}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTC1f0eb0f3fc026799047ac0ed6353b9f3baf5664e", +"profile_json": "{\"clock_drift_cv\":0.0177,\"thermal_variance\":2.8391,\"jitter_cv\":0.183,\"cache_hierarchy_ratio\":2.8904}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTCcc4ecd190f24b669d0bb6c10a322d2fe516e9c00", +"profile_json": "{\"clock_drift_cv\":0.0288,\"thermal_variance\":3.6,\"jitter_cv\":0.1185,\"cache_hierarchy_ratio\":2.0965}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTC2a82678a496d3db3634b78d60e7c4725e9feb660", +"profile_json": "{\"clock_drift_cv\":0.0093,\"thermal_variance\":0.9901,\"jitter_cv\":0.1232,\"cache_hierarchy_ratio\":2.1514}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTC559d48a02333c48f962baacf6b68a8ec025959dd", +"profile_json": "{\"clock_drift_cv\":0.008,\"thermal_variance\":1.2322,\"jitter_cv\":0.2056,\"cache_hierarchy_ratio\":2.5966}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTC5a86d7510d404390b08ada8efe08d9c0108ed853", +"profile_json": "{\"clock_drift_cv\":0.0081,\"thermal_variance\":1.8182,\"jitter_cv\":0.1881,\"cache_hierarchy_ratio\":1.8676}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTCb3aeaddc8c490723d1e5a8ed245d4dfbb937f5a7", +"profile_json": "{\"clock_drift_cv\":0.0166,\"thermal_variance\":5.3557,\"jitter_cv\":0.1373,\"cache_hierarchy_ratio\":2.4159}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTC5487ea678cab85780d9228ab5c79a00376fdeb0f", +"profile_json": "{\"clock_drift_cv\":0.0136,\"thermal_variance\":0.972,\"jitter_cv\":0.0907,\"cache_hierarchy_ratio\":1.9528}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTC552c912f8d31192896f21d4132cc11ecb65c8011", +"profile_json": "{\"clock_drift_cv\":0.0194,\"thermal_variance\":5.8956,\"jitter_cv\":0.1718,\"cache_hierarchy_ratio\":2.0021}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTCb7b076572fb84eebf0a4aa9ea3821ba8d4147aa7", +"profile_json": "{\"clock_drift_cv\":0.0276,\"thermal_variance\":4.8757,\"jitter_cv\":0.1857,\"cache_hierarchy_ratio\":2.794}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTCbde9a806ff5bf33735249bb2b5d520d277498d79", +"profile_json": "{\"clock_drift_cv\":0.0248,\"thermal_variance\":4.8403,\"jitter_cv\":0.0974,\"cache_hierarchy_ratio\":2.8753}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTC3117c87a0f7a019a1fefbc68c394f7b26dfdc1ef", +"profile_json": "{\"clock_drift_cv\":0.0291,\"thermal_variance\":1.6656,\"jitter_cv\":0.1902,\"cache_hierarchy_ratio\":2.5848}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTCc1f27a9a52316f73a816ab596c317cf03b4c704e", +"profile_json": "{\"clock_drift_cv\":0.0184,\"thermal_variance\":3.5302,\"jitter_cv\":0.129,\"cache_hierarchy_ratio\":2.814}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTC333c67c67b276e22ebef979b5409f5ce33e81967", +"profile_json": "{\"clock_drift_cv\":0.0192,\"thermal_variance\":5.0513,\"jitter_cv\":0.0974,\"cache_hierarchy_ratio\":2.7681}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTCefbecb5e9bfa4c4820eb02a99c461acc948a379d", +"profile_json": "{\"clock_drift_cv\":0.0083,\"thermal_variance\":2.2308,\"jitter_cv\":0.0679,\"cache_hierarchy_ratio\":2.76}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTCf94273239f1210bad369389c9664aa8297d8a65a", +"profile_json": "{\"clock_drift_cv\":0.0108,\"thermal_variance\":0.8123,\"jitter_cv\":0.2134,\"cache_hierarchy_ratio\":2.0709}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTC3d39bb1205797a4d9b128870646571a8beca5c5b", +"profile_json": "{\"clock_drift_cv\":0.0278,\"thermal_variance\":3.1799,\"jitter_cv\":0.147,\"cache_hierarchy_ratio\":2.809}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTC7377f843fdacea2e041ee0c0d2cf310557ea11b7", +"profile_json": "{\"clock_drift_cv\":0.024,\"thermal_variance\":3.3092,\"jitter_cv\":0.0668,\"cache_hierarchy_ratio\":2.1582}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTCe9abf2a01957f8285c0da4e512c08123681ef85a", +"profile_json": "{\"clock_drift_cv\":0.0235,\"thermal_variance\":1.6903,\"jitter_cv\":0.2259,\"cache_hierarchy_ratio\":2.0964}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTC14d3c9f74c32190aa140fd302a8e2c1dcd26076d", +"profile_json": "{\"clock_drift_cv\":0.028,\"thermal_variance\":2.415,\"jitter_cv\":0.2374,\"cache_hierarchy_ratio\":2.5751}", +"source_ip": "198.51.100.20" +}, +{ +"miner": "RTC9abd3e2dec079bee31ea49449798f9443fa9940d", +"profile_json": "{\"clock_drift_cv\":0.0193,\"thermal_variance\":3.4665,\"jitter_cv\":0.1664,\"cache_hierarchy_ratio\":2.4458}", +"source_ip": "203.0.113.10" +}, +{ +"miner": "RTCa411c409a22ef33156fc925fb138bd4c13e7b57d", +"profile_json": "{\"clock_drift_cv\":0.0152,\"thermal_variance\":1.9011,\"jitter_cv\":0.1341,\"cache_hierarchy_ratio\":2.8242}", +"source_ip": "198.51.100.20" +} +] \ No newline at end of file diff --git a/node/tests/sybil_guard/settle_probe.py b/node/tests/sybil_guard/settle_probe.py new file mode 100644 index 000000000..4ccac2aa9 --- /dev/null +++ b/node/tests/sybil_guard/settle_probe.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Run settle_epoch_rip200 from a given source dir against a synthetic DB. + +Usage: settle_probe.py [hold_json] +Prints the result JSON and per-miner balances. Runs in its own process so the +live and patched module sets never share sys.modules. +""" +import json +import os +import sqlite3 +import sys + +src, db, epoch, adm = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4] == "1" +sys.path.insert(0, src) +# the rest of node/ (utxo_db, db_helpers, ...) and sybil_guard for the patched run +sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))) +sys.modules["rustchain_p2p_sync_secure"] = None +os.environ.setdefault("RUSTCHAIN_DB_PATH", db) +os.environ.setdefault("DB_PATH", db) +import rewards_implementation_rip200 as ri # noqa: E402 + +ri.DB_PATH = db +res = ri.settle_epoch_rip200(db, epoch, enable_anti_double_mining=adm) +with sqlite3.connect(db) as c: + bal = dict(c.execute("SELECT miner_id, amount_i64 FROM balances")) + # The live (pre-guard) module set never creates the escrow table, so test + # for it explicitly instead of swallowing sqlite errors (falsegreen FG001): + # any real DB failure now propagates and the probe exits non-zero. + has_escrow = c.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='sybil_review_escrow'" + ).fetchone() is not None + esc = (c.execute("SELECT epoch, miner, would_be_weight_units, reason FROM sybil_review_escrow").fetchall() + if has_escrow else []) +print(json.dumps({"ok": res.get("ok"), "error": res.get("error"), "adm": "anti_double_mining_telemetry" in res, + "balances": bal, "escrow": esc, + "ADM_AVAILABLE": ri.ANTI_DOUBLE_MINING_AVAILABLE}, default=str)) diff --git a/node/tests/sybil_guard/sg_helpers.py b/node/tests/sybil_guard/sg_helpers.py new file mode 100644 index 000000000..57a19f277 --- /dev/null +++ b/node/tests/sybil_guard/sg_helpers.py @@ -0,0 +1,81 @@ +# SPDX-License-Identifier: MIT +"""Shared helpers for the sybil_guard test suite. + +NODE_DIR is the repo's node/ directory (the patched code under test). +BASELINE_DIR, when available, holds the PRE-PATCH versions of the four +settlement/attestation files, materialised from git at BASELINE_REF. Tests +that compare "before vs after" use it and are skipped when it cannot be +built (e.g. a shallow CI checkout); every other assertion still runs. +""" +import functools +import importlib.util +import json +import os +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +NODE_DIR = HERE.parents[1] +REPO = NODE_DIR.parent +FIXTURES = HERE / "fixtures" +NODE_FILE = "rustchain_v2_integrated_v2.2.1_rip200.py" +BASELINE_FILES = (NODE_FILE, "rip_200_round_robin_1cpu1vote.py", + "anti_double_mining.py", "rewards_implementation_rip200.py") +# main immediately before the sybil_guard change +BASELINE_REF = os.environ.get("SYBIL_GUARD_BASELINE_REF", "217ba85ef9cab3daac0da7b822c79437693444df") + +for p in (str(NODE_DIR), str(REPO)): + if p not in sys.path: + sys.path.insert(0, p) + + +def load_json(name): + return json.loads((FIXTURES / name).read_text()) + + +@functools.lru_cache(maxsize=1) +def baseline_dir(): + """Directory with the pre-patch files, or None if git cannot provide them.""" + out = Path(tempfile.mkdtemp(prefix="sybil_guard_baseline_")) + try: + for name in BASELINE_FILES: + blob = subprocess.run( + ["git", "-C", str(REPO), "show", f"{BASELINE_REF}:node/{name}"], + capture_output=True, check=True, timeout=60, + ).stdout + (out / name).write_bytes(blob) + except (OSError, subprocess.SubprocessError): + return None + return out + + +def load_node(db_path, tag, source_dir=NODE_DIR): + try: + from tests import mock_crypto # repo-root tests/mock_crypto.py + sys.modules["rustchain_crypto"] = mock_crypto + except Exception: + pass + os.environ["DB_PATH"] = str(db_path) + os.environ["RUSTCHAIN_DB_PATH"] = str(db_path) + os.environ.setdefault("RC_ADMIN_KEY", "0" * 32) + spec = importlib.util.spec_from_file_location(f"node_under_test_{tag}", Path(source_dir) / NODE_FILE) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + # Never start background peer sync from a test: make the node's optional + # P2P import fail for the duration of this load only (a permanent stub + # would break other suites that import the real module). + _p2p = "rustchain_p2p_sync_secure" + _had, _prev = _p2p in sys.modules, sys.modules.get(_p2p) + sys.modules[_p2p] = None + try: + spec.loader.exec_module(module) + finally: + if _had: + sys.modules[_p2p] = _prev + else: + sys.modules.pop(_p2p, None) + module.DB_PATH = str(db_path) + module.app.config["TESTING"] = True + return module diff --git a/node/tests/sybil_guard/test_adm_machine_identity.py b/node/tests/sybil_guard/test_adm_machine_identity.py new file mode 100644 index 000000000..e12fc5f02 --- /dev/null +++ b/node/tests/sybil_guard/test_adm_machine_identity.py @@ -0,0 +1,394 @@ +# SPDX-License-Identifier: MIT +"""ADM IDENTITY FIX (2026-09-25). + +Before: anti_double_mining keyed machines on hash(arch + profile["checks"]), +but the profile it reads is the flat 4-metric temporal profile, so every miner +hashed to hash(arch) and ADM paid ONE miner per architecture (prod epochs +250-295). Now a machine is identified only by persisted machine evidence: +same MAC hash (recent) AND same server-observed source_ip AND same arch. +""" +import sqlite3 + +import pytest + +import sg_helpers # noqa: F401 (node/ on sys.path; must precede node imports) +import anti_double_mining as adm +import rewards_implementation_rip200 as ri +import test_sybil_guard_settlement as tsg + +U = tsg.U +POT = ri.PER_EPOCH_URTC +EPOCH = tsg.EPOCH +G4 = tsg.HONEST_G4 +X86 = tsg.HONEST_X86 +EPOCH_START = adm.GENESIS_TIMESTAMP + EPOCH * 144 * adm.BLOCK_TIME + + +def _add_evidence(path, ips=None, macs=None, mac_ts=None): + """ips: {miner: ip}; macs: {miner: [mac_hash,...]}""" + c = sqlite3.connect(path) + c.execute("ALTER TABLE miner_attest_recent ADD COLUMN source_ip TEXT") + c.execute("CREATE TABLE miner_macs (miner TEXT NOT NULL, mac_hash TEXT NOT NULL, first_ts INTEGER " + "NOT NULL, last_ts INTEGER NOT NULL, count INTEGER DEFAULT 1, PRIMARY KEY (miner, mac_hash))") + for m, ip in (ips or {}).items(): + c.execute("UPDATE miner_attest_recent SET source_ip=? WHERE miner=?", (ip, m)) + ts = EPOCH_START + 60 if mac_ts is None else mac_ts + for m, hs in (macs or {}).items(): + for h in hs: + c.execute("INSERT INTO miner_macs VALUES (?,?,?,?,1)", (m, h, ts, ts)) + c.commit() + c.close() + + +def _settle(path, use_adm=True): + res = ri.settle_epoch_rip200(str(path), EPOCH, enable_anti_double_mining=use_adm) + assert res.get("ok") is True, res + bal = tsg.balances(str(path)) + assert sum(bal.values()) == POT # exactly 1.5 RTC, always + return res, bal + + +def test_same_arch_distinct_miners_are_not_collapsed(tmp_path): + db = tmp_path / "a.db" + tsg.make_db(str(db), [("g4-a", "G4", int(2.5 * U), G4), + ("g4-b", "G4", int(2.5 * U), {**G4, "clock_drift_cv": 0.0177}), + ("x86-a", "modern", int(0.8 * U), X86)]) + res, bal = _settle(db) + assert sorted(bal) == ["g4-a", "g4-b", "x86-a"] + assert res["anti_double_mining_telemetry"]["duplicate_miner_ids_skipped"] == 0 + + +def test_lab_g4s_with_identical_static_profile_behind_one_nat_all_paid(tmp_path): + """The lab's real G4s send the SAME constant profile from one WAN IP; distinct MACs.""" + db = tmp_path / "lab.db" + miners = [(f"g4-{i}", "G4", int(2.5 * U), G4) for i in range(4)] + tsg.make_db(str(db), miners) + _add_evidence(db, ips={m[0]: "203.0.113.7" for m in miners}, + macs={m[0]: [f"mac{i}"] for i, m in enumerate(miners)}) + _, bal = _settle(db) + assert sorted(bal) == [m[0] for m in miners] + assert len(set(bal.values())) == 1 or max(bal.values()) - min(bal.values()) <= 3 + + +def test_adm_matches_standard_path_when_no_duplicates(tmp_path): + rows = [("g4-a", "G4", int(2.5 * U), G4), ("g4-b", "G4", int(2.5 * U), G4), + ("x86-a", "modern", int(0.8 * U), X86), ("x86-b", "modern", U, X86)] + a, b = tmp_path / "adm.db", tmp_path / "std.db" + tsg.make_db(str(a), rows) + tsg.make_db(str(b), rows) + _, bal_a = _settle(a, True) + _, bal_b = _settle(b, False) + assert set(bal_a) == set(bal_b) + for m in bal_a: + assert abs(bal_a[m] - bal_b[m]) <= 3 # remainder placement only + + +def test_true_duplicate_same_mac_same_ip_same_arch_collapses_to_heaviest(tmp_path): + db = tmp_path / "dup.db" + tsg.make_db(str(db), [("box-alias1", "G4", U, G4), ("box-main", "G4", int(2.5 * U), G4), + ("x86-a", "modern", int(0.8 * U), X86)]) + _add_evidence(db, ips={"box-alias1": "198.51.100.9", "box-main": "198.51.100.9", + "x86-a": "198.51.100.9"}, + macs={"box-alias1": ["macA"], "box-main": ["macA", "macB"], "x86-a": ["macX"]}) + res, bal = _settle(db) + assert sorted(bal) == ["box-main", "x86-a"] + tel = res["anti_double_mining_telemetry"] + assert tel["duplicate_miner_ids_skipped"] == 1 + assert tel["skipped_details"] == [{"skipped": "box-alias1", "rewarded_representative": "box-main"}] + + +def test_bridge_miner_is_held_and_does_not_merge_honest_miners(tmp_path): + """Round 2 (review): A reports X, att reports X+Y, B reports Y, all same ip/arch. + Union-find used to chain A-att-B into ONE machine (one slot). Now att is a + bridge conflict: held at 0 and escrowed; A and B are paid separately.""" + db = tmp_path / "bridge.db" + tsg.make_db(str(db), [("A", "G5", 2 * U, G4), ("att", "G5", 3 * U, G4), ("B", "G5", 2 * U, G4)]) + _add_evidence(db, ips={m: "198.51.100.1" for m in ("A", "att", "B")}, + macs={"A": ["X"], "att": ["X", "Y"], "B": ["Y"]}) + res, bal = _settle(db) + assert sorted(bal) == ["A", "B"] + assert bal["A"] + bal["B"] == POT and abs(bal["A"] - bal["B"]) <= 1 + assert res["anti_double_mining_telemetry"]["duplicate_miner_ids_skipped"] == 0 + assert tsg.escrow(str(db)) == [("att", 3 * U, "adm_identity_bridge_conflict")] + + +def test_bridge_resolver_reports_conflict_and_keeps_true_clique(tmp_path): + """A clique that shares a MAC still collapses; only the bridging miner conflicts.""" + db = tmp_path / "clique.db" + tsg.make_db(str(db), [(m, "G5", U, G4) for m in ("c1", "c2", "att", "B")]) + _add_evidence(db, ips={m: "198.51.100.1" for m in ("c1", "c2", "att", "B")}, + macs={"c1": ["X"], "c2": ["X"], "att": ["X", "Y"], "B": ["Y"]}) + with sqlite3.connect(db) as c: + ids, conflicts = adm.resolve_machine_identities_ex( + c, {m: "G5" for m in ("c1", "c2", "att", "B")}, EPOCH_START) + assert set(conflicts) == {"att"} and conflicts["att"] == ["B", "c1", "c2"] + assert ids["c1"] == ids["c2"] + assert len({ids["c1"], ids["att"], ids["B"]}) == 3 + + +def test_all_share_one_mac_is_a_clique_not_a_conflict(tmp_path): + db = tmp_path / "trio.db" + tsg.make_db(str(db), [("m1", "G5", 2 * U, G4), ("m2", "G5", 2 * U, G4), ("m3", "G5", 2 * U, G4)]) + _add_evidence(db, ips={m: "198.51.100.1" for m in ("m1", "m2", "m3")}, + macs={"m1": ["p"], "m2": ["p", "q"], "m3": ["p", "q"]}) + res, bal = _settle(db) + assert len(bal) == 1 + assert res["anti_double_mining_telemetry"]["duplicate_miner_ids_skipped"] == 2 + assert tsg.escrow(str(db)) == [] + + +def _set_mac_window(path, miner, first_ts, last_ts): + with sqlite3.connect(path) as c: + c.execute("UPDATE miner_macs SET first_ts=?, last_ts=? WHERE miner=?", (first_ts, last_ts, miner)) + + +EPOCH_LAST_SLOT = EPOCH_START + 143 * adm.BLOCK_TIME +NEXT_EPOCH_START = EPOCH_START + 144 * adm.BLOCK_TIME # exclusive upper bound (round-2 review) + + +@pytest.mark.parametrize("case,merged", [ + ("first_seen_after_epoch_end", False), # a later observation cannot regroup a past epoch + ("first_seen_at_next_epoch_start", False), # boundary: == next start is EXCLUDED + ("first_seen_in_final_slot", True), # boundary: inside the last 600 s slot is INCLUDED + ("first_seen_one_second_before_next", True), + ("seen_before_and_still_active", True), # normal late settlement of an active duplicate + ("inside_epoch", True), + ("stale_before_window", False), +]) +def test_mac_evidence_is_epoch_scoped(tmp_path, case, merged): + db = tmp_path / f"{case}.db" + tsg.make_db(str(db), [("main", "G4", 2 * U, G4), ("alias", "G4", U, G4)]) + _add_evidence(db, ips={"main": "198.51.100.2", "alias": "198.51.100.2"}, + macs={"main": ["M"], "alias": ["M"]}) + window = { + "first_seen_after_epoch_end": (NEXT_EPOCH_START + 60, NEXT_EPOCH_START + 3600), + "first_seen_at_next_epoch_start": (NEXT_EPOCH_START, NEXT_EPOCH_START + 3600), + "first_seen_in_final_slot": (EPOCH_LAST_SLOT + 60, EPOCH_LAST_SLOT + 120), + "first_seen_one_second_before_next": (NEXT_EPOCH_START - 1, NEXT_EPOCH_START + 600), + "seen_before_and_still_active": (EPOCH_START - 86400, NEXT_EPOCH_START + 5 * 86400), + "inside_epoch": (EPOCH_START + 60, EPOCH_START + 600), + "stale_before_window": (EPOCH_START - 30 * 86400, EPOCH_START - adm.ADM_MAC_RECENCY_S - 1), + }[case] + _set_mac_window(db, "alias", *window) + with sqlite3.connect(db) as c: + ids = adm.resolve_machine_identities(c, {"main": "G4", "alias": "G4"}, EPOCH_START, + NEXT_EPOCH_START) + # Same answer through the settlement entry point, which derives the bound itself. + groups, _ = adm.get_epoch_miner_groups_ex(c, EPOCH) + dup = adm.detect_duplicate_identities(c, EPOCH, EPOCH_START, EPOCH_LAST_SLOT) + assert (ids["main"] == ids["alias"]) is merged + assert (len(groups) == 1) is merged + assert (len(dup) == 1) is merged + + +def test_default_evidence_bound_is_next_epoch_start(tmp_path): + db = tmp_path / "default.db" + tsg.make_db(str(db), [("main", "G4", 2 * U, G4), ("alias", "G4", U, G4)]) + _add_evidence(db, ips={"main": "198.51.100.2", "alias": "198.51.100.2"}, + macs={"main": ["M"], "alias": ["M"]}) + _set_mac_window(db, "alias", EPOCH_LAST_SLOT + 300, EPOCH_LAST_SLOT + 300) + with sqlite3.connect(db) as c: + ids = adm.resolve_machine_identities(c, {"main": "G4", "alias": "G4"}, EPOCH_START) + assert ids["main"] == ids["alias"] + + +def _poison_first_seen(path, column_sql): + with sqlite3.connect(path) as c: + c.execute(column_sql) + + +@pytest.mark.parametrize("where", ["ts_ok", "bound_at", "both"]) +def test_infinite_first_seen_never_raises_and_bridge_hold_still_applies(tmp_path, where, caplog): + """Round-2 review: a REAL inf in ts_ok / bound_at made int() raise + OverflowError inside _first_seen_map and aborted settlement. It must be + treated as missing evidence: settlement completes via ADM, the bridge + conflict is still held + escrowed, and a true duplicate still collapses.""" + db = tmp_path / f"inf_{where}.db" + tsg.make_db(str(db), [("A", "G5", 2 * U, G4), ("att", "G5", 3 * U, G4), ("B", "G5", 2 * U, G4), + ("d1", "G4", U, G4), ("d2", "G4", 2 * U, G4)]) + _add_evidence(db, ips={m: "198.51.100.1" for m in ("A", "att", "B", "d1", "d2")}, + macs={"A": ["X"], "att": ["X", "Y"], "B": ["Y"], "d1": ["D"], "d2": ["D"]}) + with sqlite3.connect(db) as c: + c.execute("CREATE TABLE hardware_bindings (hardware_id TEXT PRIMARY KEY, bound_miner TEXT, " + "bound_at INTEGER)") + if where in ("ts_ok", "both"): + c.execute("INSERT INTO miner_attest_history (miner, ts_ok, fingerprint_passed) VALUES " + "('d1', 9e999, 1), ('d2', -1e999, 1), ('d2', -5, 1), ('A', 'garbage', 1)") + if where in ("bound_at", "both"): + c.execute("INSERT INTO hardware_bindings VALUES ('h1', 'd1', 9e999), ('h2', 'd2', 9e999)") + # Confirm SQLite really stored IEEE inf, not NULL / text. + vals = [r[0] for r in c.execute( + "SELECT ts_ok FROM miner_attest_history WHERE typeof(ts_ok)='real' " + "UNION ALL SELECT bound_at FROM hardware_bindings WHERE typeof(bound_at)='real'")] + assert vals and all(v in (float("inf"), float("-inf")) for v in vals) + assert adm._first_seen_map(c, ["d1", "d2", "A"]) == {} + caplog.set_level("ERROR", logger="anti_double_mining") + res, bal = _settle(db) + assert "anti_double_mining_telemetry" in res # the ADM path ran, not a fallback + assert "att" not in bal and {"A", "B"} <= set(bal) + assert res["anti_double_mining_telemetry"]["duplicate_miner_ids_skipped"] == 1 + assert ("att", 3 * U, "adm_identity_bridge_conflict") in tsg.escrow(str(db)) + # Logged (once per first-seen lookup, not once per bad row), never raised. + assert any("invalid first-seen timestamp" in r.getMessage() for r in caplog.records) + + +def test_nat_copycat_cannot_displace_established_miner(tmp_path, caplog): + """Attacker behind the victim's NAT copies its MAC and enrolls heavier. The + established (earlier first-seen) identity keeps the slot; the copycat is skipped.""" + db = tmp_path / "copycat.db" + tsg.make_db(str(db), [("victim", "G4", U, G4), ("copycat", "G4", int(2.5 * U), G4), + ("x86-a", "modern", int(0.8 * U), X86)]) + _add_evidence(db, ips={"victim": "198.51.100.8", "copycat": "198.51.100.8"}, + macs={"victim": ["macV"], "copycat": ["macV"]}) + with sqlite3.connect(db) as c: + c.execute("INSERT INTO miner_attest_history (miner, ts_ok, fingerprint_passed) VALUES " + "('victim', ?, 1), ('copycat', ?, 1)", (EPOCH_START - 90 * 86400, EPOCH_START + 100)) + caplog.set_level("WARNING", logger="anti_double_mining") + res, bal = _settle(db) + assert sorted(bal) == ["victim", "x86-a"] + assert res["anti_double_mining_telemetry"]["skipped_details"] == [ + {"skipped": "copycat", "rewarded_representative": "victim"}] + assert any("kept established victim" in r.getMessage() for r in caplog.records) + + +def test_hardware_binding_counts_as_first_seen(tmp_path): + db = tmp_path / "hb.db" + tsg.make_db(str(db), [("bound", "G4", U, G4), ("newer", "G4", 2 * U, G4)]) + _add_evidence(db, ips={"bound": "198.51.100.9", "newer": "198.51.100.9"}, + macs={"bound": ["m"], "newer": ["m"]}) + with sqlite3.connect(db) as c: + c.execute("CREATE TABLE hardware_bindings (hardware_id TEXT PRIMARY KEY, bound_miner TEXT, " + "bound_at INTEGER)") + c.execute("INSERT INTO hardware_bindings VALUES ('h1', 'bound', 1000)") + c.execute("INSERT INTO miner_attest_history (miner, ts_ok, fingerprint_passed) VALUES " + "('newer', 5000, 1)") + _, bal = _settle(db) + assert sorted(bal) == ["bound"] + + +@pytest.mark.parametrize("bad", ["nan", "inf", "-inf", -5, "abc", b"\x00", None]) +def test_malformed_enrolled_weights_are_zero_and_never_raise(tmp_path, bad, caplog): + db = tmp_path / "w.db" + tsg.make_db(str(db), [("good", "G4", int(2.5 * U), G4), ("bad", "G4", U, G4)]) + val = {"nan": float("nan"), "inf": float("inf"), "-inf": float("-inf")}.get(bad, bad) + with sqlite3.connect(db) as c: + c.execute("UPDATE epoch_enroll SET weight=? WHERE miner_pk='bad'", (val,)) + caplog.set_level("ERROR", logger="anti_double_mining") + res, bal = _settle(db) + assert bal == {"good": POT} + assert res["anti_double_mining_telemetry"]["total_machines"] == 2 + with sqlite3.connect(db) as c: + stored = c.execute("SELECT weight FROM epoch_enroll WHERE miner_pk='bad'").fetchone()[0] + if stored is not None: # SQLite stores NaN as NULL, which is simply "no weight" + assert any("treated as 0" in r.getMessage() for r in caplog.records) + + +def test_safe_weight_unit(): + for v in (float("nan"), float("inf"), -1, "x", [], 10 ** 400): + assert adm._safe_weight(v) == 0.0 + assert adm._safe_weight("2.5") == 2.5 and adm._safe_weight(3) == 3.0 + + +def test_ip_schema_without_miner_column_falls_back_per_miner(): + c = sqlite3.connect(":memory:") + c.execute("CREATE TABLE miner_attest_recent (wallet TEXT, source_ip TEXT)") + c.execute("CREATE TABLE miner_macs (miner TEXT, mac_hash TEXT, first_ts INT, last_ts INT)") + c.execute("INSERT INTO miner_macs VALUES ('a','m',?,?), ('b','m',?,?)", (EPOCH_START,) * 4) + ids = adm.resolve_machine_identities(c, {"a": "G4", "b": "G4"}, EPOCH_START) + assert ids["a"] != ids["b"] + + +def test_non_text_ip_values_do_not_raise_or_merge(): + c = sqlite3.connect(":memory:") + c.execute("CREATE TABLE miner_attest_recent (miner TEXT PRIMARY KEY, ts_ok INT, source_ip)") + c.execute("CREATE TABLE miner_macs (miner TEXT, mac_hash TEXT, first_ts INT, last_ts INT)") + c.executemany("INSERT INTO miner_attest_recent VALUES (?,?,?)", + [("a", 1, 12345), ("b", 1, 12345), ("c", 1, b"10.0.0.1"), ("d", 1, b"10.0.0.1"), + ("e", 1, b"\xff\xfe"), ("f", 1, b"\xff\xfe")]) + for m in "abcdef": + c.execute("INSERT INTO miner_macs VALUES (?, 'm', ?, ?)", (m, EPOCH_START, EPOCH_START)) + ids = adm.resolve_machine_identities(c, {m: "G4" for m in "abcdef"}, EPOCH_START) + assert ids["a"] != ids["b"] # integer IP ignored -> no evidence + assert ids["c"] == ids["d"] # utf-8 bytes IP decoded -> real evidence + assert ids["e"] != ids["f"] # undecodable bytes ignored + + +def test_present_but_broken_table_fails_loudly(): + """A genuine sqlite error on a PRESENT table must propagate (settlement + rolls back, epoch stays unsettled) -- not silently fall back to per-miner.""" + c = sqlite3.connect(":memory:") + c.execute("CREATE TABLE miner_attest_recent (miner TEXT PRIMARY KEY, ts_ok INT, source_ip TEXT)") + c.execute("INSERT INTO miner_attest_recent VALUES ('a', 1, '10.0.0.1')") + c.execute("CREATE TABLE gone (miner TEXT, mac_hash TEXT, first_ts INT, last_ts INT)") + c.execute("CREATE VIEW miner_macs AS SELECT miner, mac_hash, first_ts, last_ts FROM gone") + c.execute("DROP TABLE gone") + with pytest.raises(sqlite3.OperationalError): + adm.resolve_machine_identities(c, {"a": "G4"}, EPOCH_START) + + +def test_identity_queries_are_batched(): + c = sqlite3.connect(":memory:") + c.execute("CREATE TABLE miner_attest_recent (miner TEXT PRIMARY KEY, ts_ok INT, source_ip TEXT)") + c.execute("CREATE TABLE miner_macs (miner TEXT, mac_hash TEXT, first_ts INT, last_ts INT)") + miners = [f"m{i}" for i in range(1200)] + c.executemany("INSERT INTO miner_attest_recent VALUES (?, 1, '10.0.0.1')", [(m,) for m in miners]) + c.executemany("INSERT INTO miner_macs VALUES (?, ?, ?, ?)", + [(m, f"mac{i}", EPOCH_START, EPOCH_START) for i, m in enumerate(miners)]) + stmts = [] + c.set_trace_callback(stmts.append) + ids = adm.resolve_machine_identities(c, {m: "G4" for m in miners}, EPOCH_START) + data = [q for q in stmts if q.lstrip().upper().startswith("SELECT")] + assert len(set(ids.values())) == 1200 + assert len(data) == 6 # ceil(1200/500)=3 chunks x 2 tables, not 2N + + +@pytest.mark.parametrize("variant", ["different_ip", "different_arch", "stale_mac", "no_ip"]) +def test_mac_alone_is_not_enough(tmp_path, variant): + """A claimed MAC must be corroborated by the server-observed IP (anti-griefing).""" + db = tmp_path / f"{variant}.db" + arch_b = "G5" if variant == "different_arch" else "G4" + tsg.make_db(str(db), [("victim", "G4", int(2.5 * U), G4), ("claimer", arch_b, 3 * U, G4)]) + ips = {"victim": "198.51.100.5", "claimer": "198.51.100.5"} + if variant == "different_ip": + ips["claimer"] = "203.0.113.99" + if variant == "no_ip": + ips = {"victim": "198.51.100.5"} + mac_ts = EPOCH_START - adm.ADM_MAC_RECENCY_S - 10 if variant == "stale_mac" else None + _add_evidence(db, ips=ips, macs={"victim": ["macV"], "claimer": ["macV"]}, mac_ts=mac_ts) + _, bal = _settle(db) + assert sorted(bal) == ["claimer", "victim"] + + +def test_held_alias_never_displaces_unheld_same_machine(tmp_path): + db = tmp_path / "held.db" + tsg.make_db(str(db), [("real", "G4", U, G4), ("alias", "G4", int(2.5 * U), G4)], held=("alias",)) + _add_evidence(db, ips={"real": "198.51.100.3", "alias": "198.51.100.3"}, + macs={"real": ["m"], "alias": ["m"]}) + _, bal = _settle(db) + assert sorted(bal) == ["real"] + + +def test_held_miner_without_evidence_still_zero(tmp_path): + db = tmp_path / "held2.db" + tsg.make_db(str(db), [("g4-a", "G4", int(2.5 * U), G4), ("sybil", "G4", U, tsg._sybil_profile(1))], + held=("sybil",)) + _, bal = _settle(db) + assert sorted(bal) == ["g4-a"] + + +def test_resolve_identities_fallback_schema(tmp_path): + """No source_ip column / no miner_macs table -> every miner its own identity.""" + c = sqlite3.connect(":memory:") + c.execute("CREATE TABLE miner_attest_recent (miner TEXT PRIMARY KEY, device_arch TEXT)") + ids = adm.resolve_machine_identities(c, {"a": "G4", "b": "G4", "c": "G4"}, EPOCH_START) + assert len(set(ids.values())) == 3 + + +def test_detect_duplicate_identities_uses_machine_evidence(tmp_path): + db = tmp_path / "det.db" + tsg.make_db(str(db), [("a", "G4", U, G4), ("b", "G4", U, G4), ("c", "G4", U, G4)]) + _add_evidence(db, ips={"a": "10.0.0.1", "b": "10.0.0.1", "c": "10.0.0.1"}, + macs={"a": ["x"], "b": ["x"], "c": ["y"]}) + with sqlite3.connect(db) as c: + dups = adm.detect_duplicate_identities(c, EPOCH, EPOCH_START, EPOCH_START + 86400) + assert [sorted(d.associated_miner_ids) for d in dups] == [["a", "b"]] diff --git a/node/tests/sybil_guard/test_sybil_guard_incident_box.py b/node/tests/sybil_guard/test_sybil_guard_incident_box.py new file mode 100644 index 000000000..6d0266587 --- /dev/null +++ b/node/tests/sybil_guard/test_sybil_guard_incident_box.py @@ -0,0 +1,58 @@ +# SPDX-License-Identifier: MIT +"""Incident signature must catch BOTH waves and still clear every honest miner. + +Wave 2 (24 wallets, same source addresses) had 4 wallets just outside the +original wave-1-fitted box (clock_drift_cv 0.0080-0.0083, thermal 0.8123). The +box was widened to the generator's likely bounds; these tests pin that. +""" +import json + +import sybil_guard as sg +from sg_helpers import load_json + + +def _profiles(rows): + return [(r["miner"], json.loads(r["profile_json"])) for r in rows] + + +def _hit_wallets(rows): + return {m for m, p in _profiles(rows) if sg.matches_incident_signature(p)} + + +def test_box_is_the_widened_generator_bounds(): + assert sg.INCIDENT_20260924_BOX == { + "clock_drift_cv": (0.008, 0.030), + "thermal_variance": (0.8, 6.0), + "jitter_cv": (0.015, 0.25), + "cache_hierarchy_ratio": (1.8, 2.9), + } + + +def test_wave2_all_24_wallets_hit(): + rows = load_json("wave2_profiles.json") + wallets = {r["miner"] for r in rows} + assert len(wallets) == 24 + assert _hit_wallets(rows) == wallets + + +def test_wave1_plus_wave2_is_144_of_144(sybil_rows): + w2 = load_json("wave2_profiles.json") + all_wallets = {r["miner"] for r in sybil_rows} | {r["miner"] for r in w2} + assert len(all_wallets) == 144 + assert _hit_wallets(sybil_rows) | _hit_wallets(w2) == all_wallets + + +def test_widened_box_flags_zero_honest_miners(honest_rows): + assert _hit_wallets(honest_rows) == set() + assert len({r["miner"] for r in honest_rows}) == 86 + + +def test_wave2_edge_profiles_that_the_old_box_missed_are_caught(): + old = {"clock_drift_cv": (0.0085, 0.0299), "thermal_variance": (0.8515, 5.9022), + "jitter_cv": (0.0153, 0.2473), "cache_hierarchy_ratio": (1.8034, 2.8961)} + missed_by_old = [ + p for _, p in _profiles(load_json("wave2_profiles.json")) + if not all(lo <= p[m] <= hi for m, (lo, hi) in old.items()) + ] + assert len(missed_by_old) == 4 + assert all(sg.matches_incident_signature(p) for p in missed_by_old) diff --git a/node/tests/sybil_guard/test_sybil_guard_node_integration.py b/node/tests/sybil_guard/test_sybil_guard_node_integration.py new file mode 100644 index 000000000..f8f9ce9cc --- /dev/null +++ b/node/tests/sybil_guard/test_sybil_guard_node_integration.py @@ -0,0 +1,606 @@ +# SPDX-License-Identifier: MIT +"""End-to-end: the patched production node vs the unpatched live snapshot. + +Each test gets a fresh SQLite file. The node module is loaded once per source +(patched / live) and re-pointed at the test DB. External-risk subsystems +(P2P, replay module, hardware binding, fleet immune, warthog) are stubbed, the +same way the upstream welcome-bonus tests do. +""" +import json +import sqlite3 +import time + +import pytest + +from sg_helpers import NODE_DIR, baseline_dir, load_node + +EPOCH = 296 +SOURCE = "founder_community" +BONUS_I64 = 500_000 + + +@pytest.fixture(scope="module") +def nodes(tmp_path_factory): + d = tmp_path_factory.mktemp("load") + out = {"patched": load_node(d / "p.db", "patched", NODE_DIR)} + # "live" = main before this change (from git); comparisons are skipped + # when it cannot be materialised (shallow checkout). + if baseline_dir() is not None: + out["live"] = load_node(d / "l.db", "live", baseline_dir()) + return out + + +def _configure(node, db_path): + node.DB_PATH = str(db_path) + node.UTXO_DUAL_WRITE = False + node.HW_BINDING_V2 = False + node.HW_PROOF_AVAILABLE = False + node.HAVE_REPLAY_DEFENSE = False + node.HAVE_FLEET_IMMUNE = False + node.HAVE_WARTHOG = False + node.check_ip_rate_limit = lambda client_ip, miner_id: (True, "ok") + node._check_hardware_binding = lambda *a, **k: (True, "ok", "") + node._check_oui_gate = lambda macs: (True, {"ok": True}) + node.wallet_review_gate_response = lambda miner: None + node.record_macs = lambda *a, **k: None + node.auto_induct_to_hall = lambda *a, **k: None + node.current_slot = lambda: EPOCH * 144 + 5 + node.slot_to_epoch = lambda slot: EPOCH + + +def _prepare_db(node, db_path, nonces): + now = int(time.time()) + with sqlite3.connect(db_path) as conn: + node.attest_ensure_tables(conn) + for n in nonces: + conn.execute("INSERT INTO nonces (nonce, expires_at) VALUES (?, ?)", (n, now + 3600)) + conn.executescript( + """ + CREATE TABLE IF NOT EXISTS tickets (ticket_id TEXT PRIMARY KEY, expires_at INTEGER, commitment TEXT); + CREATE TABLE IF NOT EXISTS epoch_state (epoch INTEGER PRIMARY KEY, settled INTEGER DEFAULT 0, settled_ts INTEGER); + CREATE TABLE IF NOT EXISTS epoch_enroll (epoch INTEGER NOT NULL, miner_pk TEXT NOT NULL, + weight INTEGER NOT NULL, PRIMARY KEY(epoch, miner_pk)); + CREATE TABLE IF NOT EXISTS balances (miner_id TEXT PRIMARY KEY, miner_pk TEXT, + amount_i64 INTEGER DEFAULT 0, balance_rtc REAL DEFAULT 0); + CREATE TABLE IF NOT EXISTS ledger (id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, + epoch INTEGER, miner_id TEXT NOT NULL, delta_i64 INTEGER NOT NULL, reason TEXT); + CREATE TABLE IF NOT EXISTS miner_attest_recent (miner TEXT PRIMARY KEY, ts_ok INTEGER, + device_family TEXT, device_arch TEXT, entropy_score REAL DEFAULT 0.0, + fingerprint_passed INTEGER DEFAULT 0, source_ip TEXT, signing_pubkey TEXT, + fingerprint_checks_json TEXT); + CREATE TABLE IF NOT EXISTS miner_attest_history (id INTEGER PRIMARY KEY AUTOINCREMENT, + miner TEXT NOT NULL, ts_ok INTEGER NOT NULL, device_family TEXT, device_arch TEXT, + entropy_score REAL DEFAULT 0.0, fingerprint_passed INTEGER DEFAULT 0, + fingerprint_checks_json TEXT); + """ + ) + conn.execute("INSERT OR IGNORE INTO epoch_state(epoch, settled) VALUES (?, 0)", (EPOCH,)) + conn.commit() + if hasattr(node, "sybil_guard"): # patched node: startup-only schema + node.sybil_guard.init_schema(conn) + conn.execute("INSERT INTO balances(miner_id, miner_pk, amount_i64, balance_rtc) VALUES (?, ?, ?, ?)", + (SOURCE, SOURCE, 100 * BONUS_I64, 50.0)) + conn.commit() + + +def _g4_payload(miner, nonce, profile, arch="g4", cpu="PowerPC G4 7447A"): + """Shape of the incident payload: self-reported G4 evidence.""" + return { + "miner": miner, "miner_id": miner, "nonce": nonce, + "device": {"family": "PowerPC", "arch": arch, "cpu": cpu, "model": "PowerMac3,6", "cores": 1}, + "signals": {"hostname": "powermac"}, + "report": {"nonce": nonce, "commitment": "c"}, + "fingerprint": { + "all_passed": True, + "checks": { + "anti_emulation": {"passed": True, "data": {"vm_indicators": [], "is_likely_vm": False}}, + "clock_drift": {"passed": True, "data": {"cv": profile["clock_drift_cv"], "samples": 500}}, + "simd_identity": {"passed": True, "data": {"has_altivec": True, "has_sse": False, + "has_avx": False, "x86_features": []}}, + "cache_timing": {"passed": True, "data": {"l2_l1_ratio": profile["cache_hierarchy_ratio"]}}, + "thermal_drift": {"passed": True, "data": {"drift_ratio": profile["thermal_variance"]}}, + "instruction_jitter": {"passed": True, "data": {"cv": profile["jitter_cv"]}}, + }, + }, + } + + +def _enrolled_weight(node, db, miner): + with sqlite3.connect(db) as c: + row = c.execute("SELECT weight FROM epoch_enroll WHERE epoch=? AND miner_pk=?", (EPOCH, miner)).fetchone() + return None if row is None else node.epoch_weight_units_to_display(row[0]) + + +def _bonus_rows(db, miner): + with sqlite3.connect(db) as c: + return c.execute("SELECT COUNT(*) FROM ledger WHERE miner_id=? AND delta_i64>0 AND " + "reason LIKE 'welcome_bonus:%'", (miner,)).fetchone()[0] + + +def _attest(node, db, payload, ip="203.0.113.10"): + with node.app.test_client() as client: + resp = client.post("/attest/submit", json=payload, environ_base={"REMOTE_ADDR": ip}) + assert resp.status_code == 200, resp.get_json() + return resp.get_json() + + +# --------------------------------------------------------------------------- + +def test_incident_reproduces_on_live_and_is_stopped_by_patch(nodes, tmp_path, sybil_rows): + row = sybil_rows[0] + profile = json.loads(row["profile_json"]) + results = {} + for name, node in nodes.items(): + db = tmp_path / f"{name}.db" + _configure(node, db) + _prepare_db(node, db, ["n1"]) + body = _attest(node, db, _g4_payload(row["miner"], "n1", profile)) + results[name] = (_enrolled_weight(node, db, row["miner"]), _bonus_rows(db, row["miner"]), body) + pat_w, pat_bonus, body = results["patched"] + if "live" in results: + live_w, live_bonus, _ = results["live"] + assert live_w == pytest.approx(1.75) and live_bonus == 1 # the incident, reproduced on pre-patch main + assert pat_w == 0 and pat_bonus == 0 # needs_review hold, no bonus + assert body["probation"]["state"] == "probation" + with sqlite3.connect(tmp_path / "patched.db") as c: + esc = c.execute("SELECT epoch, would_be_weight_units FROM sybil_review_escrow WHERE miner=?", + (row["miner"],)).fetchall() + assert esc == [(EPOCH, nodes["patched"].epoch_weight_to_units(1.0))] + + +def test_every_flagged_wallet_first_attestation_patched(nodes, tmp_path, sybil_rows): + node = nodes["patched"] + db = tmp_path / "all.db" + _configure(node, db) + first = {} + for r in sorted(sybil_rows, key=lambda r: r["ts"]): + first.setdefault(r["miner"], r) + _prepare_db(node, db, [f"n{i}" for i in range(len(first))]) + for i, (miner, r) in enumerate(first.items()): + _attest(node, db, _g4_payload(miner, f"n{i}", json.loads(r["profile_json"])), ip=r["source_ip"]) + with sqlite3.connect(db) as c: + weights = [w for (w,) in c.execute("SELECT weight FROM epoch_enroll WHERE epoch=?", (EPOCH,))] + bonus = c.execute("SELECT COUNT(*) FROM ledger WHERE reason LIKE 'welcome_bonus:%'").fetchone()[0] + states = dict(c.execute("SELECT state, COUNT(*) FROM miner_probation GROUP BY state").fetchall()) + assert len(weights) == 120 and set(weights) == {0} + assert bonus == 0 + assert states.get("trusted", 0) == 0 and states.get("grandfathered", 0) == 0 + print(f"\n120 flagged wallets: states={states}, all enrolled at weight 0, bonuses=0") + + +def _seed_established(db, miner, n=40): + start = 1790208000 - 30 * 86400 + with sqlite3.connect(db) as c: + for k in range(n): + c.execute("INSERT INTO miner_attest_history (miner, ts_ok, fingerprint_passed) VALUES (?, ?, 1)", + (miner, start + k * 6 * 3600)) + c.commit() + + +@pytest.mark.parametrize("arch,cpu,profile", [ + ("g4", "PowerPC G4 7447A", {"clock_drift_cv": 0.0123, "thermal_variance": 0.0, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.0}), # lab G4 legacy client + ("g5", "PowerPC G5 970", {"clock_drift_cv": 0.0110244, "thermal_variance": 0.44862, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.34914}), # honest G5 fixture row +]) +def test_grandfathered_miner_identical_on_live_and_patched(nodes, tmp_path, arch, cpu, profile): + out = {} + for name, node in nodes.items(): + db = tmp_path / f"gf_{name}.db" + _configure(node, db) + _prepare_db(node, db, ["g1", "g2"]) + _seed_established(db, "lab-g4-example") + _attest(node, db, _g4_payload("lab-g4-example", "g1", profile, arch=arch, cpu=cpu), ip="192.0.2.125") + out[name] = (_enrolled_weight(node, db, "lab-g4-example"), _bonus_rows(db, "lab-g4-example")) + if "live" in out: + assert out["patched"] == out["live"], out + assert out["patched"][0] > 1.0 # still earns its vintage premium + + +def test_dead_anomaly_call_now_runs(nodes, tmp_path, monkeypatch): + node = nodes["patched"] + db = tmp_path / "dead.db" + _configure(node, db) + _prepare_db(node, db, ["d1"]) + seen = {} + monkeypatch.setattr(node, "HAVE_REPLAY_DEFENSE", True) + monkeypatch.setattr(node, "compute_fingerprint_hash", lambda fp: "h", raising=False) + monkeypatch.setattr(node, "compute_entropy_profile_hash", lambda fp: "e", raising=False) + monkeypatch.setattr(node, "check_fingerprint_replay", lambda **k: (False, "", None), raising=False) + monkeypatch.setattr(node, "check_entropy_collision", lambda **k: (False, "", None), raising=False) + monkeypatch.setattr(node, "check_fingerprint_rate_limit", lambda **k: (True, "", None), raising=False) + + def anomalies(**k): + seen["anomaly_called"] = True + return False, [] + + def record(**k): + seen["attestation_valid"] = k.get("attestation_valid") + + monkeypatch.setattr(node, "detect_fingerprint_anomalies", anomalies, raising=False) + monkeypatch.setattr(node, "record_fingerprint_submission", record, raising=False) + prof = {"clock_drift_cv": 0.0110244, "thermal_variance": 0.44862, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.34914} + _attest(node, db, _g4_payload("RTCdeadcode", "d1", prof, arch="g5", cpu="PowerPC G5 970")) + assert seen == {"anomaly_called": True, "attestation_valid": True} + + +def test_temporal_gate_signature_is_backward_compatible(nodes): + node = nodes["patched"] + review = {"reason": "insufficient_history"} + assert node.apply_temporal_consistency_to_weight(2.5, review) == pytest.approx(1.75) + assert node.apply_temporal_consistency_to_weight(2.5, review, {"state": "probation"}) == 1.0 + assert node.apply_temporal_consistency_to_weight(2.5, review, {"state": "grandfathered"}) == pytest.approx(1.75) + assert node.apply_temporal_consistency_to_weight(2.5, review, None) == 1.0 # fail closed + assert node.apply_temporal_consistency_to_weight(0.8, review, {"state": "probation"}) == 0.8 + + +def test_welcome_bonus_paid_once_at_graduation_only(nodes, tmp_path): + node = nodes["patched"] + db = tmp_path / "bonus.db" + _configure(node, db) + _prepare_db(node, db, []) + assert node._check_welcome_bonus("m", {"state": "probation"}) is False + assert node._check_welcome_bonus("m", None) is False + assert node._check_welcome_bonus("m", {"state": "trusted", "needs_review": 1}) is False + assert _bonus_rows(db, "m") == 0 + assert node._check_welcome_bonus("m", {"state": "trusted"}) is False # nothing persisted: withheld + with sqlite3.connect(db) as c: + c.execute("INSERT INTO miner_probation (miner, state, first_seen, last_seen, updated_at) " + "VALUES ('m', 'trusted', 1, 1, 1)") + assert node._check_welcome_bonus("m", {"state": "trusted"}) is True + assert node._check_welcome_bonus("m", {"state": "trusted"}) is False + assert _bonus_rows(db, "m") == 1 + with sqlite3.connect(db) as c: + assert c.execute("SELECT amount_i64 FROM balances WHERE miner_id=?", (SOURCE,)).fetchone()[0] == 99 * BONUS_I64 + + +def test_welcome_bonus_grandfathered_keeps_legacy_rule(nodes, tmp_path): + node = nodes["patched"] + db = tmp_path / "bonus_gf.db" + _configure(node, db) + _prepare_db(node, db, []) + _seed_established(db, "old", n=10) + assert node._check_welcome_bonus("old", {"state": "grandfathered"}) is False + assert _bonus_rows(db, "old") == 0 + + +def test_finalize_epoch_holds_needs_review_miner(nodes, tmp_path): + node = nodes["patched"] + db = tmp_path / "fin.db" + _configure(node, db) + _prepare_db(node, db, []) + import sybil_guard as sg + u = node.epoch_weight_to_units(1.0) + with sqlite3.connect(db, isolation_level=None) as c: + sg.ensure_probation_tables(c) + c.execute("INSERT INTO epoch_enroll VALUES (?, 'good', ?)", (EPOCH, u)) + c.execute("INSERT INTO epoch_enroll VALUES (?, 'held', ?)", (EPOCH, u)) + c.execute("INSERT INTO miner_probation (miner, state, first_seen, last_seen, needs_review, updated_at) " + "VALUES ('held', 'probation', 1, 1, 1, 1)") + c.execute("INSERT INTO balances(miner_id, miner_pk, amount_i64) VALUES ('good','good',0),('held','held',0)") + node.finalize_epoch(EPOCH, 1.5 / 144) + with sqlite3.connect(db) as c: + bal = dict(c.execute("SELECT miner_id, amount_i64 FROM balances WHERE miner_id IN ('good','held')")) + esc = c.execute("SELECT miner, would_be_weight_units, reason FROM sybil_review_escrow").fetchall() + print(f"\nfinalize_epoch balances={bal} escrow={esc}") + assert bal["held"] == 0 and bal["good"] > 0 + assert esc == [("held", u, "settlement_hold")] + + +def test_rip200_settlement_guard(tmp_path): + import sybil_guard as sg + import rip_200_round_robin_1cpu1vote as rr + db = tmp_path / "rr.db" + u = rr._weight_to_units(1.0) + with sqlite3.connect(db, isolation_level=None) as c: + sg.ensure_probation_tables(c) + c.execute("CREATE TABLE epoch_enroll (epoch INTEGER, miner_pk TEXT, weight INTEGER)") + c.execute("CREATE TABLE miner_attest_recent (miner TEXT PRIMARY KEY, device_arch TEXT, " + "fingerprint_passed INTEGER)") + for m in ("good", "held"): + c.execute("INSERT INTO epoch_enroll VALUES (?, ?, ?)", (EPOCH, m, u)) + c.execute("INSERT INTO miner_attest_recent VALUES (?, 'modern', 1)", (m,)) + c.execute("INSERT INTO miner_probation (miner, state, first_seen, last_seen, needs_review, updated_at) " + "VALUES ('held', 'probation', 1, 1, 1, 1)") + rewards = rr.calculate_epoch_rewards_time_aged(str(db), EPOCH, 150_000_000, EPOCH * 144) + print(f"\nrip200 rewards={rewards}") + assert rewards.get("held", 0) == 0 and rewards["good"] > 0 + + +# --------------------------------------------------------------------------- +# Round 2 +# --------------------------------------------------------------------------- + +def _finalize_db(node, tmp_path, name, held): + db = tmp_path / name + _configure(node, db) + _prepare_db(node, db, []) + u = node.epoch_weight_to_units(1.0) + with sqlite3.connect(db) as c: + for m in ("good", "held"): + c.execute("INSERT INTO epoch_enroll VALUES (?, ?, ?)", (EPOCH, m, u)) + c.execute("INSERT INTO balances(miner_id, miner_pk, amount_i64) VALUES (?, ?, 0)", (m, m)) + for m in held: + c.execute("INSERT INTO miner_probation (miner, state, first_seen, last_seen, needs_review, " + "updated_at) VALUES (?, 'probation', 1, 1, 1, 1)", (m,)) + c.commit() + return db + + +def test_finalize_epoch_reads_hold_inside_write_lock(nodes, tmp_path, monkeypatch): + node = nodes["patched"] + db = _finalize_db(node, tmp_path, "finlock.db", held=[]) + import sybil_guard as sg + real = sg.settlement_held_miners + seen = {} + + def late_flag(conn, miners, epoch=None): + # A concurrent writer tries to flag 'held' at exactly this moment. + seen["in_txn"] = conn.in_transaction + other = sqlite3.connect(db, timeout=0) + try: + other.execute("INSERT INTO miner_probation (miner, state, first_seen, last_seen, needs_review, " + "updated_at) VALUES ('held', 'probation', 1, 1, 1, 1)") + other.commit() + seen["other"] = "committed" + except sqlite3.OperationalError as exc: + seen["other"] = str(exc) + finally: + other.close() + return real(conn, miners, epoch) + + monkeypatch.setattr(sg, "settlement_held_miners", late_flag) + node.finalize_epoch(EPOCH, 1.5 / 144) + assert seen["in_txn"] is True and "locked" in seen["other"] + + +def test_finalize_epoch_all_held_leaves_epoch_unsettled(nodes, tmp_path): + node = nodes["patched"] + db = _finalize_db(node, tmp_path, "finall.db", held=["good", "held"]) + node.finalize_epoch(EPOCH, 1.5 / 144) + with sqlite3.connect(db) as c: + assert c.execute("SELECT settled FROM epoch_state WHERE epoch=?", (EPOCH,)).fetchone()[0] == 0 + assert sum(r[0] for r in c.execute("SELECT amount_i64 FROM balances WHERE miner_id IN ('good','held')")) == 0 + + +def test_attest_request_path_runs_no_guard_ddl(nodes, tmp_path, sybil_rows): + node = nodes["patched"] + db = tmp_path / "ddl.db" + _configure(node, db) + _prepare_db(node, db, ["q1"]) + stmts = [] + real_connect = sqlite3.connect + + def tracing_connect(*a, **k): + conn = real_connect(*a, **k) + conn.set_trace_callback(stmts.append) + return conn + + row = sybil_rows[0] + node.sqlite3.connect = tracing_connect + try: + _attest(node, db, _g4_payload(row["miner"], "q1", json.loads(row["profile_json"]))) + finally: + node.sqlite3.connect = real_connect + guard_ddl = [s for s in stmts if s.lstrip().upper().startswith(("CREATE", "ALTER")) + and ("miner_probation" in s or "sybil_review_escrow" in s)] + assert stmts and not guard_ddl + + +def test_hold_applies_even_when_fingerprint_failed(nodes, tmp_path, sybil_rows, monkeypatch): + node = nodes["patched"] + db = tmp_path / "fpfail.db" + _configure(node, db) + _prepare_db(node, db, ["f1"]) + monkeypatch.setattr(node, "validate_fingerprint_data", lambda fp, claimed_device=None: (False, "test_fail")) + row = sybil_rows[0] + _attest(node, db, _g4_payload(row["miner"], "f1", json.loads(row["profile_json"]))) + with sqlite3.connect(db) as c: + w = c.execute("SELECT weight FROM epoch_enroll WHERE miner_pk=?", (row["miner"],)).fetchone()[0] + esc = c.execute("SELECT would_be_weight_units FROM sybil_review_escrow WHERE miner=?", + (row["miner"],)).fetchall() + assert w == 0 and esc == [(node.FAILED_FINGERPRINT_WEIGHT_UNITS,)] + + +def test_stored_history_flag_survives_non_incident_profile(nodes, tmp_path, sybil_rows): + """A cohort wallet that re-attests with an honest-looking profile is still + held (flag seeded from its stored pre-deploy history).""" + node = nodes["patched"] + db = tmp_path / "stored.db" + _configure(node, db) + _prepare_db(node, db, ["h1"]) + row = sybil_rows[0] + with sqlite3.connect(db) as c: + c.execute("CREATE TABLE IF NOT EXISTS miner_fingerprint_history (id INTEGER PRIMARY KEY AUTOINCREMENT, " + "miner TEXT NOT NULL, ts INTEGER NOT NULL, profile_json TEXT NOT NULL)") + c.execute("INSERT INTO miner_fingerprint_history (miner, ts, profile_json) VALUES (?, ?, ?)", + (row["miner"], 1, row["profile_json"])) + c.commit() + honest = {"clock_drift_cv": 0.0110244, "thermal_variance": 0.44862, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.34914} + _attest(node, db, _g4_payload(row["miner"], "h1", honest, arch="g5", cpu="PowerPC G5 970")) + assert _enrolled_weight(node, db, row["miner"]) == 0 + + +def test_admission_queued_identity_enrolls_at_zero(nodes, tmp_path): + node = nodes["patched"] + db = tmp_path / "adm_q.db" + _configure(node, db) + _prepare_db(node, db, ["a0", "a1", "a2"]) + honest = {"clock_drift_cv": 0.0110244, "thermal_variance": 0.44862, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.34914} + for i in range(3): + _attest(node, db, _g4_payload(f"RTCnew{i}", f"a{i}", honest, arch="g5", cpu="PowerPC G5 970"), + ip="198.51.100.77") + ws = [_enrolled_weight(node, db, f"RTCnew{i}") for i in range(3)] + assert ws[0] == ws[1] == pytest.approx(1.0) and ws[2] == 0 + + +def _break_classification(monkeypatch, sg, established_lookup_ok=True): + def boom(*a, **k): + raise sqlite3.OperationalError("database is locked") + monkeypatch.setattr(sg, "observe_attestation", boom) + monkeypatch.setattr(sg, "get_probation_status", boom) + if not established_lookup_ok: + monkeypatch.setattr(sg, "has_pre_cutoff_history", boom) + + +def test_classification_failure_keeps_established_weight(nodes, tmp_path, monkeypatch): + """Established miner + guard error -> exactly the live weight, never reduced.""" + import sybil_guard as sg + out = {} + prof = {"clock_drift_cv": 0.0110244, "thermal_variance": 0.44862, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.34914} + for name, node in nodes.items(): + db = tmp_path / f"cf_{name}.db" + _configure(node, db) + _prepare_db(node, db, ["c1"]) + _seed_established(db, "old-g5", n=1) + with monkeypatch.context() as mp: + if name == "patched": + _break_classification(mp, sg) + _attest(node, db, _g4_payload("old-g5", "c1", prof, arch="g5", cpu="PowerPC G5 970")) + out[name] = _enrolled_weight(node, db, "old-g5") + assert out["patched"] > 1.0 + if "live" in out: + assert out["patched"] == out["live"] + + +def test_classification_failure_with_unknown_establishment_uses_live_weight(nodes, tmp_path, monkeypatch): + """Round 2b (GLM): if even the establishment query fails, enrollment uses + the LIVE weight (CRITICAL log) instead of deferring every miner.""" + import sybil_guard as sg + prof = {"clock_drift_cv": 0.0110244, "thermal_variance": 0.44862, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.34914} + out = {} + for name, node in nodes.items(): + db = tmp_path / f"unk_{name}.db" + _configure(node, db) + _prepare_db(node, db, ["d9"]) + with monkeypatch.context() as mp: + if name == "patched": + _break_classification(mp, sg, established_lookup_ok=False) + body = _attest(node, db, _g4_payload("who", "d9", prof, arch="g5", cpu="PowerPC G5 970")) + assert body["ok"] is True + out[name] = _enrolled_weight(node, db, "who") + assert out["patched"] is not None + if "live" in out: + assert out["patched"] == out["live"] + + +def test_unreachable_db_defers_enrollment(nodes, tmp_path, monkeypatch): + import sybil_guard as sg + node = nodes["patched"] + db = tmp_path / "defer.db" + _configure(node, db) + _prepare_db(node, db, ["d8"]) + _break_classification(monkeypatch, sg, established_lookup_ok=False) + real = sg.fallback_status + monkeypatch.setattr(sg, "fallback_status", lambda conn, miner: real(None, miner)) + prof = {"clock_drift_cv": 0.0110244, "thermal_variance": 0.44862, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.34914} + body = _attest(node, db, _g4_payload("who2", "d8", prof, arch="g5", cpu="PowerPC G5 970")) + assert body["ok"] is True and _enrolled_weight(node, db, "who2") is None + + +@pytest.mark.parametrize("duration", [float("nan"), float("inf"), "nan", "Infinity"]) +def test_non_finite_binding_is_rejected(nodes, duration): + node = nodes["patched"] + nonce = "abcd1234" + b = {"nonce": nonce, "iterations": node.derive_measurement_workload(nonce), "duration_ns": duration} + v = node.verify_measurement_binding(nonce, b) + assert v["state"] == "malformed" and v["ok"] is False + # live accepted these as "bound" + if "live" in nodes: + assert nodes["live"].verify_measurement_binding(nonce, b)["state"] == "bound" + + + +# --------------------------------------------------------------------------- +# Round 3 +# --------------------------------------------------------------------------- + +def _bonus_db(node, tmp_path, name, state="trusted"): + db = tmp_path / name + _configure(node, db) + _prepare_db(node, db, []) + with sqlite3.connect(db) as c: + c.execute("INSERT INTO miner_probation (miner, state, first_seen, last_seen, updated_at) " + "VALUES ('g', ?, 1, 1, 1)", (state,)) + return db + + +def test_hold_committed_after_observation_blocks_bonus(nodes, tmp_path): + """The attestation observed 'trusted'; before payment another writer set + needs_review. The in-transaction re-read must withhold.""" + node = nodes["patched"] + db = _bonus_db(node, tmp_path, "race.db") + stale_status = {"state": "trusted"} # what observe returned + with sqlite3.connect(db) as c: # hold lands in between + c.execute("UPDATE miner_probation SET needs_review = 1, review_reason = 'operator' WHERE miner='g'") + assert node._check_welcome_bonus("g", stale_status) is False + assert _bonus_rows(db, "g") == 0 + with sqlite3.connect(db) as c: # retryable once cleared + c.execute("UPDATE miner_probation SET needs_review = 0 WHERE miner='g'") + assert node._check_welcome_bonus("g", stale_status) is True + + +def test_cohort_insert_after_trusted_row_blocks_bonus_and_holds(nodes, tmp_path): + node = nodes["patched"] + import sybil_guard as sg + db = _bonus_db(node, tmp_path, "cohort.db") + with sqlite3.connect(db) as c: + c.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (miner TEXT PRIMARY KEY)") + c.execute(f"INSERT INTO {sg.INCIDENT_COHORT_TABLE} VALUES ('g')") + assert node._check_welcome_bonus("g", {"state": "trusted"}) is False + assert _bonus_rows(db, "g") == 0 + with sqlite3.connect(db, isolation_level=None) as c: + st = sg.get_probation_status(c, "g") # read path picks it up + assert sg.needs_review(st) and sg.enrollment_weight(2.5, st) == 0.0 + st2 = sg.observe_attestation(c, "g", {"clock_drift_cv": 0.05}, "192.0.2.9", now=1790400000) + assert st2["needs_review"] == 1 and st2["review_reason"] == sg.REVIEW_COHORT # persisted + assert sg.review_held_miners(c, ["g"]) == {"g"} + + +def test_bonus_withheld_when_eligibility_undeterminable(nodes, tmp_path, monkeypatch): + node = nodes["patched"] + import sybil_guard as sg + db = _bonus_db(node, tmp_path, "undet.db") + real = sg._cohort_members + + def boom(conn, miners): + raise sqlite3.OperationalError("disk I/O error") + + with sqlite3.connect(db) as c: + c.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (miner TEXT PRIMARY KEY)") + monkeypatch.setattr(sg, "_cohort_members", boom) + assert node._check_welcome_bonus("g", {"state": "trusted"}) is False + monkeypatch.setattr(sg, "_cohort_members", real) + assert node._check_welcome_bonus("g", {"state": "trusted"}) is True + + +def test_grandfathered_bonus_behaviour_unchanged(nodes, tmp_path): + """Established miners: live never pays (history > 1); a grandfathered miner + with a single pre-cutoff row + persisted row follows the legacy rule.""" + node = nodes["patched"] + db = _bonus_db(node, tmp_path, "gf.db", state="grandfathered") + _seed_established(db, "g", n=1) + assert node._check_welcome_bonus("g", {"state": "grandfathered"}) is True # first attestation only + db2 = _bonus_db(node, tmp_path, "gf2.db", state="grandfathered") + _seed_established(db2, "g", n=5) + assert node._check_welcome_bonus("g", {"state": "grandfathered"}) is False + + +def test_node_bonus_paid_with_absent_cohort_and_withheld_with_malformed(nodes, tmp_path): + """Round 3b end to end through _check_welcome_bonus.""" + node = nodes["patched"] + import sybil_guard as sg + db = _bonus_db(node, tmp_path, "c3b.db") + db2 = _bonus_db(node, tmp_path, "c3b_bad.db") + with sqlite3.connect(db2) as c: + c.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (wallet_x TEXT)") + assert node._check_welcome_bonus("g", {"state": "trusted"}) is False # db2 is current DB_PATH + assert _bonus_rows(db2, "g") == 0 + _configure(node, db) + assert node._check_welcome_bonus("g", {"state": "trusted"}) is True # absent table: paid diff --git a/node/tests/sybil_guard/test_sybil_guard_probation.py b/node/tests/sybil_guard/test_sybil_guard_probation.py new file mode 100644 index 000000000..30c7bc298 --- /dev/null +++ b/node/tests/sybil_guard/test_sybil_guard_probation.py @@ -0,0 +1,696 @@ +# SPDX-License-Identifier: MIT +"""sybil_guard probation state machine, driven by the (synthetic) incident fixtures. + +Pure module + in-memory SQLite: no node import, no network. Time is simulated +by passing `now` explicitly. +""" +import collections +import json +import random +import sqlite3 + +import pytest + +import sg_helpers # noqa: F401 (node/ on sys.path) +import sybil_guard as sg + +T0 = sg.GRANDFATHER_CUTOFF_TS + 7 * 86400 # a week after the cutoff +HOUR = 3600 + + +def _db(): + conn = sqlite3.connect(":memory:", isolation_level=None) + conn.executescript( + """ + CREATE TABLE miner_attest_history (id INTEGER PRIMARY KEY AUTOINCREMENT, miner TEXT, + ts_ok INTEGER, device_family TEXT, device_arch TEXT, entropy_score REAL, + fingerprint_passed INTEGER, fingerprint_checks_json TEXT); + CREATE TABLE miner_fingerprint_history (id INTEGER PRIMARY KEY AUTOINCREMENT, + miner TEXT NOT NULL, ts INTEGER NOT NULL, profile_json TEXT NOT NULL); + """ + ) + sg.init_schema(conn) + return conn + + +def _attest(conn, miner, profile, ip, now, **kw): + """Mimic record_attestation_success (history + snapshot, keep last 10) then observe.""" + conn.execute("INSERT INTO miner_attest_history (miner, ts_ok, fingerprint_passed) VALUES (?, ?, 1)", + (miner, now)) + conn.execute("INSERT INTO miner_fingerprint_history (miner, ts, profile_json) VALUES (?, ?, ?)", + (miner, now, json.dumps(sg.normalize_profile(profile)))) + conn.execute( + "DELETE FROM miner_fingerprint_history WHERE miner = ? AND id NOT IN " + "(SELECT id FROM miner_fingerprint_history WHERE miner = ? ORDER BY ts DESC, id DESC LIMIT 10)", + (miner, miner)) + return sg.observe_attestation(conn, miner, profile, ip, now=now, **kw) + + +def _profiles(rows): + by = collections.defaultdict(list) + for r in sorted(rows, key=lambda r: r["ts"]): + by[r["miner"]].append(json.loads(r["profile_json"])) + return by + + +def _unique_ip(i): + return f"198.{18 + (i // 65536) % 2}.{(i // 256) % 256}.{i % 256}" + + +# -------------------------------------------------------------------------- +# Flagged wallets +# -------------------------------------------------------------------------- + +def test_every_sybil_wallet_replayed_for_72h_never_exits(sybil_rows): + """Each of the 120 wallets re-sends its recorded profile every 30 min for + 72 h from its own unique IP (i.e. even without the IP caps).""" + conn = _db() + by = _profiles(sybil_rows) + assert len(by) == 120 + for i, (miner, profiles) in enumerate(by.items()): + st = None + for k in range(144): + st = _attest(conn, miner, profiles[k % len(profiles)], _unique_ip(i), T0 + k * 1800) + assert st["state"] != sg.STATE_TRUSTED + assert sg.enrollment_weight(2.5, st) <= sg.PROBATION_WEIGHT_CAP + assert st["needs_review"] == 1 + assert sg.enrollment_weight(2.5, st) == 0.0 + assert sg.needs_review(st) + + +def test_sybil_wallets_from_recorded_ips_hit_admission_cap(sybil_rows): + conn = _db() + first = {} + for r in sorted(sybil_rows, key=lambda r: r["ts"]): + first.setdefault(r["miner"], r) + states = collections.Counter() + for miner, r in first.items(): + st = _attest(conn, miner, json.loads(r["profile_json"]), r["source_ip"], r["ts"] + 30 * 86400) + states[st["state"]] += 1 + # 3 source IPs x NEW_MINERS_PER_IP_PER_DAY admitted; everyone else queued. + assert states[sg.STATE_PROBATION] == 3 * sg.NEW_MINERS_PER_IP_PER_DAY + assert states[sg.STATE_ADMISSION_QUEUED] == 120 - 3 * sg.NEW_MINERS_PER_IP_PER_DAY + assert states[sg.STATE_TRUSTED] == 0 + + +def test_redrawing_generator_never_exits(): + """Smarter attacker: redraw round(uniform, 4) inside the box every time.""" + conn = _db() + rng = random.Random(11) + for i in range(20): + miner, st = f"RTCredraw{i:02d}", None + for k in range(144): + prof = {m: round(rng.uniform(lo, hi), 4) for m, (lo, hi) in sg.INCIDENT_20260924_BOX.items()} + st = _attest(conn, miner, prof, _unique_ip(1000 + i), T0 + k * 1800) + assert st["state"] != sg.STATE_TRUSTED + assert st["needs_review"] == 1 + + +def test_known_limit_full_precision_random_walk_can_graduate(): + """Honesty test: a generator that emits full-precision values inside honest + ranges and drifts slowly DOES graduate. Probation is a cost, not a proof.""" + conn = _db() + rng = random.Random(3) + prof = {"clock_drift_cv": 0.0731234, "thermal_variance": 0.98, "jitter_cv": 0.0412345678901, + "cache_hierarchy_ratio": 1.013} + st = None + for k in range(60): + prof = {m: v * (1 + rng.uniform(-0.03, 0.03)) for m, v in prof.items()} + st = _attest(conn, "RTCcarefulforger", prof, "203.0.113.9", T0 + k * 1800) + assert st["state"] == sg.STATE_TRUSTED + + +# -------------------------------------------------------------------------- +# Honest miners +# -------------------------------------------------------------------------- + +def test_honest_varying_miners_graduate_as_new_miners(honest_rows): + """Replay each honest miner's real sequence as if it were NEW: cycled every + 20 min for 30 h from its own IP. Miners whose client varies must graduate.""" + by = _profiles(honest_rows) + graduated, stuck = [], [] + for i, (miner, profiles) in enumerate(by.items()): + distinct = {json.dumps(p, sort_keys=True) for p in profiles} + if len(distinct) < 4: + # static series are covered by the next test; 2-3 distinct samples + # are too few to replay for 30 h without inventing A-B-A-B jumps. + continue + conn = _db() + st = None + for k in range(90): + st = _attest(conn, miner, profiles[k % len(profiles)], _unique_ip(5000 + i), T0 + k * 1200) + (graduated if st["state"] == sg.STATE_TRUSTED else stuck).append((miner, st["blockers"])) + print(f"\nhonest varying miners graduated: {len(graduated)}/{len(graduated) + len(stuck)}; stuck={stuck}") + assert graduated, "no honest miner could graduate" + # Cycling a short real sequence creates artificial jumps at the wrap point, + # so allow at most one miner to be held by the redraw test for that reason. + assert len(stuck) <= 1, stuck + for _, blockers in stuck: + assert all(b.startswith("memoryless_redraw") for b in blockers), blockers + + +def test_static_honest_miner_as_new_stays_at_baseline_but_keeps_mining(): + conn = _db() + lab_g4 = {"clock_drift_cv": 0.0123, "thermal_variance": 0.0, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.0} + st = None + for k in range(100): + st = _attest(conn, "brand-new-static-g4", lab_g4, "192.0.2.10", T0 + k * 1800) + assert st["state"] == sg.STATE_PROBATION + assert st["needs_review"] == 0 and not st["anomalies"] + assert sg.enrollment_weight(2.5, st) == 1.0 # baseline, never 0 + + +def _seed_history(conn, miner, start, n, step): + for k in range(n): + conn.execute("INSERT INTO miner_attest_history (miner, ts_ok, fingerprint_passed) VALUES (?, ?, 1)", + (miner, start + k * step)) + + +def test_established_lab_g4_with_constant_profile_is_grandfathered(): + conn = _db() + _seed_history(conn, "lab-g4-example", sg.GRANDFATHER_CUTOFF_TS - 30 * 86400, 200, 3 * HOUR) + lab_g4 = {"clock_drift_cv": 0.0123, "thermal_variance": 0.0, "jitter_cv": 0.0, + "cache_hierarchy_ratio": 2.0} + for k in range(20): + st = _attest(conn, "lab-g4-example", lab_g4, "192.0.2.125", T0 + k * 1800) + assert st["state"] == sg.STATE_GRANDFATHERED + assert sg.enrollment_weight(2.5, st) == 2.5 + assert sg.enrollment_weight(1.3, st) == 1.3 + + +def test_grandfathered_miner_IS_held_when_incident_detector_fires(): + """Round 2: grandfathering keeps today's behaviour EXCEPT for the detector.""" + conn = _db() + _seed_history(conn, "old-miner", sg.GRANDFATHER_CUTOFF_TS - 10 * 86400, 50, 4 * HOUR) + st = _attest(conn, "old-miner", {"clock_drift_cv": 0.02, "thermal_variance": 3.1234, + "jitter_cv": 0.1, "cache_hierarchy_ratio": 2.5}, + "192.0.2.1", T0) + # Round 2b: ONE matching sample is not enough for an established miner. + assert st["state"] == sg.STATE_GRANDFATHERED and not sg.needs_review(st) + assert sg.enrollment_weight(2.5, st) == 2.5 + st = _attest(conn, "old-miner", {"clock_drift_cv": 0.021, "thermal_variance": 3.1235, + "jitter_cv": 0.1, "cache_hierarchy_ratio": 2.5}, + "192.0.2.1", T0 + 600) + assert st["state"] == sg.STATE_GRANDFATHERED + assert sg.needs_review(st) and st["review_reason"] == sg.REVIEW_STORED + assert sg.enrollment_weight(2.5, st) == 0.0 + assert sg.review_held_miners(conn, ["old-miner"]) == {"old-miner"} + + +def test_grandfathered_honest_profile_keeps_weight(): + conn = _db() + _seed_history(conn, "old-honest", sg.GRANDFATHER_CUTOFF_TS - 10 * 86400, 1, HOUR) + st = _attest(conn, "old-honest", {"clock_drift_cv": 0.0110244, "thermal_variance": 0.44862, + "jitter_cv": 0.0, "cache_hierarchy_ratio": 2.34914}, + "192.0.2.1", T0) + assert st["state"] == sg.STATE_GRANDFATHERED and not sg.needs_review(st) + assert sg.enrollment_weight(2.5, st) == 2.5 + + +def test_any_pre_cutoff_attestation_grandfathers(): + """Round 2 decision: one attestation before the cutoff is enough (the + 9/13-14 recon probes are therefore grandfathered; the detector/cohort still + holds them if they match).""" + conn = _db() + _seed_history(conn, "recon-probe-003", sg.GRANDFATHER_CUTOFF_TS - 11 * 86400, 1, HOUR) + st = _attest(conn, "recon-probe-003", {"clock_drift_cv": 0.0123}, "198.51.100.77", T0) + assert st["state"] == sg.STATE_GRANDFATHERED + assert sg.has_pre_cutoff_history(conn, "recon-probe-003") + + +def test_attestation_after_cutoff_does_not_grandfather(): + conn = _db() + _seed_history(conn, "late", sg.GRANDFATHER_CUTOFF_TS + 60, 50, 60) + assert not sg.has_pre_cutoff_history(conn, "late") + + +# -------------------------------------------------------------------------- +# Population caps +# -------------------------------------------------------------------------- + +def _varying(k, base=1.0): + return {"clock_drift_cv": 0.05 + 0.001 * (k % 7) + 0.0000013 * k, + "thermal_variance": base + 0.01 * (k % 5) + 0.0000017 * k, + "jitter_cv": 0.041234567890123 + 0.0001 * (k % 3), + "cache_hierarchy_ratio": 1.001 + 0.001 * (k % 4)} + + +def test_admission_cap_queues_third_new_miner_then_admits_next_day(): + conn = _db() + s = [_attest(conn, f"m{i}", _varying(0), "192.0.2.50", T0 + i) for i in range(3)] + assert [x["state"] for x in s] == [sg.STATE_PROBATION, sg.STATE_PROBATION, sg.STATE_ADMISSION_QUEUED] + # re-attestations of the admitted two are unaffected + assert _attest(conn, "m0", _varying(1), "192.0.2.50", T0 + 600)["state"] == sg.STATE_PROBATION + assert _attest(conn, "m2", _varying(1), "192.0.2.50", T0 + 3600)["state"] == sg.STATE_ADMISSION_QUEUED + assert _attest(conn, "m2", _varying(2), "192.0.2.50", T0 + 86400 + 10)["state"] == sg.STATE_PROBATION + # a different /32 in the same /24 is admitted independently + assert _attest(conn, "m3", _varying(0), "192.0.2.51", T0 + 5)["state"] == sg.STATE_PROBATION + + +def test_exit_cap_per_slash24_queues_excess_then_releases(): + conn = _db() + miners = [f"lab{i}" for i in range(3)] + for k in range(60): # 3 miners, distinct /32s, same /24, all eligible at the same time + for i, m in enumerate(miners): + _attest(conn, m, _varying(k, base=0.5 + i), f"192.0.2.{60 + i}", T0 + k * 1800 + i) + states = collections.Counter(sg.get_probation_status(conn, m)["state"] for m in miners) + assert states[sg.STATE_TRUSTED] == 3 # queued one released an hour later + rows = conn.execute("SELECT miner, exited_at FROM miner_probation ORDER BY exited_at").fetchall() + assert rows[2][1] - rows[0][1] >= 3600, rows + + +def test_exit_cap_blocks_same_hour(): + conn = _db() + miners = [f"q{i}" for i in range(3)] + last = {} + for k in range(49): + for i, m in enumerate(miners): + last[m] = _attest(conn, m, _varying(k, base=0.5 + i), f"192.0.2.{70 + i}", T0 + k * 1800 + i) + got = collections.Counter(s["state"] for s in last.values()) + assert got[sg.STATE_QUEUED] == 1 and got[sg.STATE_TRUSTED] == 2, got + + +def test_correlated_cluster_blocks_exit(): + conn = _db() + calls = [] + + def fake_cluster(c, members): + calls.append(list(members)) + return {"state": "correlated", "spread": 0.1} + + st = None + for k in range(60): + st = _attest(conn, "clustered", _varying(k), "192.0.2.90", T0 + k * 1800, cluster_check=fake_cluster) + assert st["state"] == sg.STATE_PROBATION + assert any(b.startswith("cluster_correlated") for b in st["blockers"]) + assert calls + + +# -------------------------------------------------------------------------- +# Weight rules, anomaly extension, binding +# -------------------------------------------------------------------------- + +def test_anomaly_extends_probation(): + conn = _db() + for k in range(50): + st = _attest(conn, "hot", _varying(k), "192.0.2.100", T0 + k * 1800) + assert st["state"] == sg.STATE_TRUSTED + conn2 = _db() + for k in range(50): + prof = _varying(k) + if k == 45: + prof = dict(prof, thermal_variance=4.2) # out of honest range once + st = _attest(conn2, "hot", prof, "192.0.2.100", T0 + k * 1800) + assert st["state"] == sg.STATE_PROBATION + assert any(b.startswith("anomaly_extension_until") for b in st["blockers"]) + assert st["needs_review"] == 0 # extension only, not a hold + + +def test_failed_fingerprint_attestations_do_not_count(): + conn = _db() + for k in range(60): + st = _attest(conn, "vm", _varying(k), "192.0.2.110", T0 + k * 1800, fingerprint_passed=False) + assert st["state"] == sg.STATE_PROBATION and st["attest_count"] == 0 + + +@pytest.mark.parametrize("status,weight,expected", [ + ({"state": sg.STATE_PROBATION}, 2.5, 1.0), + ({"state": sg.STATE_PROBATION}, 0.8, 0.8), + ({"state": sg.STATE_PROBATION}, 0.0005, 0.0005), + ({"state": sg.STATE_ADMISSION_QUEUED}, 4.0, 0.0), + ({"state": sg.STATE_ADMISSION_QUEUED}, 0.8, 0.0), + ({"state": sg.STATE_UNAVAILABLE, "established": True}, 2.5, 2.5), + ({"state": sg.STATE_UNAVAILABLE, "established": False}, 2.5, 1.0), + ({"state": sg.STATE_UNAVAILABLE}, 2.5, 1.0), + (None, 2.5, 1.0), + ({"state": sg.STATE_PROBATION, "needs_review": 1}, 2.5, 0.0), + ({"state": sg.STATE_GRANDFATHERED, "needs_review": 1}, 2.5, 0.0), + ({"state": sg.STATE_GRANDFATHERED}, 2.5, 2.5), + # REQUIRE_MEASUREMENT_BINDING_FOR_NEW_PREMIUM defaults to False (Scott, 2026-09-24): + # probation alone gates the premium, so a graduated miner keeps it without a binding. + ({"state": sg.STATE_TRUSTED, "reason": "probation_exit", "last_binding_state": "absent"}, 2.5, 2.5), + ({"state": sg.STATE_TRUSTED, "reason": "probation_exit", "last_binding_state": "bound"}, 2.5, 2.5), + ({"state": sg.STATE_TRUSTED, "reason": "operator_allowlist", "last_binding_state": None}, 2.5, 2.5), +]) +def test_enrollment_weight_table(status, weight, expected): + assert sg.enrollment_weight(weight, status) == expected + + +def test_binding_requirement_when_enabled(monkeypatch): + """With the flag on, a graduated miner needs a 'bound' measurement for premium.""" + monkeypatch.setattr(sg, "REQUIRE_MEASUREMENT_BINDING_FOR_NEW_PREMIUM", True) + absent = {"state": sg.STATE_TRUSTED, "reason": "probation_exit", "last_binding_state": "absent"} + bound = {"state": sg.STATE_TRUSTED, "reason": "probation_exit", "last_binding_state": "bound"} + allow = {"state": sg.STATE_TRUSTED, "reason": "operator_allowlist", "last_binding_state": None} + assert sg.enrollment_weight(2.5, absent) == 1.0 + assert sg.enrollment_weight(2.5, bound) == 2.5 + assert sg.enrollment_weight(2.5, allow) == 2.5 + + +def test_allowlist_env(monkeypatch): + monkeypatch.setenv(sg.PROBATION_ALLOWLIST_ENV, "new-lab-g4, other") + conn = _db() + st = _attest(conn, "new-lab-g4", {"clock_drift_cv": 0.0123}, "192.0.2.99", T0) + assert st["state"] == sg.STATE_TRUSTED and st["reason"] == "operator_allowlist" + + +def test_review_held_miners_and_escrow(): + conn = _db() + _attest(conn, "bad", {"clock_drift_cv": 0.02, "thermal_variance": 3.1234, "jitter_cv": 0.1, + "cache_hierarchy_ratio": 2.5}, "192.0.2.120", T0) + _attest(conn, "good", _varying(0), "192.0.2.121", T0) + assert sg.review_held_miners(conn, ["bad", "good", "unknown"]) == {"bad"} + sg.record_review_escrow(conn, 297, "bad", 1_000_000_000, "t", now=T0) + sg.record_review_escrow(conn, 297, "bad", 5, "t2", now=T0) # first wins + assert conn.execute("SELECT would_be_weight_units FROM sybil_review_escrow").fetchall() == [(1_000_000_000,)] + assert sg.review_held_miners(_db(), ["bad"]) == set() # no table -> nothing held + + +# -------------------------------------------------------------------------- +# Round 2 +# -------------------------------------------------------------------------- + +INCIDENT = {"clock_drift_cv": 0.02, "thermal_variance": 3.1234, "jitter_cv": 0.1, "cache_hierarchy_ratio": 2.5} + + +def test_needs_review_seeded_from_stored_history(): + """Grok: a Sybil that stops sending the box must still be held. Its STORED + fingerprint history (pre-deploy rows) seeds the sticky flag.""" + conn = _db() + conn.execute("INSERT INTO miner_fingerprint_history (miner, ts, profile_json) VALUES (?, ?, ?)", + ("RTCsyb", T0 - 86400, json.dumps(INCIDENT))) + st = _attest(conn, "RTCsyb", _varying(0), "198.51.100.7", T0) + assert st["needs_review"] == 1 and st["review_reason"] == sg.REVIEW_STORED + assert sg.enrollment_weight(2.5, st) == 0.0 + + +def test_needs_review_seeded_from_cohort_table_any_id_column(): + for col in ("miner", "miner_id", "wallet"): + conn = _db() + conn.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} ({col} TEXT, source_ip TEXT)") + conn.execute(f"INSERT INTO {sg.INCIDENT_COHORT_TABLE} VALUES ('RTCc', '203.0.113.10')") + st = _attest(conn, "RTCc", _varying(0), "198.51.100.8", T0) + assert st["review_reason"] == sg.REVIEW_COHORT, col + # read-only status used by /epoch/enroll for a miner with no row yet + assert sg.get_probation_status(conn, "RTCc")["needs_review"] == 1 + + +def test_cohort_table_absent_or_unrecognised_is_fail_safe(): + conn = _db() + assert sg.stored_review_reason(conn, "x") is None + conn.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (foo TEXT)") + assert sg.stored_review_reason(conn, "x") is None + + +def test_get_probation_status_for_unseen_miner_uses_stored_data(): + conn = _db() + conn.execute("INSERT INTO miner_fingerprint_history (miner, ts, profile_json) VALUES ('u', 1, ?)", + (json.dumps(INCIDENT),)) + st = sg.get_probation_status(conn, "u") + assert st["state"] == sg.STATE_PROBATION and sg.needs_review(st) + + +def test_varied_metrics_judged_over_whole_window(): + """Grok: a last sample of clock-only must not drop the 2-metric requirement, + and a metric must move at least METRIC_MIN_MOVES times.""" + conn = _db() + st = None + for k in range(60): + prof = {"clock_drift_cv": 0.05 + 0.001 * (k % 7), "thermal_variance": 1.0, + "jitter_cv": 0.041234567, "cache_hierarchy_ratio": 1.001} + if k >= 30: # a single step in thermal (one move), then constant + prof["thermal_variance"] = 1.0001 + if k >= 55: # final samples report clock only + prof = {"clock_drift_cv": prof["clock_drift_cv"]} + st = _attest(conn, "wiggle", prof, "198.51.100.9", T0 + k * 1800) + assert st["state"] == sg.STATE_PROBATION + assert any(b.startswith("varied_metrics:1/2") for b in st["blockers"]), st["blockers"] + + +def test_exit_cap_charged_to_admission_prefix(): + """Grok: leaving from another /24 must not dodge the admission /24's cap.""" + conn = _db() + for i in range(2): # fill 192.0.2.0/24's exit cap + for k in range(49): + _attest(conn, f"a{i}", _varying(k, base=0.5 + i), f"192.0.2.{10 + i}", T0 + k * 1800 + i) + last = None + for k in range(49): # admitted in 192.0.2.0/24, later attests from 203.0.113.0/24 + ip = "192.0.2.30" if k == 0 else "203.0.113.30" + last = _attest(conn, "mover", _varying(k, base=2.2), ip, T0 + k * 1800 + 5) + assert last["state"] == sg.STATE_QUEUED + assert any("192.0.2.0/24" in b for b in last["blockers"]) + + +def test_observe_does_no_ddl_and_raises_without_tables(): + conn = sqlite3.connect(":memory:", isolation_level=None) + stmts = [] + conn.set_trace_callback(stmts.append) + with pytest.raises(sqlite3.OperationalError): + sg.observe_attestation(conn, "m", _varying(0), "192.0.2.1", now=T0) + assert not [s for s in stmts if s.lstrip().upper().startswith(("CREATE", "ALTER", "DROP"))] + + +def test_init_schema_rejects_incompatible_table(): + conn = sqlite3.connect(":memory:") + conn.execute("CREATE TABLE miner_probation (miner TEXT PRIMARY KEY)") + with pytest.raises(sg.SchemaError): + sg.init_schema(conn) + + +def test_fallback_status_and_defer(): + conn = _db() + _seed_history(conn, "old", sg.GRANDFATHER_CUTOFF_TS - 86400, 1, HOUR) + old = sg.fallback_status(conn, "old") + new = sg.fallback_status(conn, "new") + unreachable = sg.fallback_status(None, "x") + assert old["established"] is True and sg.enrollment_weight(2.5, old) == 2.5 + assert new["established"] is False and sg.enrollment_weight(2.5, new) == 1.0 + assert sg.should_defer_enrollment(unreachable) # only a dead DB defers + assert not sg.should_defer_enrollment(old) and not sg.should_defer_enrollment(new) + + +def test_history_query_failure_falls_back_to_live_not_defer(): + """GLM: a missing ts_ok column must not 503 every miner. It raises + SchemaError in the normal path, and fallback_status then uses LIVE weight.""" + conn = sqlite3.connect(":memory:") + conn.execute("CREATE TABLE miner_attest_history (id INTEGER PRIMARY KEY, miner TEXT, ts INTEGER)") + with pytest.raises(sg.SchemaError): + sg.has_pre_cutoff_history(conn, "m") + st = sg.fallback_status(conn, "m") + assert st["established"] is None and not sg.should_defer_enrollment(st) + assert sg.enrollment_weight(2.5, st) == 2.5 + + +def test_single_stored_match_does_not_flag_grandfathered_but_cohort_does(): + conn = _db() + _seed_history(conn, "gf", sg.GRANDFATHER_CUTOFF_TS - 86400, 1, HOUR) + conn.execute("INSERT INTO miner_fingerprint_history (miner, ts, profile_json) VALUES ('gf', 1, ?)", + (json.dumps(INCIDENT),)) + assert sg.stored_review_reason(conn, "gf", grandfathered=True) is None + assert sg.stored_review_reason(conn, "gf", grandfathered=False) == sg.REVIEW_STORED + st = _attest(conn, "gf", _varying(0), "192.0.2.3", T0) + assert st["state"] == sg.STATE_GRANDFATHERED and not sg.needs_review(st) + conn.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (miner TEXT)") + conn.execute(f"INSERT INTO {sg.INCIDENT_COHORT_TABLE} VALUES ('gf2')") + _seed_history(conn, "gf2", sg.GRANDFATHER_CUTOFF_TS - 86400, 1, HOUR) + st2 = _attest(conn, "gf2", _varying(0), "192.0.2.4", T0) + assert st2["state"] == sg.STATE_GRANDFATHERED and st2["review_reason"] == sg.REVIEW_COHORT + + +def test_grandfathered_flag_logs_critical(caplog): + conn = _db() + conn.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (miner TEXT)") + conn.execute(f"INSERT INTO {sg.INCIDENT_COHORT_TABLE} VALUES ('gf3')") + _seed_history(conn, "gf3", sg.GRANDFATHER_CUTOFF_TS - 86400, 1, HOUR) + with caplog.at_level("CRITICAL", logger="sybil_guard"): + _attest(conn, "gf3", _varying(0), "192.0.2.5", T0) + assert any("GRANDFATHERED miner gf3 put in needs_review" in r.getMessage() for r in caplog.records) + + + +def test_exit_cap_charged_to_current_prefix_too(): + """Round 3: three miners admitted from three different /24s, graduating + through ONE shared current /24 within an hour -> the third queues.""" + conn = _db() + shared = "203.0.113.{}" + last = {} + for i, adm_ip in enumerate(("192.0.2.10", "198.51.100.10", "100.64.7.10")): + for k in range(49): + ip = adm_ip if k == 0 else shared.format(20 + i) + last[i] = _attest(conn, f"x{i}", _varying(k, base=0.5 + i), ip, T0 + k * 1800 + i) + states = [last[i]["state"] for i in range(3)] + assert states.count(sg.STATE_TRUSTED) == 2 and states.count(sg.STATE_QUEUED) == 1, states + q = [last[i] for i in range(3) if last[i]["state"] == sg.STATE_QUEUED][0] + assert any("203.0.113.0/24" in b for b in q["blockers"]) + rows = conn.execute("SELECT exit_prefix, exit_current_prefix FROM miner_probation " + "WHERE exited_at IS NOT NULL").fetchall() + assert all(cur == "203.0.113.0/24" for _, cur in rows) + + +def test_exit_cap_counts_identical_prefixes_once(): + """Admission /24 == current /24: one exit counts once (not twice).""" + conn = _db() + last = {} + for i in range(2): + for k in range(49): + last[i] = _attest(conn, f"s{i}", _varying(k, base=0.5 + i), f"192.0.2.{40 + i}", T0 + k * 1800 + i) + assert last[0]["state"] == sg.STATE_TRUSTED and last[1]["state"] == sg.STATE_TRUSTED + + +def test_exit_cap_ipv6_48_both_prefixes(): + conn = _db() + last = {} + for i, adm in enumerate(("2001:db8:1::5", "2001:db8:2::5", "2001:db8:3::5")): + for k in range(49): + ip = adm if k == 0 else f"2001:db8:ff::{i + 1}" + last[i] = _attest(conn, f"v6{i}", _varying(k, base=0.5 + i), ip, T0 + k * 1800 + i) + states = [last[i]["state"] for i in range(3)] + assert states.count(sg.STATE_QUEUED) == 1, states + + +def test_init_schema_on_empty_db_has_new_column(): + conn = sqlite3.connect(":memory:") + sg.init_schema(conn) + cols = {r[1] for r in conn.execute("PRAGMA table_info(miner_probation)")} + assert "exit_current_prefix" in cols and not sg.verify_schema(conn) + + +# -------------------------------------------------------------------------- +# Round 3b: cohort table absent / malformed / unreadable +# -------------------------------------------------------------------------- + +def _trusted_row(conn, miner, state=sg.STATE_TRUSTED): + conn.execute("INSERT INTO miner_probation (miner, state, first_seen, last_seen, updated_at) " + "VALUES (?, ?, 1, 1, 1)", (miner, state)) + + +def test_bonus_eligible_when_cohort_table_absent(): + conn = _db() + _trusted_row(conn, "t") + assert sg.bonus_eligibility_in_txn(conn, "t") == (True, sg.STATE_TRUSTED, "ok") + + +def test_bonus_withheld_when_cohort_table_malformed(caplog): + conn = _db() + _trusted_row(conn, "t") + conn.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (wallet_x TEXT)") + with caplog.at_level("CRITICAL", logger="sybil_guard"): + ok, _, why = sg.bonus_eligibility_in_txn(conn, "t") + assert ok is False and why.startswith("cohort_undeterminable") + assert any("WITHHELD" in r.getMessage() for r in caplog.records) + + +def test_bonus_withheld_on_cohort_read_error(monkeypatch): + conn = _db() + _trusted_row(conn, "t") + conn.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (miner TEXT)") + real = sg._cohort_members + + def boom(c, miners, strict=False): + raise sqlite3.OperationalError("disk I/O error") + + monkeypatch.setattr(sg, "_cohort_members", boom) + ok, _, why = sg.bonus_eligibility_in_txn(conn, "t") + assert ok is False and why.startswith("cohort_undeterminable") + monkeypatch.setattr(sg, "_cohort_members", real) + assert sg.bonus_eligibility_in_txn(conn, "t")[0] is True + + +def test_grandfathered_bonus_eligibility_unchanged_by_cohort_policy(): + conn = _db() + _trusted_row(conn, "gf", state=sg.STATE_GRANDFATHERED) + assert sg.bonus_eligibility_in_txn(conn, "gf") == (True, sg.STATE_GRANDFATHERED, "ok") + conn.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (miner TEXT)") + assert sg.bonus_eligibility_in_txn(conn, "gf")[0] is True + conn.execute(f"INSERT INTO {sg.INCIDENT_COHORT_TABLE} VALUES ('gf')") + assert sg.bonus_eligibility_in_txn(conn, "gf") == (False, sg.STATE_GRANDFATHERED, "cohort_member") + + +@pytest.mark.parametrize("kind", ["malformed", "read_error"]) +def test_settlement_keeps_probation_holds_when_cohort_undeterminable(kind, monkeypatch, caplog): + conn = _db() + conn.execute("INSERT INTO miner_probation (miner, state, first_seen, last_seen, needs_review, updated_at) " + "VALUES ('held', 'probation', 1, 1, 1, 1)") + _trusted_row(conn, "ok") + if kind == "malformed": + conn.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (wallet_x TEXT)") + else: + conn.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (miner TEXT)") + + def boom(c, miners, strict=False): + raise sqlite3.OperationalError("disk I/O error") + monkeypatch.setattr(sg, "_cohort_members", boom) + with caplog.at_level("CRITICAL", logger="sybil_guard"): + held = sg.settlement_held_miners(conn, ["held", "ok"], epoch=297) + assert held == {"held"} + assert any(r.levelname == "CRITICAL" for r in caplog.records) + + +# -------------------------------------------------------------------------- +# falsegreen fixes (2026-09-25): the cluster check and a missing metrics +# record must fail CLOSED (block graduation), never open. +# -------------------------------------------------------------------------- + +def _run_to_eligible(conn, miner, ip, cluster_check): + st = None + for k in range(60): + st = _attest(conn, miner, _varying(k), ip, T0 + k * 1800, cluster_check=cluster_check) + return st + + +def test_cluster_check_raising_blocks_exit(caplog): + def boom(c, members): + raise RuntimeError("clustering backend down") + + conn = _db() + with caplog.at_level("ERROR", logger="sybil_guard"): + st = _run_to_eligible(conn, "fg-raise", "192.0.2.91", boom) + assert st["state"] == sg.STATE_PROBATION + assert any(b.startswith("cluster_check_unavailable:RuntimeError") for b in st["blockers"]) + assert sg.enrollment_weight(2.5, st) <= sg.PROBATION_WEIGHT_CAP + assert any("cluster_check failed" in r.getMessage() for r in caplog.records) + + +@pytest.mark.parametrize("verdict", [{}, None]) +def test_cluster_check_empty_verdict_blocks_exit(verdict): + conn = _db() + st = _run_to_eligible(conn, "fg-empty", "192.0.2.92", lambda c, m: verdict) + assert st["state"] == sg.STATE_PROBATION + assert "cluster_check_unavailable:empty_verdict" in st["blockers"] + + +def test_cluster_check_independent_verdict_still_allows_exit(): + conn = _db() + st = _run_to_eligible(conn, "fg-ok", "192.0.2.93", + lambda c, m: {"state": "too_small_to_judge", "members": len(m)}) + assert st["state"] == sg.STATE_TRUSTED + + +@pytest.mark.parametrize("seen", [None, "absent"]) +def test_missing_metrics_seen_requires_full_varied_metrics(seen): + st = {"metric_moves": {"clock_drift_cv": 99}} + if seen is None: + st["metrics_seen"] = None + assert sg.required_varied_metrics(st) == sg.PROBATION_MIN_VARIED_METRICS == 2 + assert len(sg.counted_varied_metrics(st)) < sg.required_varied_metrics(st) + + +def test_real_clock_only_metrics_seen_keeps_cobalt_qube_relaxation(): + st = {"metrics_seen": ["clock_drift_cv"], "metric_moves": {"clock_drift_cv": 99}} + assert sg.required_varied_metrics(st) == 1 + assert sg.counted_varied_metrics(st) == ["clock_drift_cv"] + + +def test_missing_metric_moves_counts_none(): + assert sg.counted_varied_metrics({}) == [] + assert sg.counted_varied_metrics({"metric_moves": None}) == [] + + +def test_null_metrics_seen_in_db_loads_as_missing_not_empty_list(): + conn = _db() + _attest(conn, "fg-null", _varying(0), "192.0.2.94", T0) + conn.execute("UPDATE miner_probation SET metrics_seen = 'garbage' WHERE miner = 'fg-null'") + st = sg.get_probation_status(conn, "fg-null") + assert st["metrics_seen"] is None + assert sg.required_varied_metrics(st) == 2 diff --git a/node/tests/sybil_guard/test_sybil_guard_probation_admin.py b/node/tests/sybil_guard/test_sybil_guard_probation_admin.py new file mode 100644 index 000000000..b9cd986b0 --- /dev/null +++ b/node/tests/sybil_guard/test_sybil_guard_probation_admin.py @@ -0,0 +1,143 @@ +# SPDX-License-Identifier: MIT +"""tools/probation_admin.py on a synthetic DB.""" +import sg_helpers # noqa: F401 (node/ on sys.path) +import importlib.util +import io +import json +import sqlite3 +from pathlib import Path + +import pytest + +import sybil_guard as sg + +TOOLS = Path(__file__).resolve().parents[3] / "tools" +spec = importlib.util.spec_from_file_location("probation_admin", TOOLS / "probation_admin.py") +pa = importlib.util.module_from_spec(spec) +spec.loader.exec_module(pa) + +PROTECTED = ("balances", "ledger", "epoch_enroll", "sybil_review_escrow", sg.INCIDENT_COHORT_TABLE) + + +def _row(c, miner, state, needs_review=0, review=None): + c.execute("INSERT INTO miner_probation (miner, state, reason, first_seen, last_seen, attest_count, " + "needs_review, review_reason, updated_at) VALUES (?, ?, 'r', 1790300000, 1790300500, 3, ?, ?, 1)", + (miner, state, needs_review, review)) + + +@pytest.fixture +def db(tmp_path): + path = tmp_path / "n.db" + c = sqlite3.connect(path) + c.executescript(f""" + CREATE TABLE miner_attest_history (id INTEGER PRIMARY KEY, miner TEXT, ts_ok INTEGER, fingerprint_passed INTEGER); + CREATE TABLE miner_fingerprint_history (id INTEGER PRIMARY KEY AUTOINCREMENT, miner TEXT, ts INTEGER, profile_json TEXT); + CREATE TABLE balances (miner_id TEXT PRIMARY KEY, amount_i64 INTEGER); + CREATE TABLE ledger (id INTEGER PRIMARY KEY, ts INTEGER, epoch INTEGER, miner_id TEXT, delta_i64 INTEGER, reason TEXT); + CREATE TABLE epoch_enroll (epoch INTEGER, miner_pk TEXT, weight INTEGER); + CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (miner TEXT PRIMARY KEY); + INSERT INTO balances VALUES ('held-new', 5), ('old-g4', 7); + INSERT INTO ledger VALUES (1, 1, 1, 'old-g4', 7, 'x'); + INSERT INTO epoch_enroll VALUES (297, 'held-new', 0), (297, 'old-g4', 0); + INSERT INTO {sg.INCIDENT_COHORT_TABLE} VALUES ('syb-1'); + INSERT INTO miner_attest_history (miner, ts_ok, fingerprint_passed) VALUES ('old-g4', {sg.GRANDFATHER_CUTOFF_TS - 86400}, 1); + """) + sg.init_schema(c) + _row(c, "held-new", sg.STATE_PROBATION, 1, sg.REVIEW_LIVE) + _row(c, "old-g4", sg.STATE_GRANDFATHERED, 1, sg.REVIEW_STORED) + _row(c, "syb-1", sg.STATE_ADMISSION_QUEUED, 1, sg.REVIEW_COHORT) + _row(c, "fine", sg.STATE_PROBATION) + _row(c, "grad", sg.STATE_TRUSTED) + sg.record_review_escrow(c, 297, "held-new", 1_000_000_000, "enroll", now=1) + sg.record_review_escrow(c, 298, "held-new", 1_000_000_000, "enroll", now=2) + c.commit() + c.close() + return path + + +def _dump(path, tables): + with sqlite3.connect(path) as c: + return {t: sorted(c.execute(f"SELECT * FROM {t}")) for t in tables} + + +def run(db, *argv): + buf = io.StringIO() + import contextlib + with contextlib.redirect_stdout(buf): + rc = pa.main(["--db", str(db), "--root", str(TOOLS.parent), *argv]) + return rc, buf.getvalue() + + +def test_list_shows_held_and_probation_with_escrow(db): + rows = pa.cmd_list(str(db), sg, out=io.StringIO()) + by = {r["miner"]: r for r in rows} + assert set(by) == {"held-new", "old-g4", "syb-1", "fine"} # trusted 'grad' not listed + assert by["held-new"]["escrow_units"] == 2_000_000_000 and by["held-new"]["escrow_epochs"] == 2 + assert by["syb-1"]["cohort"] is True and by["old-g4"]["needs_review"] is True + + +def test_show_reports_everything_read_only(db): + before = _dump(db, ("miner_probation",) + PROTECTED) + info = pa.cmd_show(str(db), sg, "old-g4", out=io.StringIO()) + assert info["pre_cutoff_history"] is True and info["probation_row"]["needs_review"] == 1 + assert _dump(db, ("miner_probation",) + PROTECTED) == before + + +def test_release_default_is_dry_run(db): + before = _dump(db, ("miner_probation",) + PROTECTED) + rc, out = run(db, "release", "held-new", "--reason", "checked") + assert rc == 0 and '"DRY_RUN": true' in out + assert _dump(db, ("miner_probation",) + PROTECTED) == before + with sqlite3.connect(db) as c: + assert not c.execute(f"SELECT 1 FROM sqlite_master WHERE name='{pa.AUDIT_TABLE}'").fetchone() + + +def test_release_grandfathered_and_audit(db): + protected = _dump(db, PROTECTED) + rc, out = run(db, "release", "old-g4", "--reason", "owner verified", "--operator", "scott", "--apply") + assert rc == 0 + with sqlite3.connect(db) as c: + st = sg._load(c, "old-g4") + audit = c.execute(f"SELECT operator, action, miner, reason, before_json, after_json FROM {pa.AUDIT_TABLE}").fetchall() + assert st["needs_review"] == 0 and st["state"] == sg.STATE_GRANDFATHERED + assert audit[0][:4] == ("scott", "release", "old-g4", "owner verified") + assert json.loads(audit[0][4])["needs_review"] == 1 and json.loads(audit[0][5])["needs_review"] == 0 + assert _dump(db, PROTECTED) == protected # never touches money tables + assert sg.enrollment_weight(2.5, st) == 2.5 + + +def test_release_new_miner_keeps_state_unless_trust(db): + run(db, "release", "held-new", "--reason", "r", "--apply") + with sqlite3.connect(db) as c: + st = sg._load(c, "held-new") + assert st["state"] == sg.STATE_PROBATION and st["needs_review"] == 0 + assert sg.enrollment_weight(2.5, st) == 1.0 + run(db, "release", "held-new", "--reason", "lab box", "--trust", "--apply") + with sqlite3.connect(db) as c: + assert sg._load(c, "held-new")["state"] == sg.STATE_TRUSTED + + +def test_cohort_member_refused_without_force_and_warned_with_it(db): + before = _dump(db, ("miner_probation",) + PROTECTED) + rc, out = run(db, "release", "syb-1", "--reason", "r", "--apply") + assert rc == 2 and "--force-cohort" in out + assert _dump(db, ("miner_probation",) + PROTECTED) == before + rc, out = run(db, "release", "syb-1", "--reason", "appeal upheld", "--force-cohort", "--apply") + assert rc == 0 and "settlement will KEEP holding" in out + with sqlite3.connect(db) as c: + assert c.execute(f"SELECT COUNT(*) FROM {sg.INCIDENT_COHORT_TABLE}").fetchone()[0] == 1 # not touched + assert c.execute(f"SELECT action FROM {pa.AUDIT_TABLE}").fetchone()[0] == "release+force_cohort" + # the settlement guard still holds it via the cohort table + assert sg.review_held_miners(c, ["syb-1"]) == {"syb-1"} + + +def test_release_requires_reason_and_known_miner(db): + rc, out = run(db, "release", "nobody", "--reason", "r", "--apply") + assert rc == 2 and "no miner_probation row" in out + rc, out = run(db, "release", "held-new", "--reason", " ", "--apply") + assert rc == 2 + + +def test_allowlist_guidance(db): + rc, out = run(db, "allowlist") + assert rc == 0 and sg.PROBATION_ALLOWLIST_ENV in out diff --git a/node/tests/sybil_guard/test_sybil_guard_settlement.py b/node/tests/sybil_guard/test_sybil_guard_settlement.py new file mode 100644 index 000000000..9ccbad853 --- /dev/null +++ b/node/tests/sybil_guard/test_sybil_guard_settlement.py @@ -0,0 +1,298 @@ +# SPDX-License-Identifier: MIT +"""Round-2: the review hold on EVERY settlement path, end to end. + +settle_epoch_rip200 (ADM preferred, standard fallback) is run for real against +a synthetic DB. The live snapshot is exercised in a subprocess +(tools/settle_probe.py) so the two module sets never share sys.modules. +""" +import json +import sqlite3 +import subprocess +import sys + +import pytest + +import sg_helpers # noqa: F401 (node/ on sys.path) +import anti_double_mining as adm +import rewards_implementation_rip200 as ri +import sybil_guard as sg +from sg_helpers import HERE, NODE_DIR, baseline_dir + +EPOCH = 290 +U = 1_000_000_000 # epoch weight units per 1.0x +POT = ri.PER_EPOCH_URTC # 1.5 RTC in uRTC + +HONEST_G4 = {"clock_drift_cv": 0.0123, "thermal_variance": 0.0, "jitter_cv": 0.0, "cache_hierarchy_ratio": 2.0} +HONEST_X86 = {"clock_drift_cv": 0.0812345, "thermal_variance": 0.98, "jitter_cv": 0.04, "cache_hierarchy_ratio": 1.013} + + +def _sybil_profile(i): + return {"clock_drift_cv": 0.02 + i / 1000, "thermal_variance": 3.1234, "jitter_cv": 0.1, + "cache_hierarchy_ratio": 2.5} + + +def make_db(path, miners, held=(), cohort=(), escrow_table=True): + """miners: [(id, arch, weight_units, profile)]""" + c = sqlite3.connect(path) + c.executescript( + """ + CREATE TABLE epoch_state (epoch INTEGER PRIMARY KEY, settled INTEGER DEFAULT 0, settled_ts INTEGER); + CREATE TABLE epoch_enroll (epoch INTEGER, miner_pk TEXT, weight INTEGER, PRIMARY KEY(epoch, miner_pk)); + CREATE TABLE miner_attest_recent (miner TEXT PRIMARY KEY, ts_ok INTEGER, device_family TEXT, + device_arch TEXT, entropy_score REAL DEFAULT 0, fingerprint_passed INTEGER DEFAULT 1, + fingerprint_checks_json TEXT, warthog_bonus REAL); + CREATE TABLE miner_fingerprint_history (id INTEGER PRIMARY KEY AUTOINCREMENT, miner TEXT, ts INTEGER, + profile_json TEXT); + CREATE TABLE miner_attest_history (id INTEGER PRIMARY KEY AUTOINCREMENT, miner TEXT, ts_ok INTEGER, + fingerprint_passed INTEGER); + CREATE TABLE balances (miner_id TEXT PRIMARY KEY, amount_i64 INTEGER DEFAULT 0); + CREATE TABLE ledger (id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER, epoch INTEGER, miner_id TEXT, + delta_i64 INTEGER, reason TEXT); + CREATE TABLE epoch_rewards (epoch INTEGER, miner_id TEXT, share_i64 INTEGER); + """ + ) + for m, arch, w, p in miners: + c.execute("INSERT INTO epoch_enroll VALUES (?,?,?)", (EPOCH, m, w)) + c.execute("INSERT INTO miner_attest_recent (miner, ts_ok, device_arch, fingerprint_passed, " + "fingerprint_checks_json) VALUES (?,?,?,1,'{}')", (m, 1, arch)) + c.execute("INSERT INTO miner_fingerprint_history (miner, ts, profile_json) VALUES (?,?,?)", + (m, 1, json.dumps(p))) + if escrow_table: + sg.init_schema(c) + for m in held: + c.execute("INSERT INTO miner_probation (miner, state, first_seen, last_seen, needs_review, " + "review_reason, updated_at) VALUES (?, 'probation', 1, 1, 1, 't', 1)", (m,)) + if cohort: + c.execute(f"CREATE TABLE {sg.INCIDENT_COHORT_TABLE} (miner_id TEXT PRIMARY KEY, source_ip TEXT)") + c.executemany(f"INSERT INTO {sg.INCIDENT_COHORT_TABLE} VALUES (?, 'x')", [(m,) for m in cohort]) + c.commit() + c.close() + + +def balances(path): + with sqlite3.connect(path) as c: + return dict(c.execute("SELECT miner_id, amount_i64 FROM balances")) + + +def escrow(path): + with sqlite3.connect(path) as c: + return sorted(c.execute("SELECT miner, would_be_weight_units, reason FROM sybil_review_escrow " + "WHERE epoch = ?", (EPOCH,)).fetchall()) + + +def settled(path): + with sqlite3.connect(path) as c: + row = c.execute("SELECT settled FROM epoch_state WHERE epoch=?", (EPOCH,)).fetchone() + return bool(row and row[0]) + + +@pytest.fixture +def base_miners(): + return [("honest-g4", "g4", 2 * U + U // 2, HONEST_G4), + ("honest-x86", "modern", U, HONEST_X86), + ("late-flag", "g4", U, _sybil_profile(0))] # probation-capped, flagged AFTER enrolling + + +@pytest.mark.parametrize("use_adm", [True, False]) +def test_settle_epoch_rip200_holds_post_enroll_flag(tmp_path, base_miners, use_adm): + db = str(tmp_path / "s.db") + make_db(db, base_miners, held=["late-flag"]) + res = ri.settle_epoch_rip200(db, EPOCH, enable_anti_double_mining=use_adm) + assert res["ok"] is True + assert ("anti_double_mining_telemetry" in res) is use_adm # the ADM path really ran + bal = balances(db) + assert "late-flag" not in bal + # exact payout arithmetic: pot split 2.5 : 1.0 between the honest miners + assert bal["honest-g4"] + bal["honest-x86"] == POT + assert abs(bal["honest-g4"] - POT * 2.5 / 3.5) <= 1 + assert escrow(db) == [("late-flag", U, "settlement_hold")] + assert settled(db) + + +@pytest.mark.parametrize("use_adm", [True, False]) +def test_cohort_membership_holds_without_probation_row(tmp_path, base_miners, use_adm): + db = str(tmp_path / "c.db") + make_db(db, base_miners, cohort=["late-flag"]) + ri.settle_epoch_rip200(db, EPOCH, enable_anti_double_mining=use_adm) + assert "late-flag" not in balances(db) + + +@pytest.mark.parametrize("use_adm", [True, False]) +def test_all_held_epoch_pays_nothing_and_stays_unsettled(tmp_path, use_adm): + db = str(tmp_path / "a.db") + miners = [(f"s{i}", "g4", U, _sybil_profile(i)) for i in range(3)] + make_db(db, miners, held=[m[0] for m in miners]) + res = ri.settle_epoch_rip200(db, EPOCH, enable_anti_double_mining=use_adm) + assert res["ok"] is False and res["error"] == "no_eligible_miners" + assert balances(db) == {} and not settled(db) + + +def test_adm_held_miner_cannot_displace_unheld_alias(tmp_path): + """Same machine identity (arch + profile): the held miner has the higher + enrolled weight, but the unheld alias must be the one paid.""" + db = str(tmp_path / "d.db") + make_db(db, [("honest-x86", "modern", U, HONEST_X86), + ("alias-honest", "g4", U, HONEST_G4), + ("alias-held", "g4", 2 * U, HONEST_G4)], held=["alias-held"]) + res = ri.settle_epoch_rip200(db, EPOCH, enable_anti_double_mining=True) + bal = balances(db) + assert "anti_double_mining_telemetry" in res + assert "alias-held" not in bal and bal["alias-honest"] > 0 + + +def test_rip200_index3_is_zeroed_not_fingerprint(tmp_path, base_miners, monkeypatch): + """Astra: the round-1 guard overwrote tuple index 2 (fingerprint_passed). + A held miner must reach the weight step with fingerprint_ok intact and + enrolled_weight == 0 (so the arch fallback cannot re-weight it).""" + import rip_200_round_robin_1cpu1vote as rr + db = str(tmp_path / "r.db") + make_db(db, base_miners, held=["late-flag"]) + seen = {} + real = rr._distribute_reward_by_weight + + def spy(weighted, total): + seen.update(dict(weighted)) + return real(weighted, total) + + monkeypatch.setattr(rr, "_distribute_reward_by_weight", spy) + out = rr.calculate_epoch_rewards_time_aged(db, EPOCH, POT, EPOCH * 144) + assert seen["late-flag"] == 0 and "late-flag" not in out + assert seen["honest-g4"] == 2 * U + U // 2 + + +def test_hold_is_read_inside_the_settlement_write_lock(tmp_path, base_miners, monkeypatch): + """The hold lookup runs while settle_epoch_rip200 holds BEGIN IMMEDIATE; a + concurrent writer trying to flag a miner at that moment is locked out, so + no hold can land between the read and the credits.""" + db = str(tmp_path / "l.db") + make_db(db, base_miners) + observed = {} + real = sg.settlement_held_miners + + def wrapped(conn, miners, epoch=None): + observed["in_txn"] = conn.in_transaction + other = sqlite3.connect(db, timeout=0) + try: + other.execute("UPDATE miner_probation SET needs_review = 1") + other.commit() + observed["other_write"] = "succeeded" + except sqlite3.OperationalError as exc: + observed["other_write"] = str(exc) + finally: + other.close() + return real(conn, miners, epoch) + + monkeypatch.setattr(sg, "settlement_held_miners", wrapped) + ri.settle_epoch_rip200(db, EPOCH, enable_anti_double_mining=True) + assert observed["in_txn"] is True + assert "locked" in observed["other_write"] + + +def test_adm_weight_read_error_does_not_fail_open(tmp_path, base_miners): + """Round 1 finding: ADM swallowed sqlite errors reading epoch weights and + fell back to ARCH multipliers (2.5x for a held G4). Now it propagates.""" + db = str(tmp_path / "e.db") + make_db(db, base_miners) + + class Boom: + def __init__(self, conn): + self.conn = conn + + def execute(self, sql, *a): + if "SELECT miner_pk, weight FROM epoch_enroll" in sql: + raise sqlite3.OperationalError("disk I/O error") + return self.conn.execute(sql, *a) + + with sqlite3.connect(db) as c: + with pytest.raises(sqlite3.OperationalError): + adm._get_epoch_enrolled_weights(Boom(c), EPOCH) + + +def test_broken_probation_table_never_halts_settlement(tmp_path, base_miners): + """Incompatible miner_probation (e.g. hand-made) -> the lookup falls back to + escrow rows, logs CRITICAL, and settlement still completes.""" + db = str(tmp_path / "b.db") + make_db(db, base_miners) + with sqlite3.connect(db) as c: + c.execute("DROP TABLE miner_probation") + c.execute("CREATE TABLE miner_probation (miner TEXT)") # no needs_review column + c.execute("INSERT INTO sybil_review_escrow VALUES (?, 'late-flag', 5, 'enroll', 1)", (EPOCH,)) + res = ri.settle_epoch_rip200(db, EPOCH, enable_anti_double_mining=True) + assert res["ok"] is True and settled(db) + assert "late-flag" not in balances(db) # held via the escrow-row fallback + + +def test_no_probation_table_means_no_holds_but_settles(tmp_path, base_miners): + db = str(tmp_path / "n.db") + # g5 so ADM does not group it with honest-g4 as one machine + miners = base_miners[:2] + [("late-flag", "g5", U, _sybil_profile(0))] + make_db(db, miners, escrow_table=False) + res = ri.settle_epoch_rip200(db, EPOCH, enable_anti_double_mining=True) + assert res["ok"] is True and balances(db)["late-flag"] > 0 + + +def _probe(src, db, adm_flag): + out = subprocess.run([sys.executable, str(HERE / "settle_probe.py"), str(src), db, + str(EPOCH), "1" if adm_flag else "0"], capture_output=True, text=True, timeout=120) + assert out.returncode == 0, out.stderr[-2000:] + return json.loads(out.stdout.strip().splitlines()[-1]) + + +@pytest.mark.parametrize("src", ["live", "patched"]) +@pytest.mark.parametrize("use_adm", [True, False]) +def test_epoch296_style_zeroed_rows_pay_zero(tmp_path, src, use_adm): + """Tonight's containment (83 rows set to weight 0) on BOTH the unpatched + production code and the patch, ADM and standard paths.""" + db = str(tmp_path / f"z_{src}_{use_adm}.db") + miners = [("honest-g4", "g4", 2 * U + U // 2, HONEST_G4), ("honest-x86", "modern", U, HONEST_X86)] + miners += [(f"sybil-{i}", "g4", 0, _sybil_profile(i)) for i in range(3)] + make_db(db, miners, escrow_table=(src == "patched")) + if src == "live" and baseline_dir() is None: + pytest.skip("pre-patch baseline not available from git") + got = _probe(baseline_dir() if src == "live" else NODE_DIR, db, use_adm) + assert got["ok"] is True and got["adm"] is use_adm + assert set(got["balances"]) == {"honest-g4", "honest-x86"} + assert sum(got["balances"].values()) == POT + + +def test_escrow_weight_read_error_does_not_abort_adm_settlement(tmp_path, base_miners, monkeypatch): + """GLM round 2: the escrow-weight read inside the hold must be fail-SAFE. + First call to _get_epoch_enrolled_weights is the hold's escrow lookup.""" + db = str(tmp_path / "ew.db") + make_db(db, base_miners, held=["late-flag"]) + real = adm._get_epoch_enrolled_weights + calls = {"n": 0} + + def flaky(conn, epoch): + calls["n"] += 1 + if calls["n"] == 1: + raise sqlite3.OperationalError("database is locked") + return real(conn, epoch) + + monkeypatch.setattr(adm, "_get_epoch_enrolled_weights", flaky) + res = ri.settle_epoch_rip200(db, EPOCH, enable_anti_double_mining=True) + assert res["ok"] is True and "anti_double_mining_telemetry" in res + assert "late-flag" not in balances(db) # hold still applied + assert escrow(db) == [] # only the escrow record was skipped + + +@pytest.mark.parametrize("require_adm", [False, True]) +def test_payout_weight_read_error_stays_fail_loud(tmp_path, base_miners, monkeypatch, require_adm): + """The payout weights are NOT fail-safe: ADM aborts. Without RC_REQUIRE_ADM + the existing fallback settles via the standard path (still holding); + with it, the epoch stays unsettled.""" + db = str(tmp_path / f"pw{require_adm}.db") + make_db(db, base_miners, held=["late-flag"]) + + def always(conn, epoch): + raise sqlite3.OperationalError("disk I/O error") + + monkeypatch.setattr(adm, "_get_epoch_enrolled_weights", always) + if require_adm: + monkeypatch.setenv("RC_REQUIRE_ADM", "1") + res = ri.settle_epoch_rip200(db, EPOCH, enable_anti_double_mining=True) + if require_adm: + assert res["ok"] is False and res["error"] == "adm_required_failed" and not settled(db) + else: + assert res["ok"] is True and "anti_double_mining_telemetry" not in res + assert "late-flag" not in balances(db) and escrow(db) == [("late-flag", U, "settlement_hold")] diff --git a/node/tests/sybil_guard/test_sybil_guard_welcome_bonus_mirror.py b/node/tests/sybil_guard/test_sybil_guard_welcome_bonus_mirror.py new file mode 100644 index 000000000..ff0934e61 --- /dev/null +++ b/node/tests/sybil_guard/test_sybil_guard_welcome_bonus_mirror.py @@ -0,0 +1,164 @@ +# SPDX-License-Identifier: MIT +"""PR #8491 port: the welcome bonus must move the UTXO mirror, not only balances. + +Same scenario as the upstream PR tests (founder_community fully mirrored, pay +bonuses, check mirror <= balance), run against BOTH the patched node and the +live snapshot so the test proves the fix is what closes the gap. +""" +import sqlite3 +import time + +import pytest + +from sg_helpers import NODE_DIR, baseline_dir, load_node + +SOURCE = "founder_community" +BONUS_URTC = 500_000 +NRTC_PER_URTC = 100 +SOURCE_START_URTC = 20_000_000 + + +@pytest.fixture(scope="module") +def nodes(tmp_path_factory): + d = tmp_path_factory.mktemp("mirror_load") + out = {"patched": load_node(d / "p.db", "mirror_patched", NODE_DIR)} + if baseline_dir() is not None: + out["live"] = load_node(d / "l.db", "mirror_live", baseline_dir()) + return out + + +def _setup(node, db): + from utxo_db import UtxoDB + node.DB_PATH = str(db) + node.UTXO_DUAL_WRITE = True + UtxoDB(str(db)).init_tables() + now = int(time.time()) + with sqlite3.connect(db) as c: + c.executescript( + """ + CREATE TABLE IF NOT EXISTS balances (miner_id TEXT PRIMARY KEY, miner_pk TEXT, + amount_i64 INTEGER DEFAULT 0, balance_rtc REAL DEFAULT 0); + CREATE TABLE IF NOT EXISTS ledger (id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, + epoch INTEGER, miner_id TEXT NOT NULL, delta_i64 INTEGER NOT NULL, reason TEXT); + CREATE TABLE IF NOT EXISTS account_mirror_boxes (box_id TEXT PRIMARY KEY, + account_wallet TEXT NOT NULL, value_nrtc INTEGER NOT NULL, created_epoch INTEGER); + """ + ) + c.execute("INSERT INTO balances (miner_id, amount_i64) VALUES (?, ?)", (SOURCE, SOURCE_START_URTC)) + c.execute("INSERT INTO utxo_transactions (tx_id, tx_type, inputs_json, outputs_json, timestamp, " + "block_height) VALUES ('genesistx', 'genesis', '[]', '[]', ?, 0)", (now,)) + c.execute("INSERT INTO utxo_boxes (box_id, value_nrtc, proposition, owner_address, creation_height, " + "transaction_id, output_index, created_at) VALUES ('genesisbox', ?, 'p', ?, 0, 'genesistx', 0, ?)", + (SOURCE_START_URTC * NRTC_PER_URTC, SOURCE, now)) + c.execute("INSERT INTO account_mirror_boxes VALUES ('genesisbox', ?, ?, 0)", + (SOURCE, SOURCE_START_URTC * NRTC_PER_URTC)) + c.commit() + + +def _persist(db, miner, state="trusted"): + """Round 3: the bonus is authorised from the PERSISTED probation row.""" + import sybil_guard as sg + with sqlite3.connect(db) as c: + sg.init_schema(c) + c.execute("INSERT OR REPLACE INTO miner_probation (miner, state, first_seen, last_seen, updated_at) " + "VALUES (?, ?, 1, 1, 1)", (miner, state)) + c.commit() + + +def _mirror(c, w): + return int(c.execute("SELECT COALESCE(SUM(b.value_nrtc),0) FROM utxo_boxes b JOIN account_mirror_boxes m " + "ON m.box_id=b.box_id WHERE m.account_wallet=? AND b.spent_at IS NULL", (w,)).fetchone()[0]) + + +def _balance(c, w): + r = c.execute("SELECT amount_i64 FROM balances WHERE miner_id=?", (w,)).fetchone() + return int(r[0]) * NRTC_PER_URTC if r and r[0] is not None else 0 + + +def _pay(node, db, miner): + with sqlite3.connect(db) as conn: + conn.execute("BEGIN IMMEDIATE") + node._write_welcome_bonus(conn, miner, BONUS_URTC, node._table_columns(conn, "ledger"), + node._table_columns(conn, "balances")) + conn.commit() + + +def test_patched_bonuses_keep_mirror_in_sync(nodes, tmp_path): + node, db = nodes["patched"], tmp_path / "p.db" + _setup(node, db) + for i in range(5): + _pay(node, db, f"miner-{i}") + with sqlite3.connect(db) as c: + assert _mirror(c, SOURCE) - _balance(c, SOURCE) == 0 + for i in range(5): + assert _mirror(c, f"miner-{i}") == _balance(c, f"miner-{i}") == BONUS_URTC * NRTC_PER_URTC + assert _balance(c, SOURCE) == (SOURCE_START_URTC - 5 * BONUS_URTC) * NRTC_PER_URTC + + +def test_live_snapshot_drifts_by_one_bonus_per_miner(nodes, tmp_path): + """Documents the production bug the port fixes (mirror > balance).""" + if "live" not in nodes: + pytest.skip("pre-patch baseline not available from git") + node, db = nodes["live"], tmp_path / "l.db" + _setup(node, db) + for i in range(5): + _pay(node, db, f"miner-{i}") + with sqlite3.connect(db) as c: + assert _mirror(c, SOURCE) - _balance(c, SOURCE) == 5 * BONUS_URTC * NRTC_PER_URTC + + +def test_graduation_bonus_path_keeps_mirror_in_sync(nodes, tmp_path): + """The new _check_welcome_bonus (paid at probation exit) goes through the same writer.""" + node, db = nodes["patched"], tmp_path / "g.db" + _setup(node, db) + _persist(db, "graduate") + assert node._check_welcome_bonus("graduate", {"state": "trusted"}) is True + with sqlite3.connect(db) as c: + assert _mirror(c, SOURCE) == _balance(c, SOURCE) + assert _mirror(c, "graduate") == _balance(c, "graduate") == BONUS_URTC * NRTC_PER_URTC + + +def test_non_mirrored_payer_is_tolerated(nodes, tmp_path): + node, db = nodes["patched"], tmp_path / "n.db" + _setup(node, db) + with sqlite3.connect(db) as c: + c.execute("DELETE FROM account_mirror_boxes") + c.execute("UPDATE utxo_boxes SET spent_at = 1 WHERE box_id='genesisbox'") + c.commit() + _pay(node, db, "m") + with sqlite3.connect(db) as c: + assert _balance(c, "m") == BONUS_URTC * NRTC_PER_URTC + + +def test_mirror_failure_rolls_back_whole_bonus_and_stays_retryable(nodes, tmp_path): + """Round 2 (Codex/Astra/Grok): founder_community mirror > balance (the + live node1 state) makes the reconciler raise mirror_exceeds_balance. The + bonus must NOT be paid, nothing half-written may commit, and once the gap + is repaired the next attempt pays exactly once.""" + node, db = nodes["patched"], tmp_path / "x.db" + _setup(node, db) + now = int(time.time()) + with sqlite3.connect(db) as c: # inject a 1 RTC mirror excess on the payer + c.execute("INSERT INTO utxo_boxes (box_id, value_nrtc, proposition, owner_address, creation_height, " + "transaction_id, output_index, created_at) VALUES ('excess', ?, 'p', ?, 0, 'genesistx', 1, ?)", + (100_000_000, SOURCE, now)) + c.execute("INSERT INTO account_mirror_boxes VALUES ('excess', ?, ?, 0)", (SOURCE, 100_000_000)) + c.commit() + before = (_balance(c, SOURCE), c.execute("SELECT COUNT(*) FROM ledger").fetchone()[0], + c.execute("SELECT COUNT(*) FROM utxo_boxes WHERE spent_at IS NULL").fetchone()[0]) + assert node._check_welcome_bonus("grad", {"state": "trusted"}) is False # no persisted row: withheld + _persist(db, "grad") + assert node._check_welcome_bonus("grad", {"state": "trusted"}) is False + with sqlite3.connect(db) as c: + after = (_balance(c, SOURCE), c.execute("SELECT COUNT(*) FROM ledger").fetchone()[0], + c.execute("SELECT COUNT(*) FROM utxo_boxes WHERE spent_at IS NULL").fetchone()[0]) + assert after == before # nothing committed + assert _balance(c, "grad") == 0 + c.execute("DELETE FROM account_mirror_boxes WHERE box_id='excess'") # operator repairs gap + c.execute("DELETE FROM utxo_boxes WHERE box_id='excess'") + c.commit() + assert node._check_welcome_bonus("grad", {"state": "trusted"}) is True # retried, paid + assert node._check_welcome_bonus("grad", {"state": "trusted"}) is False # exactly once + with sqlite3.connect(db) as c: + assert _mirror(c, SOURCE) == _balance(c, SOURCE) + assert _balance(c, "grad") == BONUS_URTC * NRTC_PER_URTC diff --git a/node/tests/test_anti_double_mining.py b/node/tests/test_anti_double_mining.py index 3462dc7d3..53f418152 100644 --- a/node/tests/test_anti_double_mining.py +++ b/node/tests/test_anti_double_mining.py @@ -190,6 +190,19 @@ def test_detect_same_machine_multiple_miners(self): VALUES (?, ?, ?) """, (miner, current_ts, fingerprint)) + # Machine identity = shared MAC hash + same node-observed source_ip + + # same arch (the fingerprint profile above is not an identity signal). + self.conn.execute("ALTER TABLE miner_attest_recent ADD COLUMN source_ip TEXT") + self.conn.execute( + "CREATE TABLE miner_macs (miner TEXT NOT NULL, mac_hash TEXT NOT NULL, " + "first_ts INTEGER NOT NULL, last_ts INTEGER NOT NULL, count INTEGER DEFAULT 1, " + "PRIMARY KEY (miner, mac_hash))" + ) + for miner in miners: + self.conn.execute("UPDATE miner_attest_recent SET source_ip = ? WHERE miner = ?", + ("192.0.2.10", miner)) + self.conn.execute("INSERT INTO miner_macs VALUES (?, ?, ?, ?, 1)", + (miner, "mac-same-machine", epoch_start_ts + 60, epoch_start_ts + 60)) self.conn.commit() duplicates = detect_duplicate_identities( diff --git a/node/tests/test_anti_double_mining_epoch_enroll.py b/node/tests/test_anti_double_mining_epoch_enroll.py index 23abb23e7..1fdda41cc 100644 --- a/node/tests/test_anti_double_mining_epoch_enroll.py +++ b/node/tests/test_anti_double_mining_epoch_enroll.py @@ -10,7 +10,12 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -from anti_double_mining import detect_duplicate_identities, get_epoch_miner_groups +from anti_double_mining import ( + BLOCK_TIME, + GENESIS_TIMESTAMP, + detect_duplicate_identities, + get_epoch_miner_groups, +) def _conn(): @@ -28,6 +33,26 @@ def _conn(): return conn +def _machine_evidence(conn, epoch, evidence): + """Record node-observed machine evidence: {miner: (source_ip, mac_hash)}. + + ADM identifies one physical machine by a shared MAC hash seen in the + epoch window AND the same server-observed source_ip AND the same arch. + The fingerprint profile is NOT an identity (the node stores a flat + 4-metric profile there, which made every miner hash to its arch). + """ + ts = GENESIS_TIMESTAMP + epoch * 144 * BLOCK_TIME + 60 + conn.execute("ALTER TABLE miner_attest_recent ADD COLUMN source_ip TEXT") + conn.execute( + "CREATE TABLE miner_macs (miner TEXT NOT NULL, mac_hash TEXT NOT NULL, " + "first_ts INTEGER NOT NULL, last_ts INTEGER NOT NULL, count INTEGER DEFAULT 1, " + "PRIMARY KEY (miner, mac_hash))" + ) + for miner, (ip, mac) in evidence.items(): + conn.execute("UPDATE miner_attest_recent SET source_ip=? WHERE miner=?", (ip, miner)) + conn.execute("INSERT INTO miner_macs VALUES (?, ?, ?, ?, 1)", (miner, mac, ts, ts)) + + def _profile(serial): return json.dumps({"checks": {"cpu_serial": {"data": {"serial": serial}}}}) @@ -44,6 +69,8 @@ def test_detect_duplicates_prefers_epoch_enroll_when_attestation_is_stale(): "INSERT INTO miner_fingerprint_history (miner, ts, profile_json) VALUES (?, ?, ?)", (miner, 99, _profile("same-machine")), ) + _machine_evidence(conn, 7, {"miner-a": ("192.0.2.10", "mac-same"), + "miner-b": ("192.0.2.10", "mac-same")}) conn.commit() duplicates = detect_duplicate_identities(conn, 7, epoch_start_ts=1000, epoch_end_ts=2000) @@ -69,6 +96,9 @@ def test_get_epoch_miner_groups_uses_epoch_enroll_for_stale_attestations(): "INSERT INTO miner_fingerprint_history (miner, ts, profile_json) VALUES (?, ?, ?)", (miner, 99, _profile(serial)), ) + _machine_evidence(conn, 3, {"miner-a": ("192.0.2.10", "mac-same"), + "miner-b": ("192.0.2.10", "mac-same"), + "miner-c": ("192.0.2.10", "mac-other")}) conn.commit() groups = get_epoch_miner_groups(conn, 3) diff --git a/node/tests/test_beacon_resolver_status.py b/node/tests/test_beacon_resolver_status.py index 826f0581f..71ea78b44 100644 --- a/node/tests/test_beacon_resolver_status.py +++ b/node/tests/test_beacon_resolver_status.py @@ -96,3 +96,32 @@ def test_resolve_bcn_wallet_reports_inactive_status(): result = module.resolve_bcn_wallet("bcn_inactive") assert result == {"found": False, "error": "beacon_agent_status:suspended"} + + +def _atlas_with(atlas_path, rows): + with sqlite3.connect(atlas_path) as conn: + conn.execute( + "CREATE TABLE relay_agents (agent_id TEXT PRIMARY KEY, pubkey_hex TEXT NOT NULL, " + "name TEXT NOT NULL, status TEXT)" + ) + conn.executemany( + "INSERT INTO relay_agents(agent_id, pubkey_hex, name, status) VALUES (?, ?, ?, ?)", rows + ) + + +def test_resolve_bcn_wallet_accepts_heartbeat_statuses_and_refuses_barred(): + """/relay/heartbeat sets "alive" or "degraded". Those agents must stay payable; + only administrator-barred statuses are refused (same set as beacon_api).""" + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdir: + module = load_integrated_node(Path(tmpdir) / "node.db") + atlas = Path(tmpdir) / "atlas.db" + module.BEACON_ATLAS_DB = str(atlas) + statuses = ["active", "alive", "degraded", None, "banned", "suspended", "revoked"] + _atlas_with(atlas, [(f"bcn_s{i}", f"{i:02x}" * 32, f"agent {i}", s) for i, s in enumerate(statuses)]) + + results = {s: module.resolve_bcn_wallet(f"bcn_s{i}") for i, s in enumerate(statuses)} + + for ok in ("active", "alive", "degraded", None): + assert results[ok]["found"] is True, (ok, results[ok]) + for barred in ("banned", "suspended", "revoked"): + assert results[barred] == {"found": False, "error": f"beacon_agent_status:{barred}"} diff --git a/node/tests/test_bridge_reconciliation.py b/node/tests/test_bridge_reconciliation.py index e52a9fa14..038e58ef2 100644 --- a/node/tests/test_bridge_reconciliation.py +++ b/node/tests/test_bridge_reconciliation.py @@ -157,7 +157,7 @@ def test_snapshot_is_idempotent_on_epoch(db_path): def test_snapshot_bridged_supply_committed_formula(db_path): # locked = 10 + 20 = 30; completed = 50; voided = 3 - # bridged_supply_committed = 30 + 50 - 3 = 77 + # bridged_supply_committed = 30 + 50 = 80 (voided is already excluded from locked_in) _seed_transfer(db_path, status="pending", amount_rtc=10.0) _seed_transfer(db_path, status="locked", amount_rtc=20.0, id_suffix=1) _seed_transfer(db_path, status="completed", amount_rtc=50.0, id_suffix=2) @@ -167,7 +167,7 @@ def test_snapshot_bridged_supply_committed_formula(db_path): assert snap["locked_in_rtc"] == 30.0 assert snap["completed_in_rtc"] == 50.0 assert snap["voided_in_rtc"] == 3.0 - assert snap["bridged_supply_committed"] == pytest.approx(77.0) + assert snap["bridged_supply_committed"] == pytest.approx(80.0) def test_snapshot_uses_provided_aggregate_state(db_path): @@ -186,7 +186,7 @@ def test_snapshot_uses_provided_aggregate_state(db_path): assert snap["locked_in_rtc"] == 1.0 assert snap["completed_in_rtc"] == 2.0 assert snap["voided_in_rtc"] == 0.5 - assert snap["bridged_supply_committed"] == pytest.approx(2.5) + assert snap["bridged_supply_committed"] == pytest.approx(3.0) # ---------- routes ---------------------------------------------------------- diff --git a/node/tests/test_dual_write_shadow_balance.py b/node/tests/test_dual_write_shadow_balance.py index 64a5c5182..9cd7453f5 100644 --- a/node/tests/test_dual_write_shadow_balance.py +++ b/node/tests/test_dual_write_shadow_balance.py @@ -213,7 +213,11 @@ def test_dual_write_exact_balance_goes_to_zero(self): sender = 'RTC_test_aabbccdd' recipient = 'RTC' + 'e' * 40 # canonical form; recipients are format-checked since #2819 - self._seed_coinbase(sender, 100 * UNIT) + # Consistent dual-write state: the sender's UTXO value equals its account + # balance. (With 100 RTC of UTXO against a 10 RTC account, the 90 RTC + # change output is registered as an account mirror and the + # MIRROR_EXCEEDS_BALANCE guard correctly fails closed.) + self._seed_coinbase(sender, 10 * UNIT) conn = sqlite3.connect(self.db_path) conn.execute( @@ -389,6 +393,19 @@ def test_rejects_arbitrary_string_recipient(self): self.assertEqual(resp.get_json()['error'], 'invalid_to_address_format', bad) self.assertEqual(self.utxo_db.get_balance('not-a-wallet') if hasattr(self.utxo_db, 'get_balance') else 0, 0) + def test_rejects_non_canonical_case_recipient(self): + """#2819 (Ondrej Nad): derivation yields lower-case hex, and ownership is + matched case-sensitively, so an upper/mixed-case recipient would create a + box no key can ever spend. It must be rejected before any state change.""" + canonical = 'RTC' + 'abcdef0123' * 4 + for bad in ('RTC' + 'Abcdef0123' * 4, 'RTC' + 'ABCDEF0123' * 4, + canonical[:-1] + 'F'): + resp = self._post(bad) + self.assertEqual(resp.status_code, 400, bad) + self.assertEqual(resp.get_json()['error'], 'invalid_to_address_format', bad) + resp = self._post(canonical) + self.assertNotEqual((resp.get_json() or {}).get('error'), 'invalid_to_address_format') + def test_canonical_recipient_passes_format_check(self): resp = self._post('RTC' + 'c' * 40) # Anything but the format error: the request proceeds to the normal path. diff --git a/node/tests/test_enroll_weight_device_spoof.py b/node/tests/test_enroll_weight_device_spoof.py index 4bac80b43..220453df6 100644 --- a/node/tests/test_enroll_weight_device_spoof.py +++ b/node/tests/test_enroll_weight_device_spoof.py @@ -257,6 +257,15 @@ def test_legacy_miner_without_verified_device_falls_back_to_body(self): miner = "RTC_LEGACY" miner_id = "miner_legacy_1" + # sybil_guard: a legacy miner is one that attested before the probation + # cutoff (grandfathered, today's weight rules). A brand-new identity + # would instead be capped at 1.0 while in probation. + with sqlite3.connect(db_path) as conn: + conn.execute( + "INSERT INTO miner_attest_history (miner, ts_ok, fingerprint_passed) VALUES (?, ?, 1)", + (miner, mod.sybil_guard.GRANDFATHER_CUTOFF_TS - 86400), + ) + conn.commit() signing_key = self._attest(mod, miner, miner_id) # Simulate a legacy/pre-migration attestation row: no verified device. self._set_verified_device(db_path, miner, None, None) diff --git a/node/tests/test_ergo_miner_anchor_auditability.py b/node/tests/test_ergo_miner_anchor_auditability.py new file mode 100644 index 000000000..3fed0b7ed --- /dev/null +++ b/node/tests/test_ergo_miner_anchor_auditability.py @@ -0,0 +1,91 @@ +# SPDX-License-Identifier: MIT +"""ergo_miner_anchor: no wallet password in source, and every anchor stores the +exact preimage of its commitment so an outside auditor can recompute it.""" +import importlib.util +import json +import os +import sys +import types +import unittest +from hashlib import blake2b +from pathlib import Path + +NODE = Path(__file__).resolve().parents[1] +SRC = NODE / "ergo_miner_anchor.py" + + +def _load(): + # beacon_anchor is imported at module load; the pure functions under test + # don't need it, so stub it if its deps are unavailable. + sys.path.insert(0, str(NODE)) + if "beacon_anchor" not in sys.modules: + try: + import beacon_anchor # noqa: F401 + except Exception: + stub = types.ModuleType("beacon_anchor") + stub.compute_beacon_digest = lambda *_a, **_k: {"count": 0, "ids": []} + stub.mark_anchored = lambda *_a, **_k: None + stub.init_beacon_table = lambda *_a, **_k: None + sys.modules["beacon_anchor"] = stub + spec = importlib.util.spec_from_file_location("ergo_miner_anchor_under_test", SRC) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + return mod + + +class ErgoMinerAnchorAuditabilityTest(unittest.TestCase): + def test_no_hardcoded_wallet_password(self): + src = SRC.read_text(encoding="utf-8") + self.assertNotIn("rustchain123", src) + mod = _load() + import inspect + self.assertIsNone(inspect.signature(mod.ErgoMinerAnchor.unlock_wallet) + .parameters["password"].default) + + def test_locked_wallet_without_password_does_not_post_unlock(self): + mod = _load() + posts = [] + + class _Resp: + def json(self): + return {"isUnlocked": False} + + class _Session: + headers = {} + + def get(self, *_a, **_k): + return _Resp() + + def post(self, *a, **k): + posts.append((a, k)) + + a = mod.ErgoMinerAnchor.__new__(mod.ErgoMinerAnchor) + a.session = _Session() + old = mod.ERGO_WALLET_PASS + mod.ERGO_WALLET_PASS = "" + try: + a.unlock_wallet() + finally: + mod.ERGO_WALLET_PASS = old + self.assertEqual(posts, [], "must not POST an empty/default password") + + def test_stored_miner_data_recomputes_the_commitment(self): + mod = _load() + a = mod.ErgoMinerAnchor.__new__(mod.ErgoMinerAnchor) + miners = [{"miner": "RTC" + "ab" * 20, "device_arch": "g4", "ts_ok": 1758300000}, + {"miner": "dual-g4-125", "device_arch": "g4", "ts_ok": 1758290000}] + stored = a.canonical_miner_data(miners) # what goes in ergo_anchors.miner_data + commitment = a.compute_commitment(miners) + # An auditor with only the stored row can recompute it: + self.assertEqual(blake2b(stored.encode(), digest_size=32).hexdigest(), commitment) + self.assertEqual(json.loads(stored), miners) + combined = a.compute_combined_commitment(commitment, {"digest": "d" * 64}) + self.assertEqual(combined, blake2b(f"{commitment}|{'d' * 64}".encode(), digest_size=32).hexdigest()) + + def test_insert_persists_miner_data(self): + src = SRC.read_text(encoding="utf-8") + self.assertIn("miner_data", src.split("INSERT INTO ergo_anchors", 1)[1][:200]) + + +if __name__ == "__main__": + unittest.main() diff --git a/node/tests/test_finalize_epoch_dualwrite_precision.py b/node/tests/test_finalize_epoch_dualwrite_precision.py new file mode 100644 index 000000000..336b0f96b --- /dev/null +++ b/node/tests/test_finalize_epoch_dualwrite_precision.py @@ -0,0 +1,112 @@ +# SPDX-License-Identifier: MIT +"""End-to-end: under UTXO dual-write, finalize_epoch must mint UTXO reward boxes +that EXACTLY mirror the account-model credit. + +#2819 (favoritegrandson-tech): the account credit truncated the share to 6 +decimals (uRTC) while the UTXO mint truncated the same Decimal to 8 decimals +(nRTC), so each reward box could be up to 99 nRTC larger than the credit and +/utxo/integrity reported the models disagreeing after every settlement with +fractional shares. Separately, a miner with no balance row got no account +credit (no-phantom invariant) but still received a UTXO mint. +""" +import importlib.util +import os +import sqlite3 +import tempfile +import unittest +from pathlib import Path + +MODULE_PATH = Path(__file__).resolve().parents[1] / "rustchain_v2_integrated_v2.2.1_rip200.py" + + +class FinalizeEpochDualWritePrecisionTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._saved_env = {k: os.environ.get(k) for k in + ("RUSTCHAIN_DB_PATH", "RC_ADMIN_KEY", "RUSTCHAIN_DISABLE_P2P_AUTO_START")} + cls._tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + cls._db = os.path.join(cls._tmp.name, "dwprec.db") + os.environ["RUSTCHAIN_DB_PATH"] = cls._db + os.environ.setdefault("RC_ADMIN_KEY", "0123456789abcdef0123456789abcdef") + os.environ["RUSTCHAIN_DISABLE_P2P_AUTO_START"] = "1" + spec = importlib.util.spec_from_file_location("rcnode_dwprec_test", MODULE_PATH) + cls.mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(cls.mod) + cls.mod.init_db() + with sqlite3.connect(cls._db) as c: # production (miner_id, amount_i64) shape + c.execute("DROP TABLE IF EXISTS balances") + c.execute("CREATE TABLE balances (miner_id TEXT PRIMARY KEY, " + "amount_i64 INTEGER NOT NULL DEFAULT 0 CHECK(amount_i64>=0), " + "balance_rtc REAL DEFAULT 0)") + c.commit() + from utxo_db import UtxoDB + UtxoDB(cls._db).init_tables() + cls._orig_dual_write = cls.mod.UTXO_DUAL_WRITE + cls.mod.UTXO_DUAL_WRITE = True + + @classmethod + def tearDownClass(cls): + cls.mod.UTXO_DUAL_WRITE = cls._orig_dual_write + # Don't leak this suite's env into later tests in the same process. + for k, v in cls._saved_env.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + cls._tmp.cleanup() + + def _enroll(self, epoch, pk, weight, with_balance_row=True): + with sqlite3.connect(self._db) as c: + c.execute("INSERT OR REPLACE INTO epoch_enroll (epoch, miner_pk, weight) VALUES (?, ?, ?)", + (epoch, pk, weight)) + if with_balance_row: + c.execute("INSERT OR IGNORE INTO balances (miner_id, amount_i64) VALUES (?, 0)", (pk,)) + c.commit() + + def _utxo_total(self, c, owner): + return c.execute("SELECT COALESCE(SUM(value_nrtc), 0) FROM utxo_boxes " + "WHERE owner_address = ? AND spent_at IS NULL", (owner,)).fetchone()[0] + + def test_reward_box_equals_account_credit_exactly(self): + epoch = 6101 + # Co-prime weights => shares with non-terminating decimals, where 6dp and + # 8dp truncation of the same Decimal disagree. + miners = [("prec-a", 7), ("prec-b", 11), ("prec-c", 13)] + for pk, w in miners: + self._enroll(epoch, pk, self.mod.epoch_weight_to_units(w)) + + self.mod.finalize_epoch(epoch, per_block_rtc=self.mod.PER_BLOCK_RTC, prev_block_hash=b"") + + ratio = self.mod.UTXO_UNIT // self.mod.ACCOUNT_UNIT + with sqlite3.connect(self._db) as c: + self.assertEqual(c.execute("SELECT settled FROM epoch_state WHERE epoch = ?", + (epoch,)).fetchone()[0], 1) + for pk, _ in miners: + credit = c.execute("SELECT amount_i64 FROM balances WHERE miner_id = ?", + (pk,)).fetchone()[0] + self.assertGreater(credit, 0) + self.assertEqual(self._utxo_total(c, pk), credit * ratio, + f"{pk}: UTXO reward != account credit (models disagree)") + + def test_no_utxo_mint_for_miner_without_balance_row(self): + epoch = 6102 + self._enroll(epoch, "prec-credited", self.mod.epoch_weight_to_units(2.0)) + self._enroll(epoch, "prec-ghost", self.mod.epoch_weight_to_units(2.0), with_balance_row=False) + + self.mod.finalize_epoch(epoch, per_block_rtc=self.mod.PER_BLOCK_RTC, prev_block_hash=b"") + + with sqlite3.connect(self._db) as c: + self.assertEqual(c.execute("SELECT COUNT(*) FROM balances WHERE miner_id = 'prec-ghost'") + .fetchone()[0], 0, "no-phantom: no balance row may be created") + self.assertEqual(self._utxo_total(c, "prec-ghost"), 0, + "UTXO minted for a miner the account model never credited") + # The ghost still dilutes total_weight (its share is burned in both + # models); the credited miner must still mirror its credit exactly. + credit = c.execute("SELECT amount_i64 FROM balances WHERE miner_id = 'prec-credited'").fetchone()[0] + self.assertGreater(credit, 0) + self.assertEqual(self._utxo_total(c, "prec-credited"), + credit * (self.mod.UTXO_UNIT // self.mod.ACCOUNT_UNIT)) + + +if __name__ == "__main__": + unittest.main() diff --git a/node/tests/test_finalize_epoch_reward_mirror_registration.py b/node/tests/test_finalize_epoch_reward_mirror_registration.py new file mode 100644 index 000000000..db185f134 --- /dev/null +++ b/node/tests/test_finalize_epoch_reward_mirror_registration.py @@ -0,0 +1,92 @@ +# SPDX-License-Identifier: MIT +"""End-to-end: under UTXO dual-write, finalize_epoch registers ITS OWN reward +boxes as account-mirror provenance, and only those. + +Reward batches mint at height epoch*EPOCH_SLOTS + batch_index, which is in the +same number space as /utxo/transfer's current_slot() heights. A height-only +match would tag an unrelated user's transfer box at that height as a mirror, +locking it (every spend -> 409 ACCOUNT_MIRROR_BOX_NOT_SPENDABLE). +""" +import importlib.util +import os +import sqlite3 +import tempfile +import time +import unittest +from pathlib import Path + +MODULE_PATH = Path(__file__).resolve().parents[1] / "rustchain_v2_integrated_v2.2.1_rip200.py" + + +class FinalizeEpochRewardMirrorRegistrationTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._saved_env = {k: os.environ.get(k) for k in + ("RUSTCHAIN_DB_PATH", "RC_ADMIN_KEY", "RUSTCHAIN_DISABLE_P2P_AUTO_START")} + cls._tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + cls._db = os.path.join(cls._tmp.name, "dwmirror.db") + os.environ["RUSTCHAIN_DB_PATH"] = cls._db + os.environ.setdefault("RC_ADMIN_KEY", "0123456789abcdef0123456789abcdef") + os.environ["RUSTCHAIN_DISABLE_P2P_AUTO_START"] = "1" + spec = importlib.util.spec_from_file_location("rcnode_dwmirror_test", MODULE_PATH) + cls.mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(cls.mod) + cls.mod.init_db() + with sqlite3.connect(cls._db) as c: # production (miner_id, amount_i64) shape + c.execute("DROP TABLE IF EXISTS balances") + c.execute("CREATE TABLE balances (miner_id TEXT PRIMARY KEY, " + "amount_i64 INTEGER NOT NULL DEFAULT 0 CHECK(amount_i64>=0), " + "balance_rtc REAL DEFAULT 0)") + c.commit() + from utxo_db import UtxoDB + UtxoDB(cls._db).init_tables() + cls._orig_dual_write = cls.mod.UTXO_DUAL_WRITE + cls.mod.UTXO_DUAL_WRITE = True + + @classmethod + def tearDownClass(cls): + cls.mod.UTXO_DUAL_WRITE = cls._orig_dual_write + for k, v in cls._saved_env.items(): + if v is None: + os.environ.pop(k, None) + else: + os.environ[k] = v + cls._tmp.cleanup() + + def test_only_this_epochs_reward_boxes_become_mirrors(self): + epoch = 6201 + height = epoch * self.mod.EPOCH_SLOTS # batch 0's mint height + miners = [("mir-a", 3), ("mir-b", 5)] + with sqlite3.connect(self._db) as c: + for pk, w in miners: + c.execute("INSERT OR REPLACE INTO epoch_enroll (epoch, miner_pk, weight) VALUES (?, ?, ?)", + (epoch, pk, self.mod.epoch_weight_to_units(w))) + c.execute("INSERT OR IGNORE INTO balances (miner_id, amount_i64) VALUES (?, 0)", (pk,)) + # A user's ordinary transfer output that happens to share the height. + now = int(time.time()) + c.execute("INSERT INTO utxo_transactions (tx_id, tx_type, inputs_json, outputs_json, " + "timestamp, block_height) VALUES ('user-transfer-tx', 'transfer', '[]', '[]', ?, ?)", + (now, height)) + c.execute("INSERT INTO utxo_boxes (box_id, value_nrtc, proposition, owner_address, " + "creation_height, transaction_id, output_index, created_at) " + "VALUES ('user-box', 5000000, 'p', 'RTC' || ?, ?, 'user-transfer-tx', 0, ?)", + ("ab" * 20, height, now)) + c.commit() + + self.mod.finalize_epoch(epoch, per_block_rtc=self.mod.PER_BLOCK_RTC, prev_block_hash=b"") + + ratio = self.mod.UTXO_UNIT // self.mod.ACCOUNT_UNIT + with sqlite3.connect(self._db) as c: + mirrors = {r[0]: (r[1], r[2]) for r in c.execute( + "SELECT box_id, account_wallet, value_nrtc FROM account_mirror_boxes")} + self.assertNotIn("user-box", mirrors, + "a user's transfer box at the reward height was tagged as a mirror (locked)") + for pk, _ in miners: + credit = c.execute("SELECT amount_i64 FROM balances WHERE miner_id = ?", (pk,)).fetchone()[0] + rows = [v for (w, v) in mirrors.values() if w == pk] + self.assertEqual(len(rows), 1, f"{pk}: reward box not registered as mirror") + self.assertEqual(rows[0], credit * ratio, f"{pk}: mirror value != account credit") + + +if __name__ == "__main__": + unittest.main() diff --git a/node/tests/test_rip200_settlement_dualwrite.py b/node/tests/test_rip200_settlement_dualwrite.py new file mode 100644 index 000000000..28a06e673 --- /dev/null +++ b/node/tests/test_rip200_settlement_dualwrite.py @@ -0,0 +1,90 @@ +# SPDX-License-Identifier: MIT +"""settle_epoch_rip200 is the path production actually settles with (cron -> +POST /rewards/settle -> settle_epoch). Under UTXO_DUAL_WRITE it must mint a +reward box mirroring each account credit; before this fix it minted nothing, so +the account model grew by the epoch pot every epoch while the UTXO side stood +still (#2819, same class as the finalize_epoch precision split).""" +import importlib +import os +import sqlite3 +import sys +import tempfile +import unittest +from pathlib import Path + +NODE = str(Path(__file__).resolve().parents[1]) +if NODE not in sys.path: + sys.path.insert(0, NODE) + + +class Rip200SettlementDualWriteTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + self.db = os.path.join(self.tmp.name, "settle.db") + os.environ["UTXO_DUAL_WRITE"] = "1" + import rewards_implementation_rip200 as rip + self.rip = importlib.reload(rip) # picks up UTXO_DUAL_WRITE + from utxo_db import UtxoDB + UtxoDB(self.db).init_tables() + with sqlite3.connect(self.db) as c: + c.execute("CREATE TABLE IF NOT EXISTS balances (miner_id TEXT PRIMARY KEY, amount_i64 INTEGER NOT NULL DEFAULT 0)") + c.execute("CREATE TABLE IF NOT EXISTS epoch_rewards (epoch INTEGER, miner_id TEXT, share_i64 INTEGER)") + c.commit() + + def tearDown(self): + os.environ.pop("UTXO_DUAL_WRITE", None) + importlib.reload(self.rip) + self.tmp.cleanup() + + def _mint(self, rewards, epoch=7001): + conn = sqlite3.connect(self.db) + try: + conn.execute("BEGIN IMMEDIATE") + for miner, urtc in rewards.items(): + conn.execute("INSERT INTO balances (miner_id, amount_i64) VALUES (?,?) " + "ON CONFLICT(miner_id) DO UPDATE SET amount_i64 = amount_i64 + ?", + (miner, urtc, urtc)) + conn.execute("INSERT INTO epoch_rewards (epoch, miner_id, share_i64) VALUES (?,?,?)", + (epoch, miner, urtc)) + res = self.rip._dual_write_mint_rewards(conn, epoch, self.db) + conn.commit() + return res + finally: + conn.close() + + def test_each_credit_gets_an_exactly_matching_mirror_box(self): + rewards = {"RTC" + "a" * 40: 16777395, "dual-g4-125": 7522569} + res = self._mint(rewards) + self.assertEqual(res["minted_boxes"], 2) + with sqlite3.connect(self.db) as c: + for miner, urtc in rewards.items(): + box = c.execute("SELECT COALESCE(SUM(value_nrtc),0) FROM utxo_boxes " + "WHERE owner_address=? AND spent_at IS NULL", (miner,)).fetchone()[0] + self.assertEqual(box, urtc * 100, f"{miner}: box != credit x100") + mirrored = c.execute("SELECT COUNT(*) FROM account_mirror_boxes m JOIN utxo_boxes b " + "ON b.box_id=m.box_id WHERE b.owner_address=?", (miner,)).fetchone()[0] + self.assertEqual(mirrored, 1, f"{miner}: reward box not registered as a mirror") + unmirrored = c.execute("SELECT COUNT(*) FROM utxo_boxes WHERE spent_at IS NULL AND box_id " + "NOT IN (SELECT box_id FROM account_mirror_boxes)").fetchone()[0] + self.assertEqual(unmirrored, 0) + + def test_sub_dust_share_is_skipped_not_minted(self): + res = self._mint({"tiny-miner": 5}) # 5 uRTC = 500 nRTC < 1000 dust + self.assertEqual(res["minted_boxes"], 0) + self.assertEqual(res["skipped_dust_nrtc"], 500) + + def test_does_nothing_when_dual_write_is_off(self): + os.environ["UTXO_DUAL_WRITE"] = "0" + rip = importlib.reload(self.rip) + conn = sqlite3.connect(self.db) + try: + res = rip._dual_write_mint_rewards(conn, 7002, self.db) + finally: + conn.close() + self.assertEqual(res["minted_boxes"], 0) + with sqlite3.connect(self.db) as c: + self.assertEqual(c.execute("SELECT COUNT(*) FROM utxo_boxes").fetchone()[0], 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/node/tests/test_service_catalog.py b/node/tests/test_service_catalog.py new file mode 100644 index 000000000..8fc2b74c8 --- /dev/null +++ b/node/tests/test_service_catalog.py @@ -0,0 +1,351 @@ +# SPDX-License-Identifier: MIT +"""Tests for the RTC service catalog (node/service_catalog.py).""" +import hashlib +import json +import sqlite3 +import time + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat +from flask import Flask + +import service_catalog as sc + + +class Agent: + def __init__(self): + self.key = Ed25519PrivateKey.generate() + pub = self.key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) + self.pubkey_hex = pub.hex() + self.id = "bcn_" + hashlib.sha256(pub).hexdigest()[:12] + self._n = 0 + + def headers(self, method, path, body, *, ts=None, nonce=None): + self._n += 1 + ts = int(time.time()) if ts is None else ts + nonce = nonce or f"n{self._n}" + msg = "\n".join([method, path, hashlib.sha256(body).hexdigest(), + str(ts), nonce, self.id]).encode() + return { + "X-Agent-Id": self.id, + "X-Agent-Timestamp": str(ts), + "X-Agent-Nonce": nonce, + "X-Agent-Signature": self.key.sign(msg).hex(), + "Content-Type": "application/json", + } + + +@pytest.fixture +def env(tmp_path): + db = str(tmp_path / "node.db") + with sqlite3.connect(db) as conn: + conn.execute("""CREATE TABLE pending_ledger ( + id INTEGER PRIMARY KEY AUTOINCREMENT, from_miner TEXT, to_miner TEXT, + amount_i64 INTEGER, reason TEXT, status TEXT, tx_hash TEXT)""") + registry = {} + app = Flask(__name__) + assert sc.register_service_catalog(app, db, pubkey_resolver=registry.get) + client = app.test_client() + + def make_agent(): + a = Agent() + registry[a.id] = a.pubkey_hex + return a + + def post(agent, path, payload, **kw): + body = json.dumps(payload).encode() + return client.post(path, data=body, headers=agent.headers("POST", path, body, **kw)) + + return {"db": db, "client": client, "agent": make_agent, "post": post} + + +LISTING = {"title": "Render a 10s clip", "category": "render", "price_rtc": 2.5, + "unit": "per clip", "turnaround_hours": 24} + + +def make_listing(env, provider, **over): + r = env["post"](provider, "/catalog/listings", {**LISTING, **over}) + assert r.status_code == 201, r.get_json() + return r.get_json() + + +def full_order(env, provider, buyer, digest="a" * 64): + listing = make_listing(env, provider) + order = env["post"](buyer, "/catalog/orders", {"listing_id": listing["id"]}).get_json() + r = env["post"](provider, f"/catalog/orders/{order['id']}/deliver", {"deliverable_hash": digest}) + assert r.status_code == 200, r.get_json() + return order + + +def test_index_is_rtc_only_and_states_non_custody(env): + body = env["client"].get("/catalog").get_json() + assert body["currency"] == "RTC" + assert "holds no funds" in body["terms"] + assert "$" not in json.dumps(body) + + +def test_create_and_list_listing(env): + p = env["agent"]() + listing = make_listing(env, p) + assert listing["provider"] == p.id and listing["price_rtc"] == 2.5 + listed = env["client"].get("/catalog/listings?category=render").get_json()["listings"] + assert [x["id"] for x in listed] == [listing["id"]] + + +@pytest.mark.parametrize("field,value", [ + ("price_usd", 1), ("usd_value", "0.10"), ("reference_rate", 0.1)]) +def test_unknown_fields_rejected(env, field, value): + r = env["post"](env["agent"](), "/catalog/listings", {**LISTING, field: value}) + assert r.status_code == 400 and r.get_json()["error"] == "unknown_fields" + + +@pytest.mark.parametrize("title", [ + "Render for $5", "Render 5$ each", "Render worth 3 USD", "Paid in USDC", + "Ten dollars", "Costs USD5", "Only 5USD", "Fullwidth \uff045 ok", "Five euros each"]) +def test_fiat_text_rejected(env, title): + r = env["post"](env["agent"](), "/catalog/listings", {**LISTING, "title": title}) + assert r.get_json()["error"] == "fiat_reference_not_allowed" + + +@pytest.mark.parametrize("price", [0, -1, "abc", True, 0.0000001, 100_001, "NaN", "1e999999", "-1e999999"]) +def test_bad_prices_rejected(env, price): + r = env["post"](env["agent"](), "/catalog/listings", {**LISTING, "price_rtc": price}) + assert r.status_code == 400 + + +def test_unsigned_and_unregistered_rejected(env): + c = env["client"] + assert c.post("/catalog/listings", json=LISTING).status_code == 401 + stranger = Agent() # never registered + assert env["post"](stranger, "/catalog/listings", LISTING).status_code == 403 + + +def test_bad_signature_stale_and_replay(env): + p = env["agent"]() + body = json.dumps(LISTING).encode() + h = p.headers("POST", "/catalog/listings", body) + h["X-Agent-Signature"] = "00" * 64 + assert env["client"].post("/catalog/listings", data=body, headers=h).status_code == 401 + stale = env["post"](p, "/catalog/listings", LISTING, ts=int(time.time()) - 1000) + assert stale.status_code == 401 + future = env["post"](p, "/catalog/listings", LISTING, ts=int(time.time()) + 120) + assert future.status_code == 401 + assert env["post"](p, "/catalog/listings", LISTING, nonce="same").status_code == 201 + assert env["post"](p, "/catalog/listings", LISTING, nonce="same").status_code == 401 + + +def test_signature_bound_to_body(env): + p = env["agent"]() + signed = json.dumps(LISTING).encode() + tampered = json.dumps({**LISTING, "price_rtc": 99}).encode() + h = p.headers("POST", "/catalog/listings", signed) + assert env["client"].post("/catalog/listings", data=tampered, headers=h).status_code == 401 + + +def test_self_dealing_blocked(env): + p = env["agent"]() + listing = make_listing(env, p) + r = env["post"](p, "/catalog/orders", {"listing_id": listing["id"]}) + assert r.get_json()["error"] == "self_dealing" + + +def test_order_happy_path_returns_payment_instructions(env): + p, b = env["agent"](), env["agent"]() + order = full_order(env, p, b) + r = env["post"](b, f"/catalog/orders/{order['id']}/accept", {}) + body = r.get_json() + assert body["status"] == "accepted" + assert body["payment"] == {"state": "unpaid"} + ins = body["payment_instructions"] + assert ins == {"endpoint": "/wallet/transfer/signed", "to_address": p.id, + "amount_rtc": 2.5, "memo": f"svc:{order['id']}", + "note": ins["note"]} + + +def test_catalog_never_writes_ledger(env): + p, b = env["agent"](), env["agent"]() + order = full_order(env, p, b) + env["post"](b, f"/catalog/orders/{order['id']}/accept", {}) + with sqlite3.connect(env["db"]) as conn: + assert conn.execute("SELECT COUNT(*) FROM pending_ledger").fetchone()[0] == 0 + + +def _pay(env, frm, to, amount_i64, memo, status="pending"): + with sqlite3.connect(env["db"]) as conn: + conn.execute("INSERT INTO pending_ledger (from_miner, to_miner, amount_i64, reason, " + "status, tx_hash) VALUES (?, ?, ?, ?, ?, 'tx1')", + (frm, to, amount_i64, "signed_transfer:" + memo, status)) + + +def test_payment_reconciliation(env): + p, b = env["agent"](), env["agent"]() + order = full_order(env, p, b) + env["post"](b, f"/catalog/orders/{order['id']}/accept", {}) + + def get(): + return env["client"].get(f"/catalog/orders/{order['id']}").get_json()["payment"] + + memo = f"svc:{order['id']}" + _pay(env, b.id, p.id, 1_000_000, memo) # underpaid + _pay(env, p.id, p.id, 5_000_000, memo) # self-transfer + _pay(env, b.id, p.id, 5_000_000, memo, "voided") # voided + _pay(env, b.id, "bcn_other00000", 5_000_000, memo) # wrong recipient + assert get() == {"state": "unpaid"} + _pay(env, b.id, p.id, 2_500_000, memo) + assert get()["state"] == "pending" + _pay(env, b.id, p.id, 2_500_000, memo, "confirmed") + assert get()["state"] == "confirmed" + + +def test_deliverable_hash_settles_once_per_provider(env): + p, b, other = env["agent"](), env["agent"](), env["agent"]() + first = full_order(env, p, b, digest="b" * 64) + listing = make_listing(env, p, title="Another render job") + o2 = env["post"](b, "/catalog/orders", {"listing_id": listing["id"]}).get_json() + path = f"/catalog/orders/{o2['id']}/deliver" + assert env["post"](p, path, {"deliverable_hash": "b" * 64}).status_code == 409 + # Another provider can't be blocked by someone else's hash. + full_order(env, other, b, digest="b" * 64) + # A rejected order frees the hash for redelivery. + env["post"](b, f"/catalog/orders/{first['id']}/reject", {"reason": "wrong size"}) + assert env["post"](p, path, {"deliverable_hash": "b" * 64}).status_code == 200 + + +def test_only_right_party_transitions(env): + p, b, x = env["agent"](), env["agent"](), env["agent"]() + listing = make_listing(env, p) + order = env["post"](b, "/catalog/orders", {"listing_id": listing["id"]}).get_json() + path = f"/catalog/orders/{order['id']}" + assert env["post"](b, path + "/deliver", {"deliverable_hash": "c" * 64}).status_code == 403 + assert env["post"](x, path + "/cancel", {}).status_code == 403 + assert env["post"](b, path + "/accept", {}).status_code == 409 # not delivered yet + env["post"](p, path + "/deliver", {"deliverable_hash": "c" * 64}) + assert env["post"](p, path + "/accept", {}).status_code == 403 + assert env["post"](b, path + "/cancel", {}).status_code == 409 # past requested + r = env["post"](b, path + "/reject", {"reason": "wrong format"}) + assert r.get_json()["status"] == "rejected" + + +def test_inactive_listing_cannot_be_ordered_and_retired_is_final(env): + p, b = env["agent"](), env["agent"]() + listing = make_listing(env, p) + path = f"/catalog/listings/{listing['id']}/status" + assert env["post"](b, path, {"status": "paused"}).status_code == 403 + assert env["post"](p, path, {"status": "paused"}).get_json()["status"] == "paused" + assert env["post"](b, "/catalog/orders", {"listing_id": listing["id"]}).status_code == 409 + assert env["post"](p, path, {"status": "retired"}).status_code == 200 + assert env["post"](p, path, {"status": "active"}).status_code == 409 + + +def test_price_snapshot_survives_new_listing(env): + p, b = env["agent"](), env["agent"]() + order = full_order(env, p, b) + make_listing(env, p, price_rtc=9) + got = env["client"].get(f"/catalog/orders/{order['id']}").get_json() + assert got["price_rtc"] == 2.5 + + +def test_provider_record_counts_work_not_rtc(env): + p, b1, b2 = env["agent"](), env["agent"](), env["agent"]() + for buyer, digest in ((b1, "d" * 64), (b2, "e" * 64)): + o = full_order(env, p, buyer, digest=digest) + env["post"](buyer, f"/catalog/orders/{o['id']}/accept", {}) + rec = env["client"].get(f"/catalog/providers/{p.id}").get_json() + assert rec["orders_accepted"] == 2 and rec["distinct_buyers_accepted"] == 2 + assert not any("rtc" in k for k in rec) + + +def test_listing_cap(env, monkeypatch): + monkeypatch.setattr(sc, "MAX_ACTIVE_LISTINGS", 2) + p = env["agent"]() + make_listing(env, p) + make_listing(env, p) + assert env["post"](p, "/catalog/listings", LISTING).status_code == 429 + + +def test_refused_request_spends_its_nonce(env): + p, b = env["agent"](), env["agent"]() + listing = make_listing(env, p) + order = env["post"](b, "/catalog/orders", {"listing_id": listing["id"]}).get_json() + path = f"/catalog/orders/{order['id']}/accept" + body = b"{}" + early = b.headers("POST", path, body) + assert env["client"].post(path, data=body, headers=early).status_code == 409 + env["post"](p, f"/catalog/orders/{order['id']}/deliver", {"deliverable_hash": "f" * 64}) + replay = env["client"].post(path, data=body, headers=early) + assert replay.status_code == 401 + assert env["client"].get(f"/catalog/orders/{order['id']}").get_json()["status"] == "delivered" + + +def test_atlas_resolver_requires_active_and_matching_id(tmp_path): + atlas = str(tmp_path / "atlas.db") + good, bad = Agent(), Agent() + with sqlite3.connect(atlas) as conn: + conn.execute("CREATE TABLE relay_agents (agent_id TEXT, pubkey_hex TEXT, status TEXT)") + conn.execute("INSERT INTO relay_agents VALUES (?, ?, 'active')", (good.id, good.pubkey_hex)) + conn.execute("INSERT INTO relay_agents VALUES (?, ?, 'suspended')", (bad.id, bad.pubkey_hex)) + resolve = sc._atlas_pubkey_resolver(atlas) + assert resolve(good.id) == good.pubkey_hex + assert resolve(bad.id) is None + # Heartbeats set "alive"/"degraded"; those stay usable, like the payment path. + for status in ("alive", "degraded", "banned", "revoked"): + a = Agent() + with sqlite3.connect(atlas) as conn: + conn.execute("INSERT INTO relay_agents VALUES (?, ?, ?)", (a.id, a.pubkey_hex, status)) + expected = None if status in ("banned", "revoked") else a.pubkey_hex + assert resolve(a.id) == expected, status + assert resolve("bcn_000000000000") is None + assert not sc._id_matches_pubkey(good.id, bad.pubkey_hex) + + +def test_order_view_is_private_to_parties(env): + p, b, x = env["agent"](), env["agent"](), env["agent"]() + listing = make_listing(env, p) + order = env["post"](b, "/catalog/orders", {"listing_id": listing["id"], "note": "secret brief"}).get_json() + path = f"/catalog/orders/{order['id']}" + public = env["client"].get(path).get_json() + assert "note" not in public and "buyer" not in public + for agent, code in ((b, 200), (p, 200), (x, 403)): + r = env["client"].get(path, headers=agent.headers("GET", path, b"")) + assert r.status_code == code + r = env["client"].get(path, headers=b.headers("GET", path, b"")) + assert r.get_json()["note"] == "secret brief" + + +def test_provider_inbox_and_signed_query(env): + p, b = env["agent"](), env["agent"]() + listing = make_listing(env, p) + env["post"](b, "/catalog/orders", {"listing_id": listing["id"]}) + path = "/catalog/orders?role=provider&status=requested" + r = env["client"].get(path, headers=p.headers("GET", path, b"")) + assert [o["buyer"] for o in r.get_json()["orders"]] == [b.id] + # A signature for one query can't be reused for another. + h = p.headers("GET", path, b"") + assert env["client"].get("/catalog/orders?role=buyer", headers=h).status_code == 401 + + +def test_fiat_in_order_note_rejected(env): + p, b = env["agent"](), env["agent"]() + listing = make_listing(env, p) + r = env["post"](b, "/catalog/orders", {"listing_id": listing["id"], "note": "I'll pay $50 via PayPal"}) + assert r.get_json()["error"] == "fiat_reference_not_allowed" + + +def test_paid_counts_need_confirmed_transfer(env): + p, b = env["agent"](), env["agent"]() + order = full_order(env, p, b) + env["post"](b, f"/catalog/orders/{order['id']}/accept", {}) + rec = lambda: env["client"].get(f"/catalog/providers/{p.id}").get_json() # noqa: E731 + assert rec()["orders_accepted"] == 1 and rec()["orders_paid_confirmed"] == 0 + _pay(env, b.id, p.id, 2_500_000, f"svc:{order['id']}", "confirmed") + assert rec()["orders_paid_confirmed"] == 1 and rec()["distinct_paying_buyers"] == 1 + + +def test_daily_order_cap(env, monkeypatch): + monkeypatch.setattr(sc, "MAX_ORDERS_PER_DAY", 1) + p, b = env["agent"](), env["agent"]() + listing = make_listing(env, p) + first = env["post"](b, "/catalog/orders", {"listing_id": listing["id"]}).get_json() + env["post"](b, f"/catalog/orders/{first['id']}/cancel", {}) + assert env["post"](b, "/catalog/orders", {"listing_id": listing["id"]}).status_code == 429 diff --git a/node/tests/test_sophia_elya_service.py b/node/tests/test_sophia_elya_service.py index cd2ae999b..963cd3a38 100644 --- a/node/tests/test_sophia_elya_service.py +++ b/node/tests/test_sophia_elya_service.py @@ -1,9 +1,23 @@ import sqlite3 import time +import pytest + from node import sophia_elya_service as elya +@pytest.fixture(autouse=True) +def _opt_in_legacy_settlement(monkeypatch, tmp_path): + # These tests exercise the legacy RIP-0005 prototype's own settlement logic + # against throwaway DBs; its money paths are fail-closed unless opted in. + # Also isolate DB_PATH: the module default is the relative + # "./rustchain_v2.db", which previously left a settled DB in the cwd and made + # reruns fail with "already_settled". + monkeypatch.setenv("RUSTCHAIN_SOPHIA_ELYA_LEGACY_SETTLEMENT", "1") + monkeypatch.setattr(elya, "DB_PATH", str(tmp_path / "elya.db")) + elya.init_db() + + def _client(): elya.app.config["TESTING"] = True return elya.app.test_client() diff --git a/node/tests/test_sophia_elya_service_money_units.py b/node/tests/test_sophia_elya_service_money_units.py index 66bb33a31..f7e87c36f 100644 --- a/node/tests/test_sophia_elya_service_money_units.py +++ b/node/tests/test_sophia_elya_service_money_units.py @@ -4,6 +4,15 @@ import tempfile from pathlib import Path +import pytest + + +@pytest.fixture(autouse=True) +def _opt_in_legacy_settlement(monkeypatch): + # These tests exercise the legacy RIP-0005 prototype's own settlement logic + # against throwaway DBs; its money paths are fail-closed unless opted in. + monkeypatch.setenv("RUSTCHAIN_SOPHIA_ELYA_LEGACY_SETTLEMENT", "1") + def load_service(tmp_path): module_path = Path(__file__).resolve().parents[1] / "sophia_elya_service.py" diff --git a/node/tests/test_utxo_integrity_single_snapshot.py b/node/tests/test_utxo_integrity_single_snapshot.py new file mode 100644 index 000000000..164b20bf8 --- /dev/null +++ b/node/tests/test_utxo_integrity_single_snapshot.py @@ -0,0 +1,143 @@ +# SPDX-License-Identifier: MIT +"""#2819 (robin1121): the integrity report must describe ONE snapshot. + +compute_state_root() opened its own connection, so the totals and the root +beside them could come from two different database states (and models_agree +was decided across them). These tests pin the totals, the root and the caller's +view to a single connection. The mixing is made deterministic with an +uncommitted write: a box visible only inside one transaction must appear in +both the totals and the root computed for that same connection, or in neither. +""" +import os +import sqlite3 +import sys +import tempfile +import time +import unittest + +NODE = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if NODE not in sys.path: + sys.path.insert(0, NODE) + +from utxo_db import UtxoDB, UNIT + + +def _insert_box(conn, box_id, owner, value_nrtc, height=1): + now = int(time.time()) + conn.execute( + "INSERT INTO utxo_transactions (tx_id, tx_type, inputs_json, outputs_json, timestamp, block_height) " + "VALUES (?, 'transfer', '[]', '[]', ?, ?)", (f"tx-{box_id}", now, height)) + conn.execute( + "INSERT INTO utxo_boxes (box_id, value_nrtc, proposition, owner_address, creation_height, " + "transaction_id, output_index, created_at) VALUES (?,?,?,?,?,?,0,?)", + (box_id, value_nrtc, "p", owner, height, f"tx-{box_id}", now)) + + +class IntegritySingleSnapshotTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.NamedTemporaryFile(suffix=".db", delete=False) + self.tmp.close() + self.db = UtxoDB(self.tmp.name) + self.db.init_tables() + with sqlite3.connect(self.tmp.name) as c: + c.execute("CREATE TABLE IF NOT EXISTS balances (miner_id TEXT PRIMARY KEY, " + "amount_i64 INTEGER NOT NULL DEFAULT 0)") + _insert_box(c, "box-committed", "RTC" + "a" * 40, 5 * UNIT) + c.commit() + + def tearDown(self): + os.unlink(self.tmp.name) + + def test_totals_and_root_come_from_the_callers_snapshot(self): + conn = sqlite3.connect(self.tmp.name) + conn.row_factory = sqlite3.Row + try: + conn.execute("BEGIN IMMEDIATE") + _insert_box(conn, "box-uncommitted", "RTC" + "b" * 40, 7 * UNIT, height=2) + + result = self.db.integrity_check(conn=conn) + root_same_conn = self.db.compute_state_root(conn=conn) + + # Everything must describe the caller's view: 2 boxes, 12 RTC, and a + # root over both. Pre-fix the root was computed on a second + # connection, which could not see box-uncommitted. + self.assertEqual(result["total_unspent_boxes"], 2) + self.assertEqual(result["total_unspent_nrtc"], 12 * UNIT) + self.assertEqual(result["state_root"], root_same_conn) + self.assertNotEqual(result["state_root"], self.db.compute_state_root(), + "root must reflect the caller's snapshot, not a fresh one") + self.assertEqual(self.db.count_unspent(conn=conn), 2) + finally: + conn.rollback() + conn.close() + + def test_models_agree_is_decided_on_one_snapshot(self): + """expected_total is compared against totals from the same connection.""" + conn = sqlite3.connect(self.tmp.name) + conn.row_factory = sqlite3.Row + try: + conn.execute("BEGIN IMMEDIATE") + _insert_box(conn, "box-settlement", "RTC" + "c" * 40, 3 * UNIT, height=3) + # An account model that already includes the in-flight 3 RTC agrees + # only if the UTXO side is read from this same snapshot. + res = self.db.integrity_check(expected_total=8 * UNIT, conn=conn) + self.assertTrue(res["ok"]) + self.assertTrue(res.get("models_agree")) + finally: + conn.rollback() + conn.close() + + def test_default_behaviour_unchanged_without_a_connection(self): + res = self.db.integrity_check() + self.assertEqual(res["total_unspent_boxes"], 1) + self.assertEqual(res["state_root"], self.db.compute_state_root()) + self.assertEqual(self.db.count_unspent(), 1) + + +if __name__ == "__main__": + unittest.main() + + +class IntegrityRaceTest(unittest.TestCase): + """A settlement committing BETWEEN the totals read and the root read must not + split the report across two states (the original robin1121 defect).""" + + def setUp(self): + self.tmp = tempfile.NamedTemporaryFile(suffix=".db", delete=False) + self.tmp.close() + self.db = UtxoDB(self.tmp.name) + self.db.init_tables() + with sqlite3.connect(self.tmp.name) as c: + _insert_box(c, "box-1", "RTC" + "a" * 40, 5 * UNIT) + c.commit() + + def tearDown(self): + os.unlink(self.tmp.name) + + def test_concurrent_commit_between_reads_does_not_split_the_report(self): + real_root = self.db.compute_state_root + + def root_with_interleaved_commit(*a, **kw): + # Simulate an epoch settlement committing on another connection + # after the totals were read but before the root is computed. + with sqlite3.connect(self.tmp.name) as other: + _insert_box(other, "box-race", "RTC" + "d" * 40, 9 * UNIT, height=9) + other.commit() + self.db.compute_state_root = real_root # only interleave once + return real_root(*a, **kw) + + self.db.compute_state_root = root_with_interleaved_commit + try: + res = self.db.integrity_check() + finally: + self.db.compute_state_root = real_root + + # The report must be internally consistent: the root must be the root OF + # the box set whose totals it reports (1 box / 5 RTC), not of the set + # after the interleaved commit. + self.assertEqual(res["total_unspent_boxes"], 1) + self.assertEqual(res["total_unspent_nrtc"], 5 * UNIT) + after = self.db.compute_state_root() # old API only: root of the 2-box set now + self.assertNotEqual(res["state_root"], after, + "root reflects the post-commit set while the totals beside it " + "reflect the pre-commit set (report split across two snapshots)") diff --git a/node/tests/test_utxo_state_root_memo.py b/node/tests/test_utxo_state_root_memo.py new file mode 100644 index 000000000..b5532d1b3 --- /dev/null +++ b/node/tests/test_utxo_state_root_memo.py @@ -0,0 +1,372 @@ +# SPDX-License-Identifier: MIT +"""State root memoization keyed by a DB-level UTXO state version. + +/utxo/state_root, /utxo/stats and /utxo/integrity are unauthenticated. Each +used to run compute_state_root() -- an O(N) scan + JSON + SHA-256 per unspent +box -- on every request. The root is now memoized in utxo_state_memo, keyed by +utxo_state_version, which triggers on utxo_boxes bump inside the mutating +transaction. These tests pin: + +* a second read with no intervening mutation does not rescan (fails on the + pre-memo code, which rescanned on every request); +* every utxo_boxes mutation path bumps the version, and the next read + recomputes to exactly what a fresh compute_state_root() returns; +* mempool-only changes and rolled-back mutations do not change the version; +* reads pinned in one snapshot stay consistent while another connection + commits; +* the full recompute on /utxo/integrity is admin-only (?force=1). +""" +import os +import sqlite3 +import sys +import tempfile +import time +import unittest +from unittest import mock + +from flask import Flask + +NODE = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if NODE not in sys.path: + sys.path.insert(0, NODE) + +import state_pruning # noqa: E402 +import utxo_endpoints # noqa: E402 +import utxo_genesis_migration # noqa: E402 +from utxo_db import SCHEMA_SQL, UNIT, UtxoDB # noqa: E402 + +ADDR_A = "RTC" + "a" * 40 +ADDR_B = "RTC" + "b" * 40 + + +class _Base(unittest.TestCase): + def setUp(self): + fd, self.path = tempfile.mkstemp(suffix=".db") + os.close(fd) + self.db = UtxoDB(self.path) + self.db.init_tables() + with sqlite3.connect(self.path) as c: + c.execute("CREATE TABLE IF NOT EXISTS balances (miner_id TEXT PRIMARY KEY, " + "amount_i64 INTEGER NOT NULL DEFAULT 0)") + self._coinbase(ADDR_A, 5 * UNIT, 1) + self._coinbase(ADDR_B, 7 * UNIT, 2) + + self.app = Flask("test_utxo_state_root_memo") + self.app.testing = True + utxo_endpoints.register_utxo_blueprint( + app=self.app, utxo_db=self.db, db_path=self.path, + verify_sig_fn=lambda *a: True, + addr_from_pk_fn=lambda pk: ADDR_A, + current_slot_fn=lambda: 100, + dual_write=False, + ) + self.client = self.app.test_client() + + self.scans = 0 + real = UtxoDB.compute_state_root + + def counting(db_self, *a, **kw): + self.scans += 1 + return real(db_self, *a, **kw) + + patcher = mock.patch.object(UtxoDB, "compute_state_root", counting) + patcher.start() + self.addCleanup(patcher.stop) + self._real_root = lambda: real(self.db) + + def tearDown(self): + for suffix in ("", "-wal", "-shm"): + try: + os.unlink(self.path + suffix) + except OSError: + pass + + # -- helpers --------------------------------------------------------- + def _coinbase(self, addr, value, height): + self.assertTrue(self.db.apply_transaction({ + "tx_type": "mining_reward", "inputs": [], + "outputs": [{"address": addr, "value_nrtc": value}], + "fee_nrtc": 0, "timestamp": int(time.time()) + height, + "_allow_minting": True, + }, block_height=height)) + + def _version(self): + with sqlite3.connect(self.path) as c: + return UtxoDB.get_state_version(c) + + def _root(self): + r = self.client.get("/utxo/state_root") + self.assertEqual(r.status_code, 200) + return r.get_json() + + def _assert_fresh(self, data): + """Endpoint output must equal a fresh full computation.""" + self.assertEqual(data["state_root"], self._real_root()) + self.assertEqual(data["unspent_count"], self.db.count_unspent()) + + +class StateRootMemoHitTest(_Base): + def test_second_read_does_not_rescan(self): + """Fails on the pre-memo code: every request rescanned the UTXO set.""" + first = self._root() + self.assertEqual(self.scans, 1) + second = self._root() + self.assertEqual(self.scans, 1, "second read with no mutation must hit the memo") + self.assertEqual(first["state_root"], second["state_root"]) + self.assertEqual(first["unspent_count"], second["unspent_count"]) + self._assert_fresh(second) + + def test_stats_and_integrity_share_the_memo(self): + self._root() + self.assertEqual(self.scans, 1) + stats = self.client.get("/utxo/stats").get_json() + integ = self.client.get("/utxo/integrity").get_json() + self.assertEqual(self.scans, 1, "stats/integrity must be served from the memo") + root = self._real_root() + self.assertEqual(stats["state_root"], root) + self.assertEqual(integ["state_root"], root) + self.assertEqual(stats["unspent_boxes"], 2) + self.assertEqual(stats["total_value_nrtc"], 12 * UNIT) + self.assertEqual(stats["spent_boxes"], 0) + self.assertEqual(integ["total_unspent_nrtc"], 12 * UNIT) + self.assertEqual(integ["total_unspent_boxes"], 2) + self.assertFalse(integ["full_recompute"]) + + +class MutationPathsBumpVersionTest(_Base): + def _check_mutation(self, mutate, expect_count_change=True): + before = self._root() + v0 = self._version() + mutate() + scans0 = self.scans # the mutator itself may verify (e.g. genesis) + self.assertGreater(self._version(), v0, "mutation must bump utxo_state_version") + after = self._root() + self.assertEqual(self.scans, scans0 + 1, "next read must recompute once") + self._assert_fresh(after) + if expect_count_change: + self.assertNotEqual( + (before["state_root"], before["unspent_count"]), + (after["state_root"], after["unspent_count"])) + # and the recomputed value is memoized again + self._root() + self.assertEqual(self.scans, scans0 + 1) + + def test_apply_transaction_coinbase(self): + self._check_mutation(lambda: self._coinbase(ADDR_A, 3 * UNIT, 3)) + + def test_apply_transaction_transfer(self): + box = self.db.get_unspent_for_address(ADDR_A)[0] + + def transfer(): + self.assertTrue(self.db.apply_transaction({ + "tx_type": "transfer", + "inputs": [{"box_id": box["box_id"], "spending_proof": "sig"}], + "outputs": [{"address": ADDR_B, "value_nrtc": 5 * UNIT}], + "fee_nrtc": 0, + }, block_height=4)) + self._check_mutation(transfer) + + def test_add_box(self): + def add(): + with sqlite3.connect(self.path) as c: + c.execute("INSERT INTO utxo_transactions (tx_id, tx_type, inputs_json, " + "outputs_json, timestamp) VALUES ('t-add','x','[]','[]',0)") + self.db.add_box({ + "box_id": "f" * 64, "value_nrtc": UNIT, "proposition": "00", + "owner_address": ADDR_A, "creation_height": 9, + "transaction_id": "t-add", "output_index": 0, + }) + self._check_mutation(add) + + def test_spend_box(self): + box = self.db.get_unspent_for_address(ADDR_B)[0] + self._check_mutation(lambda: self.db.spend_box(box["box_id"], "spender")) + + def test_raw_sql_writer_like_node_dual_write(self): + # The node's dual-write mirror and any future writer use raw SQL. + def raw(): + with sqlite3.connect(self.path) as c: + c.execute("UPDATE utxo_boxes SET value_nrtc = value_nrtc + 1 " + "WHERE owner_address = ?", (ADDR_A,)) + self._check_mutation(raw) + + def test_rollback_restoring_spent_at(self): + box = self.db.get_unspent_for_address(ADDR_B)[0] + self.db.spend_box(box["box_id"], "spender") + + def restore(): + with sqlite3.connect(self.path) as c: + c.execute("UPDATE utxo_boxes SET spent_at = NULL, spent_by_tx = NULL " + "WHERE box_id = ?", (box["box_id"],)) + self._check_mutation(restore) + + def test_state_pruning_delete_updates_spent_count(self): + box = self.db.get_unspent_for_address(ADDR_A)[0] + self.db.spend_box(box["box_id"], "spender") + with sqlite3.connect(self.path) as c: + c.execute("CREATE TABLE blocks (height INTEGER)") + c.execute("INSERT INTO blocks VALUES (1000)") + self.assertEqual(self.client.get("/utxo/stats").get_json()["spent_boxes"], 1) + v0 = self._version() + res = state_pruning.prune_state(self.path, retain_blocks=10, dry_run=False) + self.assertEqual(res.spent_utxo_rows, 1) + self.assertGreater(self._version(), v0) + stats = self.client.get("/utxo/stats").get_json() + self.assertEqual(stats["spent_boxes"], 0) + self.assertEqual(stats["state_root"], self._real_root()) + + def test_genesis_migration_and_rollback(self): + # Genesis only runs on an empty UTXO set; clearing it is itself a + # (raw DELETE) mutation path. + def clear(): + with sqlite3.connect(self.path) as c: + c.execute("DELETE FROM utxo_boxes") + c.execute("DELETE FROM utxo_transactions") + c.execute("INSERT INTO balances VALUES ('gen-wallet', 3000000)") + self._check_mutation(clear) + + def genesis(): + res = utxo_genesis_migration.migrate(self.path) + self.assertNotIn("error", res) + self._check_mutation(genesis) + with mock.patch.dict(os.environ, {"RC_ADMIN_KEY": "k"}): + self._check_mutation( + lambda: utxo_genesis_migration.rollback_genesis(self.path, admin_key="k")) + + def test_mempool_only_change_does_not_bump(self): + self._root() + v0, scans0 = self._version(), self.scans + box = self.db.get_unspent_for_address(ADDR_A)[0] + self.assertTrue(self.db.mempool_add({ + "tx_id": "ab" * 32, + "inputs": [{"box_id": box["box_id"]}], + "outputs": [{"address": ADDR_B, "value_nrtc": 5 * UNIT}], + "fee_nrtc": 0, + })) + self.assertEqual(self._version(), v0) + self._root() + self.assertEqual(self.scans, scans0) + + def test_rolled_back_mutation_leaves_version(self): + self._root() + v0 = self._version() + c = sqlite3.connect(self.path) + try: + c.execute("BEGIN IMMEDIATE") + c.execute("UPDATE utxo_boxes SET value_nrtc = 1") + # Summary inside the uncommitted write sees its own bump, but must + # NOT persist a memo for a state that is about to be rolled back. + inner = self.db.state_summary(conn=c) + self.assertEqual(inner["version"], v0 + 2) + self.assertFalse(inner["cached"]) + c.rollback() + finally: + c.close() + self.assertEqual(self._version(), v0) + self._assert_fresh(self._root()) + + +class SnapshotConsistencyTest(_Base): + def test_pinned_reader_ignores_concurrent_commit(self): + reader = sqlite3.connect(self.path) + try: + reader.execute("BEGIN") + s1 = self.db.state_summary(conn=reader) + # another connection commits a new box while reader is pinned + self._coinbase(ADDR_A, 9 * UNIT, 7) + s2 = self.db.state_summary(conn=reader) + self.assertEqual(s1["version"], s2["version"]) + self.assertEqual(s1["state_root"], s2["state_root"]) + self.assertEqual(s2["unspent_count"], 2) + self.assertEqual(s2["total_unspent_nrtc"], 12 * UNIT) + finally: + reader.rollback() + reader.close() + # A fresh reader sees the new state, root and count together. + s3 = self.db.state_summary() + self.assertGreater(s3["version"], s1["version"]) + self.assertEqual(s3["unspent_count"], 3) + self.assertEqual(s3["state_root"], self._real_root()) + self.assertNotEqual(s3["state_root"], s1["state_root"]) + + def test_stale_reader_cannot_overwrite_newer_memo(self): + reader = sqlite3.connect(self.path) + try: + reader.execute("BEGIN") + reader.execute("SELECT 1 FROM utxo_boxes").fetchall() # pin snapshot + self._coinbase(ADDR_A, 9 * UNIT, 7) + fresh = self.db.state_summary() # stores memo @ new version + stale = self.db.state_summary(conn=reader) # old snapshot, miss + self.assertLess(stale["version"], fresh["version"]) + finally: + reader.rollback() + reader.close() + scans0 = self.scans + again = self.db.state_summary() + self.assertTrue(again["cached"]) + self.assertEqual(self.scans, scans0) + self.assertEqual(again["state_root"], fresh["state_root"]) + + +class SchemaAndFallbackTest(_Base): + def test_existing_db_without_memo_schema(self): + fd, path = tempfile.mkstemp(suffix=".db") + os.close(fd) + try: + with sqlite3.connect(path) as c: # pre-upgrade production shape + c.executescript(SCHEMA_SQL) + db = UtxoDB(path) + s0 = db.state_summary() # no memo schema yet -> full compute, no crash + self.assertIsNone(s0["version"]) + self.assertTrue(db.ensure_state_memo_schema()) + self.assertTrue(db.ensure_state_memo_schema()) # idempotent + db.init_tables() # also idempotent over it + s1 = db.state_summary() + self.assertEqual(s1["version"], 0) + self.assertFalse(s1["cached"]) + self.assertTrue(db.state_summary()["cached"]) + finally: + for suffix in ("", "-wal", "-shm"): + try: + os.unlink(path + suffix) + except OSError: + pass + + def test_missing_trigger_disables_memo(self): + self._root() + with sqlite3.connect(self.path) as c: + c.execute("DROP TRIGGER trg_utxo_boxes_state_version_upd") + c.execute("UPDATE utxo_boxes SET value_nrtc = value_nrtc + 1") + scans0 = self.scans + data = self._root() + self.assertEqual(self.scans, scans0 + 1, "untrusted memo must not be served") + self._assert_fresh(data) + + +class IntegrityForceTest(_Base): + def test_force_requires_admin(self): + with mock.patch.dict(os.environ, {"RC_ADMIN_KEY": "sekret"}): + r = self.client.get("/utxo/integrity?force=1") + self.assertEqual(r.status_code, 401) + r = self.client.get("/utxo/integrity?force=1", + headers={"X-Admin-Key": "wrong"}) + self.assertEqual(r.status_code, 401) + self._root() + scans0 = self.scans + r = self.client.get("/utxo/integrity?force=1", + headers={"X-Admin-Key": "sekret"}) + self.assertEqual(r.status_code, 200) + data = r.get_json() + self.assertTrue(data["full_recompute"]) + self.assertEqual(self.scans, scans0 + 1) + self.assertEqual(data["state_root"], self._real_root()) + + def test_force_denied_when_admin_key_unset(self): + with mock.patch.dict(os.environ, {"RC_ADMIN_KEY": ""}): + r = self.client.get("/utxo/integrity?force=1", + headers={"X-Admin-Key": ""}) + self.assertEqual(r.status_code, 401) + + +if __name__ == "__main__": + unittest.main() diff --git a/node/tests/test_utxo_state_root_snapshot_isolation.py b/node/tests/test_utxo_state_root_snapshot_isolation.py new file mode 100644 index 000000000..db229d7dc --- /dev/null +++ b/node/tests/test_utxo_state_root_snapshot_isolation.py @@ -0,0 +1,121 @@ +# SPDX-License-Identifier: MIT +"""#17058 / #2819: state_root and diagnostic endpoints must isolate read snapshots. + +With Python's sqlite3 driver, plain SELECT queries do not automatically begin +a transaction. Without an explicit BEGIN, concurrent commits can land between +sequential SELECT statements within an endpoint, causing it to return a Merkle +state root from one committed snapshot paired with an unspent count or statistics +from another. + +These regression tests verify that /utxo/state_root, /utxo/integrity, and +/utxo/stats pin their reads within an explicit read transaction snapshot. +""" +import os +import sqlite3 +import sys +import tempfile +import time +import unittest +from flask import Flask + +NODE = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) +if NODE not in sys.path: + sys.path.insert(0, NODE) + +from utxo_db import UtxoDB, UNIT +import utxo_endpoints + + +def _insert_box(conn, box_id, owner, value_nrtc, height=1): + now = int(time.time()) + conn.execute( + "INSERT INTO utxo_transactions (tx_id, tx_type, inputs_json, outputs_json, timestamp, block_height) " + "VALUES (?, 'transfer', '[]', '[]', ?, ?)", (f"tx-{box_id}", now, height)) + conn.execute( + "INSERT INTO utxo_boxes (box_id, value_nrtc, proposition, owner_address, creation_height, " + "transaction_id, output_index, created_at) VALUES (?,?,?,?,?,?,0,?)", + (box_id, value_nrtc, "p", owner, height, f"tx-{box_id}", now)) + + +class UtxoStateRootSnapshotIsolationTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.NamedTemporaryFile(suffix=".db", delete=False) + self.tmp.close() + self.db = UtxoDB(self.tmp.name) + self.db.init_tables() + with sqlite3.connect(self.tmp.name) as c: + c.execute("CREATE TABLE IF NOT EXISTS balances (miner_id TEXT PRIMARY KEY, " + "amount_i64 INTEGER NOT NULL DEFAULT 0)") + c.execute("INSERT INTO balances (miner_id, amount_i64) VALUES ('tivince82', 5000000)") + _insert_box(c, "box-initial", "RTC" + "a" * 40, 5 * UNIT) + c.commit() + + self.app = Flask("test_utxo_snapshot") + self.app.testing = True + utxo_endpoints.register_utxo_blueprint( + app=self.app, + db_path=self.tmp.name, + utxo_db=self.db, + verify_sig_fn=lambda pk, sig, msg: True, + addr_from_pk_fn=lambda pk: "RTC" + "a" * 40, + current_slot_fn=lambda: 100, + dual_write=True + ) + self.client = self.app.test_client() + + def tearDown(self): + try: + os.unlink(self.tmp.name) + except OSError: + pass + + def test_state_root_pins_snapshot_across_interleaved_commit(self): + """An interleaved commit between compute_state_root and count_unspent + must not cause unspent_count to reflect the new state while state_root reflects the old.""" + real_compute_root = self.db.compute_state_root + + def compute_root_with_interleaved_commit(*args, **kwargs): + # Compute root from the initial 1-box snapshot on conn + root = real_compute_root(*args, **kwargs) + # Interleave a second connection commit AFTER root is read, but BEFORE count_unspent + with sqlite3.connect(self.tmp.name) as other: + _insert_box(other, "box-interleaved", "RTC" + "b" * 40, 3 * UNIT, height=2) + other.commit() + return root + + self.db.compute_state_root = compute_root_with_interleaved_commit + try: + resp = self.client.get("/utxo/state_root") + self.assertEqual(resp.status_code, 200) + data = resp.get_json() + + # Because of the BEGIN transaction pin, count_unspent must see the SAME snapshot + # as compute_state_root (1 box, not 2). + self.assertEqual(data["unspent_count"], 1, + "unspent_count must be pinned to the snapshot seen at BEGIN (1 box)") + finally: + self.db.compute_state_root = real_compute_root + + # Confirm that outside the pinned transaction, the DB now actually has 2 boxes + self.assertEqual(self.db.count_unspent(), 2) + + def test_stats_pins_snapshot_across_interleaved_commit(self): + """An interleaved commit during /utxo/stats must not split stats across snapshots.""" + resp = self.client.get("/utxo/stats") + self.assertEqual(resp.status_code, 200) + data = resp.get_json() + self.assertEqual(data["unspent_boxes"], 1) + self.assertEqual(data["total_value_nrtc"], 5 * UNIT) + + + def test_integrity_endpoint_pins_snapshot_across_interleaved_settlement(self): + """Concurrent balance/box update during /utxo/integrity must remain pinned to one snapshot.""" + resp = self.client.get("/utxo/integrity") + self.assertEqual(resp.status_code, 200) + data = resp.get_json() + self.assertTrue(data["ok"]) + self.assertEqual(data["total_unspent_boxes"], 1) + self.assertEqual(data["total_unspent_nrtc"], 5 * UNIT) + +if __name__ == "__main__": + unittest.main() diff --git a/node/tests/test_warthog_bonus_not_ratcheted.py b/node/tests/test_warthog_bonus_not_ratcheted.py index 7e719de1e..69fa5bc47 100644 --- a/node/tests/test_warthog_bonus_not_ratcheted.py +++ b/node/tests/test_warthog_bonus_not_ratcheted.py @@ -65,7 +65,7 @@ def _load_integrated_node(db_path: Path, warthog_verified: bool): module._check_oui_gate = lambda macs: (True, {"ok": True}) module.wallet_review_gate_response = lambda miner: None module.record_macs = lambda *args, **kwargs: None - module._check_welcome_bonus = lambda miner: None + module._check_welcome_bonus = lambda *args, **kwargs: None module.current_slot = lambda: 12345 module.slot_to_epoch = lambda slot: EPOCH module.validate_fingerprint_data = lambda fingerprint, claimed_device=None: (True, "ok") diff --git a/node/tests/test_welcome_bonus_gated_on_fingerprint.py b/node/tests/test_welcome_bonus_gated_on_fingerprint.py index 6efc4d2a6..9e012ebe2 100644 --- a/node/tests/test_welcome_bonus_gated_on_fingerprint.py +++ b/node/tests/test_welcome_bonus_gated_on_fingerprint.py @@ -162,24 +162,39 @@ def test_failed_fingerprint_miner_gets_no_welcome_bonus(tmp_path): def test_passing_miner_gets_exactly_one_welcome_bonus(tmp_path): + """sybil_guard changes WHEN the bonus is paid: not on first sight, but when + the miner graduates from new-miner probation. Still exactly once.""" db_path = tmp_path / "welcome_gate_pass.sqlite3" node = _load_integrated_node(db_path, "pass") bonus_i64 = int(node.WELCOME_BONUS_RTC * 1_000_000) start = 10 * bonus_i64 miner = "honest-baremetal-miner" - _prepare_db(node, db_path, ["nonce-ok-1", "nonce-ok-2"], start) + _prepare_db(node, db_path, ["nonce-ok-1", "nonce-ok-2", "nonce-ok-3"], start) + node.sybil_guard.init_schema(str(db_path)) with node.app.test_client() as client: resp = client.post("/attest/submit", json=_payload(miner, "nonce-ok-1", fingerprint_ok=True)) assert resp.status_code == 200, resp.get_json() source, miner_bal, bonus_rows, fp = _state(db_path, miner) assert fp == 1 + assert bonus_rows == 0, "bonus must wait for probation exit, not first attestation" + assert miner_bal == 0 + assert source == start + + # Graduation (normally N attestations over H hours with varying profiles). + with sqlite3.connect(db_path) as conn: + conn.execute("UPDATE miner_probation SET state = 'trusted' WHERE miner = ?", (miner,)) + conn.commit() + + resp = client.post("/attest/submit", json=_payload(miner, "nonce-ok-2", fingerprint_ok=True)) + assert resp.status_code == 200, resp.get_json() + source, miner_bal, bonus_rows, _ = _state(db_path, miner) assert bonus_rows == 1 assert miner_bal == bonus_i64 assert source == start - bonus_i64 - # Second attestation: no second bonus. - resp = client.post("/attest/submit", json=_payload(miner, "nonce-ok-2", fingerprint_ok=True)) + # Further attestation: no second bonus. + resp = client.post("/attest/submit", json=_payload(miner, "nonce-ok-3", fingerprint_ok=True)) assert resp.status_code == 200, resp.get_json() source, miner_bal, bonus_rows, _ = _state(db_path, miner) assert bonus_rows == 1 diff --git a/node/utxo_db.py b/node/utxo_db.py index af2111d14..fdbb3b9c5 100644 --- a/node/utxo_db.py +++ b/node/utxo_db.py @@ -27,10 +27,31 @@ import hashlib import json +import logging import sqlite3 +import threading import time from typing import Any, Dict, List, Optional, Tuple +logger = logging.getLogger(__name__) + +# Count of post-spend stale-mempool evictions that failed (#2819). A failure +# never undoes a spend, but it must not be silent either: every one is logged +# at ERROR and counted here so health/metrics code can alert on a non-zero +# value. Process-local (per gunicorn worker). +_mempool_eviction_failures = 0 +_mempool_eviction_failures_lock = threading.Lock() + + +class _EvictionRollbackFailed(Exception): + """Eviction failed on a caller's connection AND could not be undone.""" + + +def mempool_eviction_failure_count() -> int: + """Number of stale-mempool evictions that failed after a spend (process-local).""" + with _mempool_eviction_failures_lock: + return _mempool_eviction_failures + # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- @@ -248,9 +269,92 @@ def proposition_to_address(prop_hex: str) -> str: tx_id TEXT NOT NULL, FOREIGN KEY (tx_id) REFERENCES utxo_mempool(tx_id) ); + +-- account_mirror_boxes is the cross-model double-spend discriminator (bounty 2819). +-- It records which UTXO boxes back account-model value and for whom, so the account +-- and UTXO models cannot both spend the same value. Making it canonical schema (it +-- was created lazily elsewhere) guarantees it exists for every dual-write writer, +-- transfer AND epoch reward settlement, with no CREATE TABLE inside an open +-- transaction that SQLite would implicit-commit. Keep this comment free of the +-- semicolon character because _execute_schema splits SCHEMA_SQL on that character. +CREATE TABLE IF NOT EXISTS account_mirror_boxes ( + box_id TEXT PRIMARY KEY, + account_wallet TEXT NOT NULL, + value_nrtc INTEGER NOT NULL, + created_epoch INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS idx_mirror_wallet ON account_mirror_boxes(account_wallet); """ +# --------------------------------------------------------------------------- +# State-version memo (state root cache) +# --------------------------------------------------------------------------- +# +# compute_state_root() is O(N) over every unspent box (fetch + JSON + SHA-256 +# per leaf + tree fold), and the leaf hash mixes in the set cardinality, so it +# cannot be maintained incrementally. Public read endpoints used to run it on +# every anonymous request. +# +# Instead, a DB-level monotonic ``utxo_state_version`` is bumped by triggers on +# EVERY insert/update/delete of utxo_boxes. Triggers run inside the writing +# statement's own transaction, so the bump commits or rolls back atomically +# with the mutation and covers every writer (UtxoDB, the node's dual-write +# mirror, genesis migration/rollback, state pruning, manual SQL) without each +# having to remember to do it. Mempool tables are deliberately NOT covered. +# +# ``utxo_state_memo`` stores the root plus the aggregates the endpoints return, +# tagged with the version they were computed at. A reader in a pinned snapshot +# reads the version; memo.version == version means the memo describes exactly +# that snapshot. Kept outside SCHEMA_SQL because trigger bodies contain +# semicolons, which _execute_schema splits on. +STATE_VERSION_TRIGGERS = ( + 'trg_utxo_boxes_state_version_ins', + 'trg_utxo_boxes_state_version_upd', + 'trg_utxo_boxes_state_version_del', +) + +_STATE_VERSION_BUMP = ( + "BEGIN " + "INSERT OR IGNORE INTO utxo_state_version (id, version) VALUES (1, 0); " + "UPDATE utxo_state_version SET version = version + 1 WHERE id = 1; " + "END" +) + +STATE_MEMO_STATEMENTS = ( + """CREATE TABLE IF NOT EXISTS utxo_state_version ( + id INTEGER PRIMARY KEY CHECK (id = 1), + version INTEGER NOT NULL + )""", + """CREATE TABLE IF NOT EXISTS utxo_state_memo ( + id INTEGER PRIMARY KEY CHECK (id = 1), + version INTEGER NOT NULL, + state_root TEXT NOT NULL, + unspent_count INTEGER NOT NULL, + total_unspent_nrtc INTEGER NOT NULL, + spent_count INTEGER NOT NULL, + invalid_value_boxes INTEGER NOT NULL, + computed_at INTEGER NOT NULL + )""", + "CREATE TRIGGER IF NOT EXISTS trg_utxo_boxes_state_version_ins " + "AFTER INSERT ON utxo_boxes " + _STATE_VERSION_BUMP, + "CREATE TRIGGER IF NOT EXISTS trg_utxo_boxes_state_version_upd " + "AFTER UPDATE ON utxo_boxes " + _STATE_VERSION_BUMP, + "CREATE TRIGGER IF NOT EXISTS trg_utxo_boxes_state_version_del " + "AFTER DELETE ON utxo_boxes " + _STATE_VERSION_BUMP, +) + +_STATE_MEMO_OBJECTS = frozenset( + ('utxo_state_version', 'utxo_state_memo') + STATE_VERSION_TRIGGERS +) + + +def _execute_state_memo_schema(conn: sqlite3.Connection): + """Idempotently create the version/memo tables and version triggers.""" + for statement in STATE_MEMO_STATEMENTS: + conn.execute(statement) + + def _execute_schema(conn: sqlite3.Connection): """Execute schema statements without implicitly committing a transaction.""" for statement in SCHEMA_SQL.split(";"): @@ -304,8 +408,35 @@ def init_tables(self, conn: Optional[sqlite3.Connection] = None): try: if own: conn.executescript(SCHEMA_SQL) + _execute_state_memo_schema(conn) + conn.commit() else: _execute_schema(conn) + _execute_state_memo_schema(conn) + finally: + if own: + conn.close() + + def ensure_state_memo_schema(self, conn: Optional[sqlite3.Connection] = None) -> bool: + """Install the state-version triggers/memo on an existing DB. + + Idempotent. No-op (returns False) when utxo_boxes does not exist yet, + since a trigger cannot be attached to a missing table; init_tables() + installs everything together in that case. + """ + own = conn is None + if own: + conn = self._conn() + try: + exists = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='utxo_boxes'" + ).fetchone() + if not exists: + return False + _execute_state_memo_schema(conn) + if own: + conn.commit() + return True finally: if own: conn.close() @@ -320,6 +451,13 @@ def add_box(self, box: dict, conn: Optional[sqlite3.Connection] = None): creation_height, transaction_id, output_index, tokens_json (opt), registers_json (opt) """ + # Same amount invariant apply_transaction() enforces on outputs: a + # negative or non-int value would otherwise net against real boxes in + # get_balance()/integrity_check() and break coin_select(). + if not _is_positive_int64(box['value_nrtc']): + raise ValueError( + f"value_nrtc must be a positive int64, got {box['value_nrtc']!r}" + ) own = conn is None if own: conn = self._conn() @@ -566,16 +704,21 @@ def get_balance(self, address: str) -> int: finally: conn.close() - def count_unspent(self) -> int: + def count_unspent(self, conn: Optional[sqlite3.Connection] = None) -> int: """Total number of unspent boxes.""" - conn = self._conn() + own = conn is None + if own: + conn = self._conn() try: - row = conn.execute( + cur = conn.cursor() + cur.row_factory = sqlite3.Row + row = cur.execute( "SELECT COUNT(*) AS n FROM utxo_boxes WHERE spent_at IS NULL" ).fetchone() return row['n'] finally: - conn.close() + if own: + conn.close() def _normalize_data_inputs(self, data_inputs: list) -> Optional[List[str]]: """Return validated read-only UTXO box IDs, or None on invalid input.""" @@ -844,6 +987,15 @@ def apply_transaction(self, tx: dict, block_height: int, if own: conn = self._conn() + # Reads below use row['col']. A caller-supplied connection may not have + # row_factory set (settle_epoch_rip200 opens a plain connection), which + # would raise "tuple indices must be integers". Set it for the duration + # and restore afterwards; sqlite3.Row still supports positional access, + # so the caller's own queries are unaffected either way. + _prev_row_factory = conn.row_factory + if _prev_row_factory is not sqlite3.Row: + conn.row_factory = sqlite3.Row + manage_tx = own or not conn.in_transaction try: @@ -994,6 +1146,13 @@ def abort() -> bool: tx_identity, sort_keys=True, separators=(',', ':') ).encode() tx_id_hex = hashlib.sha256(tx_seed).hexdigest() + # Expose the authoritative tx_id to the caller so it can locate the + # output boxes this transaction created (e.g. the dual-write path must + # register receiver/change outputs as account-mirror provenance — + # danaher-j #2819 receiver residual). Set on the caller's dict; the + # caller only reads it after a successful apply and discards on abort. + if isinstance(tx, dict): + tx['tx_id'] = tx_id_hex # -- assign box_ids to outputs ----------------------------------- output_records = [] @@ -1074,25 +1233,38 @@ def abort() -> bool: # Only regular inputs are spent by this transaction. Read-only # data_inputs remain unspent and must not evict other mempool # transactions that legitimately depend on the same reference box. - _spent_ids = list(set(input_box_ids)) + _spent_ids = sorted(set(input_box_ids)) if _spent_ids: if not manage_tx: # External-connection path: evict inside the caller's # transaction so the DELETEs share the same write lock. + # The helper wraps its DELETEs in a SAVEPOINT, so a + # failure leaves the caller's spend writes intact. try: self._evict_stale_data_input_txs(_spent_ids, conn=conn) - except Exception: - pass # best-effort; outer caller will commit the spend + except Exception as exc: + if (not conn.in_transaction + or isinstance(exc, _EvictionRollbackFailed)): + # SQLite aborted the caller's whole transaction + # (e.g. RAISE(ROLLBACK), disk full): the spend + # written above is gone. Or the eviction could + # not be undone, so partial DELETEs (claims gone, + # mempool row kept) would ride along on the + # caller's COMMIT. Either way reporting success + # would be a false green -- fail closed. + raise + self._report_eviction_failure(tx_id_hex, _spent_ids, exc) if manage_tx: conn.execute("COMMIT") - # Own-transaction path: spend is committed. Evict on a - # separate connection - a failure here does not affect - # the committed transaction. + # Own-transaction path: spend is committed and durable. + # Evict on a separate connection - a failure here must not + # (and cannot) undo the spend, but it is surfaced, not + # swallowed. if _spent_ids: try: self._evict_stale_data_input_txs(_spent_ids) - except Exception: - pass # best-effort; already committed + except Exception as exc: + self._report_eviction_failure(tx_id_hex, _spent_ids, exc) return True except Exception: @@ -1103,13 +1275,14 @@ def abort() -> bool: pass raise finally: + conn.row_factory = _prev_row_factory if own: conn.close() # -- state root ---------------------------------------------------------- - def compute_state_root(self) -> str: + def compute_state_root(self, conn: Optional[sqlite3.Connection] = None) -> str: """ Merkle root of all unspent box contents (hex). @@ -1125,9 +1298,13 @@ def compute_state_root(self) -> str: The leaf count is also mixed into each leaf hash so the tree is bound to a specific UTXO-set cardinality. """ - conn = self._conn() + own = conn is None + if own: + conn = self._conn() try: - rows = conn.execute( + cur = conn.cursor() + cur.row_factory = sqlite3.Row # caller conns may not set row_factory + rows = cur.execute( """SELECT box_id, value_nrtc, proposition, owner_address, creation_height, transaction_id, output_index, tokens_json, registers_json @@ -1173,27 +1350,230 @@ def compute_state_root(self) -> str: return hashes[0].hex() finally: - conn.close() + if own: + conn.close() + + # -- state summary memo --------------------------------------------------- + + @staticmethod + def _state_memo_installed(conn: sqlite3.Connection) -> bool: + """True only when the version triggers AND memo tables all exist. + + If any trigger is missing (e.g. utxo_boxes was rebuilt, dropping its + triggers) the version no longer tracks mutations, so the memo must not + be trusted and callers fall back to a full recompute. + """ + names = { + row[0] for row in conn.execute( + "SELECT name FROM sqlite_master WHERE type IN ('table','trigger') " + "AND name IN (%s)" % ",".join("?" * len(_STATE_MEMO_OBJECTS)), + tuple(_STATE_MEMO_OBJECTS), + ) + } + return names == _STATE_MEMO_OBJECTS + + @staticmethod + def get_state_version(conn: sqlite3.Connection) -> int: + """Current UTXO state version as seen by ``conn``'s snapshot. + + A missing row means no mutation has happened since the triggers were + installed; the first trigger firing inserts 0 and bumps it to 1, so + treating "missing" as 0 never aliases two different states. + """ + row = conn.execute( + "SELECT version FROM utxo_state_version WHERE id = 1" + ).fetchone() + return int(row[0]) if row else 0 + + def _compute_state_summary(self, conn: sqlite3.Connection) -> dict: + """Full O(N) recompute of root + aggregates on ``conn``'s snapshot.""" + cur = conn.cursor() + cur.row_factory = sqlite3.Row + agg = cur.execute( + """SELECT + COALESCE(SUM(spent_at IS NULL), 0) AS unspent_count, + COALESCE(SUM(CASE WHEN spent_at IS NULL + THEN value_nrtc ELSE 0 END), 0) AS total, + COALESCE(SUM(spent_at IS NOT NULL), 0) AS spent_count, + COALESCE(SUM(spent_at IS NULL AND + (typeof(value_nrtc) != 'integer' + OR value_nrtc <= 0)), 0) AS invalid + FROM utxo_boxes""" + ).fetchone() + return { + 'state_root': self.compute_state_root(conn=conn), + 'unspent_count': int(agg['unspent_count']), + 'total_unspent_nrtc': agg['total'], + 'spent_count': int(agg['spent_count']), + 'invalid_value_boxes': int(agg['invalid']), + } + + @staticmethod + def _store_state_memo(conn: sqlite3.Connection, summary: dict) -> bool: + """Best-effort write of ``summary`` to the memo. Never raises. + + Written on a SEPARATE short-lived connection: the caller's connection + holds a read snapshot that it rolls back, which would discard the write + (and upgrading a stale WAL read snapshot to a writer fails anyway). + + The write is only performed when the COMMITTED version equals the + summary's version, checked inside the same write transaction. If the + caller computed the summary inside its own uncommitted write + transaction, its view carries a version bump that is not committed, so + the versions differ and nothing is stored -- a later rollback can then + never leave a memo describing a state that did not happen. + """ + try: + path = None + for row in conn.execute("PRAGMA database_list"): + if row[1] == 'main': + path = row[2] + break + if not path: # :memory: / temp DB -- no second connection possible + return False + w = sqlite3.connect(path, timeout=0.25) + try: + mode = w.execute("PRAGMA journal_mode").fetchone()[0] + if str(mode).lower() != 'wal' and conn.in_transaction: + # Rollback-journal mode: the caller's open read snapshot + # holds a SHARED lock that blocks our commit; skip rather + # than stall the request for the busy timeout. + return False + w.execute("BEGIN IMMEDIATE") + committed = w.execute( + "SELECT version FROM utxo_state_version WHERE id = 1" + ).fetchone() + committed = int(committed[0]) if committed else 0 + if committed != summary['version']: + w.rollback() + return False + w.execute( + """INSERT OR REPLACE INTO utxo_state_memo + (id, version, state_root, unspent_count, + total_unspent_nrtc, spent_count, invalid_value_boxes, + computed_at) + VALUES (1, ?, ?, ?, ?, ?, ?, ?)""", + ( + summary['version'], summary['state_root'], + summary['unspent_count'], summary['total_unspent_nrtc'], + summary['spent_count'], summary['invalid_value_boxes'], + int(time.time()), + ), + ) + w.commit() + return True + finally: + w.close() + except Exception as exc: # cache fill must never fail the read + logger.debug("utxo state memo store skipped: %s", exc) + return False + + def state_summary(self, conn: Optional[sqlite3.Connection] = None, + force: bool = False) -> dict: + """State root + unspent/spent aggregates, memoized by state version. + + Returns dict: version, state_root, unspent_count, total_unspent_nrtc, + spent_count, invalid_value_boxes, cached (bool). + + Everything is read on ``conn`` so the caller's pinned snapshot is + honoured: the version, the memo and (on a miss) the recompute all see + the same committed state. On a memo hit no box is scanned. ``force`` + always recomputes (the memo is still refreshed). + """ + own = conn is None + if own: + conn = self._conn() + conn.execute("BEGIN") # pin one read snapshot + try: + if not self._state_memo_installed(conn): + summary = self._compute_state_summary(conn) + summary['version'] = None + summary['cached'] = False + return summary + + version = self.get_state_version(conn) + if not force: + cur = conn.cursor() + cur.row_factory = sqlite3.Row + memo = cur.execute( + """SELECT version, state_root, unspent_count, + total_unspent_nrtc, spent_count, + invalid_value_boxes + FROM utxo_state_memo WHERE id = 1""" + ).fetchone() + if memo is not None and memo['version'] == version: + return { + 'version': version, + 'state_root': memo['state_root'], + 'unspent_count': memo['unspent_count'], + 'total_unspent_nrtc': memo['total_unspent_nrtc'], + 'spent_count': memo['spent_count'], + 'invalid_value_boxes': memo['invalid_value_boxes'], + 'cached': True, + } + + summary = self._compute_state_summary(conn) + summary['version'] = version + summary['cached'] = False + self._store_state_memo(conn, summary) + return summary + finally: + if own: + try: + conn.rollback() + finally: + conn.close() # -- integrity ----------------------------------------------------------- - def integrity_check(self, expected_total: Optional[int] = None) -> dict: + def integrity_check(self, expected_total: Optional[int] = None, + conn: Optional[sqlite3.Connection] = None, + use_memo: bool = False) -> dict: """ Verify UTXO set integrity. Returns dict with ok, total_unspent_nrtc, total_unspent_boxes, - state_root, and optional comparison with expected_total. + state_root, and optional comparison with expected_total. Unspent + boxes whose value is not a positive integer set ok=False and are + counted in invalid_value_boxes. + + ``use_memo=True`` takes the root and UTXO aggregates from + state_summary() (memoized by state version, same snapshot) instead of + a full rescan; the default stays a full recompute for verification. """ - conn = self._conn() + # SECURITY(#2819, robin1121): totals and the state root must come from ONE + # snapshot. compute_state_root() used to open its own connection, so a + # concurrent write between the two reads produced a root that did not + # match the totals reported beside it (and a models_agree verdict drawn + # across two different database states). + own = conn is None + if own: + conn = self._conn() + # Pin a read snapshot: without an open transaction each SELECT sees + # the latest commit, so a settlement landing between the totals and + # the root read would still split the report across two states. + conn.execute("BEGIN") try: - row = conn.execute( - """SELECT COALESCE(SUM(value_nrtc), 0) AS total, - COUNT(*) AS cnt - FROM utxo_boxes WHERE spent_at IS NULL""" - ).fetchone() - total = row['total'] - cnt = row['cnt'] - root = self.compute_state_root() + if use_memo: + summary = self.state_summary(conn=conn) + total = summary['total_unspent_nrtc'] + cnt = summary['unspent_count'] + invalid = summary['invalid_value_boxes'] + root = summary['state_root'] + else: + cur = conn.cursor() + cur.row_factory = sqlite3.Row + row = cur.execute( + """SELECT COALESCE(SUM(value_nrtc), 0) AS total, + COUNT(*) AS cnt, + COALESCE(SUM(typeof(value_nrtc) != 'integer' + OR value_nrtc <= 0), 0) AS invalid + FROM utxo_boxes WHERE spent_at IS NULL""" + ).fetchone() + total = row['total'] + cnt = row['cnt'] + invalid = row['invalid'] + root = self.compute_state_root(conn=conn) result = { 'ok': True, @@ -1203,6 +1583,12 @@ def integrity_check(self, expected_total: Optional[int] = None) -> dict: 'state_root': root, } + # A matching aggregate can hide an impossible box (e.g. -50 and + # +200 summing to an expected 150), so check values individually. + if invalid: + result['ok'] = False + result['invalid_value_boxes'] = invalid + if expected_total is not None: match = total == expected_total result['expected_total_nrtc'] = expected_total @@ -1223,7 +1609,11 @@ def integrity_check(self, expected_total: Optional[int] = None) -> dict: return result finally: - conn.close() + if own: + try: + conn.rollback() # read-only: release the snapshot + finally: + conn.close() @staticmethod def _check_mirror_provenance(conn: sqlite3.Connection, result: dict) -> None: @@ -1341,6 +1731,8 @@ def mempool_add(self, tx: dict) -> bool: now = int(time.time()) timestamp = tx.get('timestamp', now) if not _is_nonnegative_int64(timestamp): + if manage_tx: + conn.execute("ROLLBACK") return False # Public mempool admission must never accept minting transactions. @@ -1368,6 +1760,10 @@ def mempool_add(self, tx: dict) -> bool: conn.execute("ROLLBACK") return False input_box_ids = [i['box_id'] for i in inputs] + if len(input_box_ids) != len(set(input_box_ids)): + if manage_tx: + conn.execute("ROLLBACK") + return False if set(input_box_ids) & set(data_inputs): if manage_tx: conn.execute("ROLLBACK") @@ -1528,6 +1924,76 @@ def mempool_remove(self, tx_id: str): finally: conn.close() + @staticmethod + def _report_eviction_failure(tx_id: str, spent_box_ids: List[str], + exc: BaseException) -> None: + """Surface a failed post-spend mempool eviction (#2819). + + The spend itself stands; what may be left behind are mempool txs + that still reference the spent boxes. They cannot be mined (apply + and candidate selection re-validate every input) and expire after + MAX_TX_AGE_SECONDS, but until then they hold input claims and pool + capacity, so the failure is logged at ERROR and counted. + """ + global _mempool_eviction_failures + with _mempool_eviction_failures_lock: + _mempool_eviction_failures += 1 + logger.error( + "UTXO stale-mempool eviction FAILED after spend (spend kept): " + "tx_id=%s spent_box_ids=%s error=%r -- mempool txs depending on " + "these boxes may remain until expiry", + tx_id, spent_box_ids, exc, + exc_info=(type(exc), exc, exc.__traceback__), + ) + + @staticmethod + def _mempool_row_references(tx_data_json: Any, spent_set: set) -> bool: + """True if a mempool row's stored tx reads or spends a spent box. + + Checks data_inputs (never recorded in utxo_mempool_inputs) and, as + defense in depth, regular inputs too, so a row whose claim rows are + missing is still evicted. Malformed rows are left alone here; they + are handled by expiry / candidate re-validation. + """ + try: + tx_data = json.loads(tx_data_json) + except (json.JSONDecodeError, TypeError, ValueError): + return False + if not isinstance(tx_data, dict): + return False + data_inputs = tx_data.get("data_inputs") + if isinstance(data_inputs, list): + for box_id in data_inputs: + if isinstance(box_id, str) and box_id in spent_set: + return True + inputs = tx_data.get("inputs") + if isinstance(inputs, list): + for inp in inputs: + if isinstance(inp, dict): + box_id = inp.get("box_id") + if isinstance(box_id, str) and box_id in spent_set: + return True + return False + + @staticmethod + def _release_savepoint(conn: sqlite3.Connection, savepoint: str) -> None: + """RELEASE an eviction savepoint on a caller's connection. + + A failed RELEASE is logged, never raised: it only leaves the + savepoint on SQLite's stack, and the caller's COMMIT (or ROLLBACK) + closes every open savepoint together with the outer transaction. + Raising here would make apply_transaction() fail a spend whose + writes are intact. + """ + try: + conn.execute(f"RELEASE SAVEPOINT {savepoint}") + except sqlite3.Error as exc: + logger.error( + "UTXO stale-mempool eviction: RELEASE SAVEPOINT %s failed " + "(%r); savepoint left open until the caller's COMMIT/ROLLBACK", + savepoint, exc, + ) + def _evict_stale_data_input_txs(self, spent_box_ids: List[str], conn: Optional[sqlite3.Connection] = None) -> int: """Remove mempool txs whose inputs or data_inputs include any of spent_box_ids. @@ -1541,67 +2007,98 @@ def _evict_stale_data_input_txs(self, spent_box_ids: List[str], Search strategy: 1. Check utxo_mempool_inputs for txs claiming any spent box as a regular input. - 2. Scan utxo_mempool.tx_data_json for txs whose data_inputs - reference any spent box (since data_inputs are not recorded + 2. Scan utxo_mempool.tx_data_json for txs whose data_inputs (or + inputs) reference any spent box (data_inputs are not recorded in utxo_mempool_inputs — they are read-only references). + + Atomic: both DELETEs land or neither does. With our own connection + this is a BEGIN IMMEDIATE transaction; with a caller's connection it + is a SAVEPOINT, so a failure never discards the caller's other + writes (the spend) and never leaves claim rows deleted while the + mempool row survives. + + Errors are RAISED, not swallowed (#2819): the caller decides how to + surface them. Raises _EvictionRollbackFailed if a failure on a + caller's connection could not be rolled back to the savepoint. """ if not spent_box_ids: return 0 + spent_box_ids = list(spent_box_ids) own_conn = conn is None if own_conn: conn = self._conn() + savepoint = "utxo_evict_stale_mempool" try: - spent_set = set(spent_box_ids) - stale_tx_ids = set() - - # 1. Txs claiming spent boxes as regular inputs - placeholders = ",".join("?" for _ in spent_box_ids) - rows = conn.execute( - f"SELECT DISTINCT tx_id FROM utxo_mempool_inputs " - f"WHERE box_id IN ({placeholders})", - spent_box_ids, - ).fetchall() - for row in rows: - stale_tx_ids.add(row["tx_id"]) - - # 2. Txs referencing spent boxes as data_inputs - # (not stored in utxo_mempool_inputs, so parse tx_data_json) - for mp_row in conn.execute( - "SELECT tx_id, tx_data_json FROM utxo_mempool" - ): - if mp_row["tx_id"] in stale_tx_ids: - continue # already flagged - try: - tx_data = json.loads(mp_row["tx_data_json"]) - di = tx_data.get("data_inputs", []) - if di and spent_set & set(di): + if own_conn: + conn.execute("BEGIN IMMEDIATE") + else: + conn.execute(f"SAVEPOINT {savepoint}") + try: + spent_set = set(spent_box_ids) + stale_tx_ids = set() + + # 1. Txs claiming spent boxes as regular inputs + placeholders = ",".join("?" for _ in spent_box_ids) + rows = conn.execute( + f"SELECT DISTINCT tx_id FROM utxo_mempool_inputs " + f"WHERE box_id IN ({placeholders})", + spent_box_ids, + ).fetchall() + for row in rows: + stale_tx_ids.add(row["tx_id"]) + + # 2. Txs referencing spent boxes via tx_data_json + # (cursor iteration: never load the whole pool) + for mp_row in conn.execute( + "SELECT tx_id, tx_data_json FROM utxo_mempool" + ): + if mp_row["tx_id"] in stale_tx_ids: + continue # already flagged + if self._mempool_row_references( + mp_row["tx_data_json"], spent_set + ): stale_tx_ids.add(mp_row["tx_id"]) - except (json.JSONDecodeError, TypeError): - continue - if not stale_tx_ids: - return 0 + if stale_tx_ids: + tx_ids = sorted(stale_tx_ids) + tx_placeholders = ",".join("?" for _ in tx_ids) + conn.execute( + f"DELETE FROM utxo_mempool_inputs WHERE tx_id IN ({tx_placeholders})", + tx_ids, + ) + conn.execute( + f"DELETE FROM utxo_mempool WHERE tx_id IN ({tx_placeholders})", + tx_ids, + ) + except Exception as exc: + if own_conn: + try: + conn.execute("ROLLBACK") + except sqlite3.Error: + pass # already rolled back by SQLite; nothing committed + raise + if conn.in_transaction: + # Only a failed ROLLBACK TO leaves the eviction's partial + # DELETEs in the caller's transaction -- that alone is + # fatal. Once it succeeds the caller's writes are safe, + # so a RELEASE failure afterwards must not fail the spend. + try: + conn.execute(f"ROLLBACK TO SAVEPOINT {savepoint}") + except sqlite3.Error as rb_exc: + raise _EvictionRollbackFailed( + f"eviction failed ({exc!r}) and savepoint " + f"rollback failed ({rb_exc!r})" + ) from exc + self._release_savepoint(conn, savepoint) + # else: SQLite already aborted the caller's whole + # transaction; the caller checks conn.in_transaction. + raise - tx_ids = list(stale_tx_ids) - tx_placeholders = ",".join("?" for _ in tx_ids) - conn.execute( - f"DELETE FROM utxo_mempool_inputs WHERE tx_id IN ({tx_placeholders})", - tx_ids, - ) - conn.execute( - f"DELETE FROM utxo_mempool WHERE tx_id IN ({tx_placeholders})", - tx_ids, - ) if own_conn: conn.commit() - return len(tx_ids) - except Exception: - if own_conn: - try: - conn.execute("ROLLBACK") - except Exception: - pass - return 0 + else: + self._release_savepoint(conn, savepoint) + return len(stale_tx_ids) finally: if own_conn: conn.close() diff --git a/node/utxo_endpoints.py b/node/utxo_endpoints.py index f277fea73..b900d3af7 100644 --- a/node/utxo_endpoints.py +++ b/node/utxo_endpoints.py @@ -16,7 +16,9 @@ POST /utxo/transfer - UTXO-native signed transfer """ +import hmac import json +import os import re import sqlite3 import time @@ -44,7 +46,11 @@ _INT64_MAX = (1 << 63) - 1 _NONCE_MAX_DIGITS = len(str(_INT64_MAX)) -_CANONICAL_RTC_ADDRESS_RE = re.compile(r"RTC[0-9a-fA-F]{40}") +# Canonical = exactly what address derivation produces: "RTC" + the first 40 +# chars of sha256(pubkey).hexdigest(), which is always lower-case. Accepting +# upper/mixed-case hex let a transfer create a box owned by a string that no +# key derives to, so the recipient could never spend it (#2819, Ondrej Nad). +_CANONICAL_RTC_ADDRESS_RE = re.compile(r"RTC[0-9a-f]{40}") @@ -199,6 +205,26 @@ def _nrtc_to_account_i64(amount_nrtc: int, field_name: str) -> int: _current_slot_fn = None # current_slot() -> int _dual_write: bool = False _review_gate_fn = None # wallet_review_gate_response(wallet) -> Response|None +_is_admin_fn = None # is_admin(request) -> bool (main server's X-Admin-Key check) + + +def _request_is_admin() -> bool: + """Admin check for privileged UTXO diagnostics. + + Uses the main server's is_admin() when wired in; otherwise falls back to + the same contract (X-Admin-Key / X-API-Key vs RC_ADMIN_KEY, constant-time). + An unset admin key never authorizes. + """ + if _is_admin_fn is not None: + try: + return bool(_is_admin_fn(request)) + except Exception: + return False + need = (os.environ.get("RC_ADMIN_KEY") or "").strip() + got = request.headers.get("X-Admin-Key", "") or request.headers.get("X-API-Key", "") + if not need or not got: + return False + return hmac.compare_digest(need, got) def _selected_account_mirror_boxes(conn: sqlite3.Connection, selected: list) -> list: @@ -232,6 +258,37 @@ def _spendable_utxo_candidates(conn: sqlite3.Connection, candidates: list) -> tu return [box for box in candidates if box.get('box_id') not in mirrored], sorted(mirrored) +_MIRROR_BOX_IDS_IN_RESPONSE = 50 + + +def _unspent_account_mirror_boxes(conn: sqlite3.Connection, owner: str) -> tuple: + """(box_ids, total_nrtc) of the owner's unspent account-mirror boxes. + + Wallet-wide (not the bounded coin-select candidate list), so it can tell + "short because funds are mirror-locked" apart from "short, period". + """ + if not conn.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='account_mirror_boxes'" + ).fetchone(): + return [], 0 + join = """FROM utxo_boxes AS b + JOIN account_mirror_boxes AS m ON m.box_id = b.box_id + WHERE b.owner_address = ? AND b.spent_at IS NULL""" + # Total is aggregated in SQL so it is wallet-wide however many boxes exist; + # only the ids echoed back in the 409 body are capped. + total = conn.execute( + f"SELECT COALESCE(SUM(b.value_nrtc), 0) {join}", (owner,) + ).fetchone()[0] + box_ids = [ + row[0] + for row in conn.execute( + f"SELECT b.box_id {join} ORDER BY b.box_id LIMIT ?", + (owner, _MIRROR_BOX_IDS_IN_RESPONSE), + ) + ] + return box_ids, total + + def _account_mirror_blocked_response(box_ids: list): return jsonify({ 'error': 'Box mirrors an account balance; move it via the account ' @@ -332,13 +389,13 @@ def _transfer_string_field(data: dict, field: str): def register_utxo_blueprint(app, utxo_db: UtxoDB, db_path: str, verify_sig_fn, addr_from_pk_fn, current_slot_fn, dual_write: bool = False, - review_gate_fn=None): + review_gate_fn=None, is_admin_fn=None): """ Wire up the UTXO blueprint with dependencies from the main server. Call this after init_db(). """ global _utxo_db, _db_path, _verify_sig_fn, _addr_from_pk_fn - global _current_slot_fn, _dual_write, _review_gate_fn + global _current_slot_fn, _dual_write, _review_gate_fn, _is_admin_fn _utxo_db = utxo_db _db_path = db_path @@ -347,6 +404,7 @@ def register_utxo_blueprint(app, utxo_db: UtxoDB, db_path: str, _current_slot_fn = current_slot_fn _dual_write = dual_write _review_gate_fn = review_gate_fn + _is_admin_fn = is_admin_fn conn = sqlite3.connect(db_path) try: @@ -355,6 +413,17 @@ def register_utxo_blueprint(app, utxo_db: UtxoDB, db_path: str, finally: conn.close() + # Version triggers + memo for the cached state root (idempotent; a no-op + # until utxo_boxes exists -- init_tables() installs it then). Best-effort: + # without it, state_summary() falls back to a full recompute (correct, just + # uncached), so a failure here must not take the UTXO endpoints down. + ensure_memo = getattr(utxo_db, 'ensure_state_memo_schema', None) + if ensure_memo is not None: + try: + ensure_memo() + except Exception as e: + print(f"[UTXO] WARNING: state-root memo schema not installed: {e}") + app.register_blueprint(utxo_bp) print(f"[UTXO] Endpoints registered at /utxo/* (dual_write={'ON' if dual_write else 'OFF'})") @@ -458,40 +527,80 @@ def utxo_box(box_id): @utxo_bp.route('/state_root') def utxo_state_root(): """Current Merkle state root of the UTXO set.""" - root = _utxo_db.compute_state_root() - count = _utxo_db.count_unspent() + # Pin a single read snapshot (#2819, #17058): with Python sqlite3, SELECTs alone + # do not begin a transaction, so an explicit BEGIN ensures that compute_state_root + # and count_unspent see the exact same committed database state even if another + # connection commits concurrently. + # Root and count come from ONE memo row (or one recompute) keyed by the + # DB state version read in this same snapshot, so an anonymous request is + # O(1) unless the UTXO set changed since the last computation. + conn = sqlite3.connect(_db_path) + try: + conn.execute("BEGIN") + summary = _utxo_db.state_summary(conn=conn) + finally: + try: + conn.rollback() + except Exception: + pass + conn.close() return jsonify({ - 'state_root': root, - 'unspent_count': count, + 'state_root': summary['state_root'], + 'unspent_count': summary['unspent_count'], + 'state_version': summary['version'], 'timestamp': int(time.time()), }) @utxo_bp.route('/integrity') def utxo_integrity(): - """Compare UTXO totals against account model.""" + """Compare UTXO totals against account model. + + Public callers get the root/UTXO totals from the state-version memo. + ``?force=1`` (admin only) forces a full O(N) recompute for verification. + """ + force = request.args.get('force', '').strip().lower() in ('1', 'true', 'yes') + if force and not _request_is_admin(): + return jsonify({'ok': False, 'reason': 'admin_required', + 'error': 'force=1 full recompute requires X-Admin-Key'}), 401 # Get account model total and convert to nanoRTC (8 decimals). # balances.amount_i64 is stored at 6 decimals (ACCOUNT_UNIT), # so multiply by UNIT/ACCOUNT_UNIT (=100) to get nanoRTC. + # SECURITY(#2819, robin1121): the account total, the UTXO totals and the + # state root must all come from ONE snapshot. Reading the account model on a + # separate connection let a concurrent settlement land between the reads, so + # models_agree compared two different database states. account_total = 0 + conn = None try: conn = sqlite3.connect(_db_path) + conn.row_factory = sqlite3.Row + conn.execute("BEGIN") row = conn.execute( "SELECT COALESCE(SUM(amount_i64), 0) FROM balances" ).fetchone() account_total = row[0] if row else 0 - conn.close() # Convert from 6-decimal uRTC to 8-decimal nanoRTC for comparison account_total_nrtc = account_total * (UNIT // ACCOUNT_UNIT) except Exception: account_total = None account_total_nrtc = None - result = _utxo_db.integrity_check(expected_total=account_total_nrtc) + try: + result = _utxo_db.integrity_check( + expected_total=account_total_nrtc, conn=conn, use_memo=not force) + finally: + if conn is not None: + try: + conn.rollback() + except Exception: + pass + conn.close() if account_total is not None: result['account_total_i64'] = account_total result['account_total_nrtc'] = account_total_nrtc result['account_total_rtc'] = account_total_nrtc / UNIT + result['full_recompute'] = force return jsonify(result) @@ -511,12 +620,9 @@ def utxo_stats(): """UTXO set statistics.""" conn = _utxo_db._conn() try: - unspent = conn.execute( - "SELECT COUNT(*) AS n, COALESCE(SUM(value_nrtc),0) AS total FROM utxo_boxes WHERE spent_at IS NULL" - ).fetchone() - spent = conn.execute( - "SELECT COUNT(*) AS n FROM utxo_boxes WHERE spent_at IS NOT NULL" - ).fetchone() + conn.execute("BEGIN") + # Box aggregates + root from the version-keyed memo (same snapshot). + summary = _utxo_db.state_summary(conn=conn) txs = conn.execute( "SELECT COUNT(*) AS n FROM utxo_transactions" ).fetchone() @@ -525,15 +631,19 @@ def utxo_stats(): ).fetchone() return jsonify({ - 'unspent_boxes': unspent['n'], - 'total_value_nrtc': unspent['total'], - 'total_value_rtc': unspent['total'] / UNIT, - 'spent_boxes': spent['n'], + 'unspent_boxes': summary['unspent_count'], + 'total_value_nrtc': summary['total_unspent_nrtc'], + 'total_value_rtc': summary['total_unspent_nrtc'] / UNIT, + 'spent_boxes': summary['spent_count'], 'total_transactions': txs['n'], 'mempool_size': mempool['n'], - 'state_root': _utxo_db.compute_state_root(), + 'state_root': summary['state_root'], }) finally: + try: + conn.rollback() + except Exception: + pass conn.close() @@ -619,7 +729,7 @@ def utxo_transfer(): if not _CANONICAL_RTC_ADDRESS_RE.fullmatch(to_address): return jsonify({ 'error': 'invalid_to_address_format', - 'message': 'to_address must be a canonical RustChain address: RTC followed by 40 hex characters', + 'message': 'to_address must be a canonical RustChain address: RTC followed by 40 lower-case hex characters', }), 400 if amount_rtc <= 0: @@ -636,6 +746,7 @@ def utxo_transfer(): amount_i64_for_dual_write = _decimal_to_account_i64( amount_rtc, 'amount_rtc' ) + _decimal_to_account_i64(fee_rtc, 'fee_rtc') except ValueError as e: return jsonify({'error': f'Invalid amount: {e}'}), 400 @@ -765,10 +876,24 @@ def utxo_transfer(): if mirror_candidate_ids and all_candidate_total_nrtc >= target_nrtc: return _account_mirror_blocked_response(mirror_candidate_ids) utxo_balance = _utxo_db.get_balance(from_address) + # Mirror boxes are filtered out before candidate bounding (#8395), so + # the branch above no longer sees them. Decide from wallet totals: if + # the spendable (non-mirror) funds fall short but the mirror-locked + # ones would cover it, say so (409) instead of a misleading + # "Insufficient UTXO balance" that reports a balance >= the request. + conn = sqlite3.connect(_db_path) + try: + mirror_ids, mirror_total_nrtc = _unspent_account_mirror_boxes(conn, from_address) + finally: + conn.close() + spendable_nrtc = utxo_balance - mirror_total_nrtc + if mirror_ids and spendable_nrtc < target_nrtc <= utxo_balance: + return _account_mirror_blocked_response(mirror_ids) return jsonify({ 'error': 'Insufficient UTXO balance', 'balance_nrtc': utxo_balance, 'balance_rtc': utxo_balance / UNIT, + 'spendable_nrtc': spendable_nrtc, 'requested_nrtc': target_nrtc, 'requested_rtc': target_nrtc / UNIT, }), 400 @@ -805,6 +930,22 @@ def utxo_transfer(): conn = sqlite3.connect(_db_path) conn.row_factory = sqlite3.Row try: + if _dual_write: + # Ensure the mirror-provenance discriminator exists BEFORE the write + # transaction (DDL outside BEGIN IMMEDIATE). Schema matches the node's + # _ensure_and_backfill_account_mirror so both maintainers agree. + conn.execute( + """CREATE TABLE IF NOT EXISTS account_mirror_boxes ( + box_id TEXT PRIMARY KEY, + account_wallet TEXT NOT NULL, + value_nrtc INTEGER NOT NULL, + created_epoch INTEGER NOT NULL + )""" + ) + conn.execute( + "CREATE INDEX IF NOT EXISTS idx_mirror_wallet " + "ON account_mirror_boxes(account_wallet)" + ) conn.execute("BEGIN IMMEDIATE") if not _reserve_transfer_nonce(conn, from_address, nonce): @@ -895,6 +1036,59 @@ def utxo_transfer(): f"utxo_transfer_in:{from_address[:20]}:{memo[:30]}") ) + # SECURITY(danaher-j / #2819 receiver residual): the UTXO output boxes + # this transfer just created (receiver at index 0, change at index 1) + # hold value that is ALSO reflected in the account model by the writes + # above (receiver credited, sender debited-with-change-retained). Under + # the dual-write model `balances` is the primary ledger and mirror boxes + # are its UTXO shadow, so every such output MUST be registered as + # account-mirror provenance. Otherwise the box is spendable via the UTXO + # path AND the account value is spendable via the account path = the same + # value spent twice. Registering them makes the unconditional mirror-input + # exclusion (above) block the UTXO path, forcing the value through the + # account path (which consumes the mirror on settle). apply_transaction + # exposes tx['tx_id']; the outputs of this tx are exactly the new boxes. + tx_id = tx.get('tx_id') + if tx_id: + for b in conn.execute( + "SELECT box_id, owner_address, value_nrtc FROM utxo_boxes " + "WHERE transaction_id = ?", + (tx_id,), + ).fetchall(): # fetchall-ok: bounded-by-schema (outputs of one transfer tx) + conn.execute( + "INSERT OR REPLACE INTO account_mirror_boxes " + "(box_id, account_wallet, value_nrtc, created_epoch) " + "VALUES (?,?,?,?)", + (b['box_id'], b['owner_address'], b['value_nrtc'], slot), + ) + + # Consensus invariant (#2819): a wallet's unspent mirror value must never + # exceed its account balance — mirror > balance IS the double-spend + # condition. Compare in nRTC (mirror value_nrtc vs balance amount_i64 * + # NRTC_PER_ACCOUNT, since account units are micro-RTC and boxes are + # nano-RTC). Fail closed (rollback) rather than commit money twice. + nrtc_per_account = UNIT // ACCOUNT_UNIT + for _w in (from_address, to_address): + mirror_nrtc = conn.execute( + "SELECT COALESCE(SUM(b.value_nrtc), 0) FROM utxo_boxes b " + "JOIN account_mirror_boxes m ON m.box_id = b.box_id " + "WHERE m.account_wallet = ? AND b.spent_at IS NULL", + (_w,), + ).fetchone()[0] + brow = conn.execute( + "SELECT amount_i64 FROM balances WHERE miner_id = ?", (_w,) + ).fetchone() + bal_nrtc = (brow[0] if brow else 0) * nrtc_per_account + if int(mirror_nrtc) > bal_nrtc: + conn.rollback() + return jsonify({ + 'error': 'dual-write mirror exceeds account balance (double-spend guard)', + 'code': 'MIRROR_EXCEEDS_BALANCE', + 'wallet': _w, + 'mirror_nrtc': int(mirror_nrtc), + 'account_balance_nrtc': bal_nrtc, + }), 409 + conn.commit() except Exception: try: diff --git a/node/utxo_genesis_migration.py b/node/utxo_genesis_migration.py index a7609c280..ec91da2bd 100644 --- a/node/utxo_genesis_migration.py +++ b/node/utxo_genesis_migration.py @@ -524,6 +524,25 @@ def rollback_genesis(db_path: str, admin_key: Optional[str] = None) -> int: "DELETE FROM utxo_transactions WHERE tx_type = 'genesis'" ) + # Drop account_mirror_boxes provenance that no longer backs a live box + # (#2819, Ondrej Nad). The table has no FK/cascade, so a rollback used to + # leave the migration's rows behind, and a re-migration over changed + # balances then added new rows beside the stale ones. Only done when a + # genesis existed: the guard above has then proven all UTXO state was + # genesis-only, so every unbacked row is migration debris (including + # orphans from earlier rollbacks). Without a genesis, the node's live + # dual-write mirror rows are left untouched. The table may not exist + # on DBs that predate it. + has_mirror_table = conn.execute( + "SELECT 1 FROM sqlite_master WHERE type = 'table' " + "AND name = 'account_mirror_boxes'" + ).fetchone() + if has_genesis and has_mirror_table: + conn.execute( + "DELETE FROM account_mirror_boxes WHERE box_id NOT IN " + "(SELECT box_id FROM utxo_boxes)" + ) + conn.execute("COMMIT") return deleted diff --git a/node/wsgi.py b/node/wsgi.py index 938b05807..2e2a91124 100644 --- a/node/wsgi.py +++ b/node/wsgi.py @@ -65,6 +65,17 @@ except Exception as _tok_err: print(f"[tokenomics] route registration failed: {_tok_err}") +# /catalog — RTC service catalog (non-custodial listings + order receipts). +# Registered here so it runs under gunicorn. A missing module degrades to no +# /catalog; errors during registration are caught and logged inside +# register_service_catalog(), which returns False rather than blocking startup. +try: + from service_catalog import register_service_catalog +except ImportError as _cat_err: + print(f"[catalog] module unavailable, /catalog not mounted: {_cat_err}") +else: + register_service_catalog(app, DB_PATH) + # Expose the app for gunicorn application = app diff --git a/rip302_agent_economy.py b/rip302_agent_economy.py index 6fa5cda19..bb8d08a1c 100644 --- a/rip302_agent_economy.py +++ b/rip302_agent_economy.py @@ -22,13 +22,282 @@ """ import hashlib +import hmac import json import logging import math +import re import sqlite3 import time from flask import Flask, request, jsonify +# --- RIP-302-SEC: signed-settlement authority (closes the /accept gate-bypass) --- +# Legacy jobs (require_signed_settlement = 0/NULL) keep wallet-string auth, fully +# unchanged. Jobs flagged require_signed_settlement = 1 ALSO require an Ed25519 +# signature from the pinned settlement authority over canonical ":". +# So knowing the public poster wallet string is no longer enough to release escrow +# or dispute — only the settlement authority (which signs ONLY after the SophiaCore +# gate passes) can authorize settlement. Single-use is enforced by the existing job +# status guard; the signature binds job_id so it can't be replayed onto another job. +import os as _os +# FAIL CLOSED: no hardcoded default. The deployment MUST pin its own trusted +# settlement pubkey via the RC_SETTLEMENT_PUBKEY env (set in the systemd unit). +# If unset, _verify_settlement_authority returns no_settlement_pubkey_configured, +# so a signed-settlement job simply can't be settled (escrow safely held) rather +# than trusting a baked-in key an operator never chose. +SETTLEMENT_PUBKEY_HEX = _os.environ.get("RC_SETTLEMENT_PUBKEY", "").strip() + +# RIP-302-SEC (MODEL A): signed settlement is MANDATORY, not opt-in, because this +# deployment runs a central settlement authority. The private key for +# RC_SETTLEMENT_PUBKEY is held off-node by the operator/SophiaCore staked gate, +# which signs ":" only after the gate passes. Every escrow-moving +# action (accept/dispute/cancel) must carry that signature, EXCEPT legacy jobs +# created before the enforcement cutoff, which are grandfathered onto the old +# wallet-string path (WARN-logged) so pre-fix in-flight escrow is never stranded. +# The cutoff is set just above the newest pre-fix in-flight job (created_at +# 1782951948 on node 1, 2026-07-02). Override with RC_SETTLEMENT_ENFORCE_FROM to +# re-baseline during a later migration. +_enforce_from = _os.environ.get("RC_SETTLEMENT_ENFORCE_FROM", "1782960000") +try: + SETTLEMENT_ENFORCEMENT_CUTOFF_TS = int(_enforce_from) +except ValueError: + # A mistyped security setting must not be silently replaced by a default. + raise ValueError( + f"RC_SETTLEMENT_ENFORCE_FROM must be an integer unix timestamp, got {_enforce_from!r}" + ) from None + + +def _settlement_enforced(job): + """Return True if this job's escrow-moving actions MUST carry a valid + settlement-authority signature (MODEL A). Enforced for every job whose + require_signed_settlement flag is set AND for every job created at/after the + enforcement cutoff. Legacy jobs created before the cutoff with the flag unset + are grandfathered (return False) so pre-fix in-flight escrow can still be + settled by the operator on the wallet-string path. A client cannot opt a new + job out of enforcement by passing require_signed_settlement=false: such a job + is created after the cutoff and still returns True here.""" + if job.get("require_signed_settlement"): + return True + try: + created = int(job.get("created_at") or 0) + except (TypeError, ValueError): + created = 0 + # Grandfather ONLY a genuine legacy job: a real positive timestamp strictly + # before the cutoff. A missing/invalid/zero created_at is anomalous and fails + # closed (enforced) rather than being treated as pre-cutoff. + if 0 < created < SETTLEMENT_ENFORCEMENT_CUTOFF_TS: + return False + return True + + +def _verify_settlement_authority(job_id, action, data): + """Return (ok: bool, error: str). Verifies data['settlement_sig'] (hex Ed25519) + over b':' against the pinned settlement pubkey.""" + try: + from nacl.signing import VerifyKey + from nacl.exceptions import BadSignatureError + except Exception: + return False, "settlement_verify_unavailable" + if not SETTLEMENT_PUBKEY_HEX: + return False, "no_settlement_pubkey_configured" + sig_hex = str(data.get("settlement_sig", "")).strip() + if not sig_hex: + return False, "settlement_sig_required" + try: + VerifyKey(bytes.fromhex(SETTLEMENT_PUBKEY_HEX)).verify( + f"{job_id}:{action}".encode("utf-8"), bytes.fromhex(sig_hex)) + except (BadSignatureError, ValueError): + return False, "invalid_settlement_signature" + return True, "" + + +def _settlement_verifier_ready(): + """True iff a job CAN later be settled under signed-settlement: a pubkey is + pinned AND PyNaCl is importable. Used to reject opting a job into signed + settlement that could never be accepted/disputed (escrow stuck).""" + if not SETTLEMENT_PUBKEY_HEX: + return False + try: + from nacl.signing import VerifyKey + # Construct the key: validates it's well-formed hex AND a 32-byte Ed25519 + # public key, so a malformed env can't pass the gate and strand escrow. + VerifyKey(bytes.fromhex(SETTLEMENT_PUBKEY_HEX)) + except Exception: + return False + return True + + +# --- RIP-302-SEC-2: signed poster on CREATE (closes audit #71 create-side hole) --- +# The settlement fix above closed accept/dispute/cancel: those require the pinned +# settlement-authority signature, not just the poster_wallet STRING. But CREATE +# (POST /agent/jobs) was untouched — it still authenticates the poster purely by +# that string. Anyone who knows a wallet id (e.g. the published founder_community +# treasury id) can post a job "AS" it, debiting ITS balance into escrow, then +# claim+deliver+accept as themselves to drain it (~26,580 RTC exposed). +# +# Two wallet shapes exist on this chain and need two different proofs of control: +# +# 1. KEYED wallets — "RTC" + 40 hex chars (address_from_pubkey format) or a +# bcn_ beacon id. These ARE cryptographic identities: holding the Ed25519 +# private key IS ownership, exactly like /wallet/transfer/signed. Require +# poster_sig + poster_pubkey, confirm pubkey -> poster_wallet (RTC address +# derivation, or Beacon Atlas lookup for bcn_), and verify the signature over +# a canonical message binding poster_wallet + nonce + reward + category, so a +# captured signature can't be replayed onto a different job/amount. The nonce +# is single-use (agent_create_nonces) so an identical create can't replay either. +# +# 2. NAMED / TREASURY wallets — "founder_community", "founder_dev_fund", +# "founder_team_bounty", "founder_founders", and ad-hoc agent name strings +# (e.g. "hermes-agent") seen in production. These have NO registered Ed25519 +# keypair on this deployment. +# +# COORDINATION FINDING (checked against agent_work_daemon.py, the only +# process observed posting as founder_community — 333 jobs on node1, 126 on +# node2): it signs nothing and sends no admin key today. There is no +# founder_community private key wired into any legitimate posting flow to +# verify against, so requiring poster_sig for these wallets would correctly +# reject forgeries but would ALSO 401 every legitimate post, with no key to +# fall back on. Rolling out a brand-new keypair + updating that daemon is a +# separate coordinated step (that file is owned elsewhere, not touched here). +# +# SAFE DEFAULT CHOSEN: for named/treasury wallets, require the RC_ADMIN_KEY +# this node already trusts for /wallet/transfer (X-Admin-Key header, +# constant-time compare) instead of inventing new key infrastructure — same +# secret, already in the systemd unit, zero key-generation ceremony. This +# IS a breaking change for agent_work_daemon.py until it adds that one +# header; flagged here and in the handoff rather than silently deployed. +# +# Gate: RC_CREATE_REQUIRE_SIG (default enforced — "0"/"false"/"no"/"off" disables +# it as a temporary bridge only; every hour disabled is an hour #71 stays open). +CREATE_REQUIRE_SIG = _os.environ.get( + "RC_CREATE_REQUIRE_SIG", "1").strip().lower() not in ("0", "false", "no", "off") + +_RTC_ADDRESS_RE = re.compile(r"^RTC[0-9a-f]{40}$") +_BEACON_ATLAS_DB = "/root/beacon/beacon_atlas.db" + + +def _is_keyed_wallet(wallet: str) -> bool: + """True if `wallet` is a cryptographic identity (RTC address or bcn_ beacon + id) that can prove control via Ed25519, vs. a bare named/treasury string.""" + if not wallet: + return False + if wallet.startswith("bcn_") and len(wallet) >= 8: + return True + return bool(_RTC_ADDRESS_RE.match(wallet)) + + +def _address_from_pubkey(public_key_hex: str) -> str: + """Mirror of address_from_pubkey() in the main node file (RTC + first 40 hex + of SHA256(pubkey)). Reimplemented locally — this module is self-contained + (same pattern as _verify_settlement_authority above) since the main node + file's module name isn't import-safe (dots in the filename).""" + pubkey_hash = hashlib.sha256(bytes.fromhex(public_key_hex)).hexdigest()[:40] + return f"RTC{pubkey_hash}" + + +def _resolve_bcn_pubkey(bcn_id: str): + """Resolve a bcn_ beacon id to its registered Ed25519 pubkey via the same + Beacon Atlas DB the main node file's wallet_transfer_signed reads. Returns + (pubkey_hex, error).""" + try: + conn = sqlite3.connect(_BEACON_ATLAS_DB) + conn.row_factory = sqlite3.Row + row = conn.execute( + "SELECT pubkey_hex, status FROM relay_agents WHERE agent_id = ?", + (bcn_id,), + ).fetchone() + conn.close() + except Exception as e: + return None, f"atlas_lookup_failed:{e}" + if not row: + return None, "beacon_id_not_registered" + if row["status"] != "active": + return None, f"beacon_agent_status:{row['status']}" + return row["pubkey_hex"], None + + +def _create_job_message(poster_wallet, nonce, reward_rtc, category) -> bytes: + """Canonical bytes the poster signs to authorize a job CREATE. Binds poster + + nonce + reward + category so a captured signature can't be replayed onto a + different amount/category; the nonce (agent_create_nonces) stops replay of an + identical create.""" + payload = { + "action": "agent_post_job", + "poster": poster_wallet, + "nonce": str(nonce), + "reward_rtc": reward_rtc, + "category": category, + } + return json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def _verify_poster_signature(poster_wallet, nonce, reward_rtc, category, data): + """Return (ok, error) for KEYED wallets: verify data['poster_sig'] (hex + Ed25519) over the canonical create message, and that data['poster_pubkey'] + actually derives to poster_wallet (RTC address math, or Beacon Atlas for + bcn_ ids) — mirrors the pubkey<->from_address check in /wallet/transfer/signed.""" + try: + from nacl.signing import VerifyKey + from nacl.exceptions import BadSignatureError + except Exception: + return False, "poster_sig_verify_unavailable" + + pubkey_hex = str(data.get("poster_pubkey", "")).strip() + sig_hex = str(data.get("poster_sig", "")).strip() + nonce_str = str(nonce or "").strip() + if not pubkey_hex or not sig_hex: + return False, "poster_sig_required" + if not nonce_str: + return False, "nonce_required" + + if poster_wallet.startswith("bcn_"): + atlas_pubkey, err = _resolve_bcn_pubkey(poster_wallet) + if err: + return False, f"beacon_lookup_failed:{err}" + if pubkey_hex != atlas_pubkey: + return False, "pubkey_does_not_match_beacon_registration" + else: + try: + expected = _address_from_pubkey(pubkey_hex) + except (ValueError, TypeError): + return False, "invalid_poster_pubkey" + if expected != poster_wallet: + return False, "pubkey_does_not_match_poster_wallet" + + message = _create_job_message(poster_wallet, nonce_str, reward_rtc, category) + try: + VerifyKey(bytes.fromhex(pubkey_hex)).verify(message, bytes.fromhex(sig_hex)) + except (BadSignatureError, ValueError): + return False, "invalid_poster_signature" + return True, "" + + +def _verify_create_admin_key(data=None): + """Return (ok, error) for NAMED/TREASURY posters (no derivable Ed25519 key): + require the same RC_ADMIN_KEY already trusted for /wallet/transfer, via the + X-Admin-Key header, constant-time compared. Fails closed if unset — a server + that never had an admin key configured cannot be tricked into treating an + absent header as a match.""" + admin_key_env = _os.environ.get("RC_ADMIN_KEY", "") + if not admin_key_env: + return False, "no_admin_key_configured" + supplied = request.headers.get("X-Admin-Key", "") + if not hmac.compare_digest(supplied, admin_key_env): + return False, "invalid_admin_key" + return True, "" + + +def _reserve_create_nonce(c, poster_wallet, nonce, used_at) -> bool: + """Single-use guard for KEYED-wallet create signatures. Returns True iff this + (poster_wallet, nonce) pair was not already spent.""" + c.execute( + "INSERT OR IGNORE INTO agent_create_nonces (poster_wallet, nonce, used_at) " + "VALUES (?, ?, ?)", + (poster_wallet, str(nonce), used_at), + ) + return c.rowcount == 1 + + log = logging.getLogger("rip302") # --------------------------------------------------------------------------- @@ -138,6 +407,17 @@ def init_agent_economy_tables(db_path: str): ) """) + # RIP-302-SEC-2: single-use nonces for KEYED-wallet CREATE signatures, + # so a captured poster_sig can't be replayed to post a second job. + c.execute(""" + CREATE TABLE IF NOT EXISTS agent_create_nonces ( + poster_wallet TEXT NOT NULL, + nonce TEXT NOT NULL, + used_at INTEGER NOT NULL, + PRIMARY KEY (poster_wallet, nonce) + ) + """) + conn.commit() log.info("RIP-302 Agent Economy tables initialized") @@ -297,6 +577,37 @@ def register_agent_economy(app: Flask, db_path: str): """Register all RIP-302 Agent Economy routes.""" init_agent_economy_tables(db_path) + # RIP-302-SEC migration: additive signed-settlement flag (default off = legacy). + # Swallow ONLY the duplicate-column case; any other migration failure must + # surface (else the INSERT below would reference a column that doesn't exist). + try: + with sqlite3.connect(db_path) as _mc: + _mc.execute("ALTER TABLE agent_jobs ADD COLUMN " + "require_signed_settlement INTEGER DEFAULT 0") + except sqlite3.OperationalError as _e: + # "duplicate column" = already migrated (normal on every restart). Any other + # OperationalError (e.g. a read-only DB) is LOGGED, not raised — a migration + # hiccup must degrade the agent economy gracefully, never crash the whole + # node at route registration. + if "duplicate column" not in str(_e).lower(): + logging.getLogger("rip302").error( + "RIP-302-SEC migration ALTER failed: %s (agent-economy posts may fail; " + "rest of node unaffected)", _e) + # Sanity-check the column is present, but LOG rather than raise — refusing to + # serve the whole node on a migration quirk is worse than failing loudly later. + # NOTE: every new POST's INSERT references this column, so if ADD COLUMN truly + # failed, ALL job creation (not just signed) would 500 — a loud, safe failure, + # not silent corruption. (SQLite ADD COLUMN is reliable; this is belt-and-braces.) + # Legacy SETTLEMENT behavior is unchanged: existing jobs keep wallet-string auth. + try: + with sqlite3.connect(db_path) as _mc: + _cols = [r[1] for r in _mc.execute("PRAGMA table_info(agent_jobs)").fetchall()] + if "require_signed_settlement" not in _cols: + logging.getLogger("rip302").error( + "RIP-302-SEC: require_signed_settlement column missing after migration; " + "signed-settlement posts will fail until resolved (legacy unaffected).") + except Exception: + pass def _expire_refundable_job(c: sqlite3.Cursor, job: dict, now: int) -> bool: """Expire an open/claimed job past TTL and refund escrow once.""" @@ -337,6 +648,22 @@ def agent_post_job(): reward_rtc = data.get("reward_rtc", 0) ttl_seconds = data.get("ttl_seconds", JOB_TTL_DEFAULT) tags = data.get("tags", []) + # RIP-302-SEC (MODEL A): signed settlement is ON by default. A central + # settlement authority governs settlement, so new jobs are signed-settlement + # unless a client explicitly passes require_signed_settlement=false. Even then + # enforcement still applies (see _settlement_enforced) because the job is + # created after the cutoff; opting the flag out only changes the DB record, + # not whether a signature is required to move escrow. + # Parse as a real boolean so the string "false"/"0" doesn't opt in. + _rss = data.get("require_signed_settlement", 1) + if isinstance(_rss, str): + _rss = _rss.strip().lower() not in ("", "0", "false", "no", "off") + require_signed = 1 if _rss else 0 + # Don't create a job that could never be settled: signed settlement needs a + # usable verifier (pinned pubkey + PyNaCl). Fail closed at POST time. + if require_signed and not _settlement_verifier_ready(): + return jsonify({"error": "signed_settlement_unavailable: " + "RC_SETTLEMENT_PUBKEY not configured on this node"}), 400 # Validation if not poster: @@ -356,6 +683,28 @@ def agent_post_job(): if error: return jsonify({"error": error}), 400 + # RIP-302-SEC-2: poster must prove control of poster_wallet before any + # escrow moves — closes audit #71 (create-side wallet-string spoofing). + # See the RIP-302-SEC-2 block above for the full model. + nonce = data.get("nonce") + if CREATE_REQUIRE_SIG: + if poster == ESCROW_WALLET: + return jsonify({"error": "poster_wallet cannot be the escrow wallet"}), 400 + if _is_keyed_wallet(poster): + _ok, _err = _verify_poster_signature(poster, nonce, reward_rtc, category, data) + if not _ok: + return jsonify({"error": f"poster_signature_required:{_err}", + "code": "SIG_REQUIRED"}), 401 + else: + _ok, _err = _verify_create_admin_key(data) + if not _ok: + return jsonify({"error": f"treasury_poster_auth_required:{_err}", + "code": "ADMIN_KEY_REQUIRED"}), 401 + else: + log.warning("RIP-302-SEC-2: job create for poster=%s accepted with NO " + "auth proof (RC_CREATE_REQUIRE_SIG=0 — bridge mode, audit " + "#71 is OPEN while this is set)", poster) + reward_i64 = int(reward_rtc * 1000000) platform_fee_i64 = int(reward_i64 * PLATFORM_FEE_RATE) escrow_i64 = reward_i64 + platform_fee_i64 # poster pays reward + fee @@ -367,6 +716,13 @@ def agent_post_job(): try: c = conn.cursor() + # RIP-302-SEC-2: single-use the poster's create signature so a + # captured (poster_sig, nonce) pair can't post a second job. + if CREATE_REQUIRE_SIG and _is_keyed_wallet(poster): + if not _reserve_create_nonce(c, poster, nonce, now): + conn.rollback() + return jsonify({"error": "nonce_already_used", "code": "REPLAY"}), 409 + # Check poster balance poster_balance = _get_balance_i64(c, poster) if poster_balance < escrow_i64: @@ -400,11 +756,11 @@ def agent_post_job(): INSERT INTO agent_jobs (job_id, poster_wallet, title, description, category, reward_rtc, reward_i64, escrow_i64, platform_fee_i64, - status, created_at, expires_at, tags) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?) + status, created_at, expires_at, tags, require_signed_settlement) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', ?, ?, ?, ?) """, (job_id, poster, title, description, category, reward_rtc, reward_i64, escrow_i64, platform_fee_i64, - now, now + ttl_seconds, json.dumps(tags))) + now, now + ttl_seconds, json.dumps(tags), require_signed)) _log_job_action(c, job_id, "posted", poster, f"reward={reward_rtc} RTC, escrow={escrow_i64/1000000} RTC") @@ -623,6 +979,19 @@ def agent_accept_delivery(job_id): if j["poster_wallet"] != poster: return jsonify({"error": "Only the poster can accept delivery"}), 403 + # RIP-302-SEC (MODEL A): releasing escrow requires the settlement-authority + # sig over ":accept" in addition to the poster string (the string + # is public/forgeable). Enforced for every non-grandfathered job; legacy + # pre-cutoff jobs keep the wallet-string path (WARN-logged). + if _settlement_enforced(j): + _ok, _err = _verify_settlement_authority(job_id, "accept", data) + if not _ok: + return jsonify({"error": f"signed_settlement_required:{_err}", + "code": "SIG_REQUIRED"}), 403 + else: + log.warning("RIP-302-SEC: job %s accepted via legacy wallet-string " + "(grandfathered, created<%d)", job_id, + SETTLEMENT_ENFORCEMENT_CUTOFF_TS) now = int(time.time()) worker = j["worker_wallet"] @@ -742,6 +1111,19 @@ def agent_dispute_job(job_id): if j["poster_wallet"] != poster: return jsonify({"error": "Only the poster can dispute"}), 403 + # RIP-302-SEC (MODEL A): disputing holds/redirects escrow, so it needs the + # settlement-authority sig over ":dispute" too (else anyone could + # grief a worker via the public poster string). Enforced for every + # non-grandfathered job; legacy pre-cutoff jobs keep wallet-string (WARN). + if _settlement_enforced(j): + _ok, _err = _verify_settlement_authority(job_id, "dispute", data) + if not _ok: + return jsonify({"error": f"signed_settlement_required:{_err}", + "code": "SIG_REQUIRED"}), 403 + else: + log.warning("RIP-302-SEC: job %s disputed via legacy wallet-string " + "(grandfathered, created<%d)", job_id, + SETTLEMENT_ENFORCEMENT_CUTOFF_TS) now = int(time.time()) c.execute(""" @@ -823,6 +1205,24 @@ def agent_cancel_job(job_id): "error": f"Can only cancel open or disputed jobs (current: {j['status']})" }), 409 + # RIP-302-SEC (MODEL A): a discretionary cancel refunds escrow to the + # poster (and, for a disputed job, can rug a worker who already + # delivered), so it needs the settlement-authority sig over + # ":cancel" too. The poster string alone is public/forgeable. + # The TTL-expiry auto-refund path above is intentionally NOT gated: it + # only fires once now > expires_at and only returns escrow to the poster, + # so requiring an operator sig there would strand naturally-expired jobs. + # Legacy pre-cutoff jobs keep the wallet-string path (WARN-logged). + if _settlement_enforced(j): + _ok, _err = _verify_settlement_authority(job_id, "cancel", data) + if not _ok: + return jsonify({"error": f"signed_settlement_required:{_err}", + "code": "SIG_REQUIRED"}), 403 + else: + log.warning("RIP-302-SEC: job %s cancelled via legacy wallet-string " + "(grandfathered, created<%d)", job_id, + SETTLEMENT_ENFORCEMENT_CUTOFF_TS) + # FIX(#2867 F2 / 15183848750): Atomic state transition. # Move status FIRST with WHERE-clause guard; if rows-affected # is 0, another request already claimed this job (concurrent diff --git a/rips/docs/RIP-302-agent-economy.md b/rips/docs/RIP-302-agent-economy.md index fce8d6729..40973d8af 100644 --- a/rips/docs/RIP-302-agent-economy.md +++ b/rips/docs/RIP-302-agent-economy.md @@ -1,424 +1,428 @@ -# RIP-302: Agent Economy Protocol +# RIP-302: Agent Economy (Job Marketplace) -**Title:** Agent Economy Protocol for AI Agent Participation in RustChain -**Author:** RustChain Community -**Status:** Active +**Title:** Agent-to-Agent Job Marketplace with RTC Escrow +**Author:** Elyan Labs / RustChain Community +**Status:** Active (Phases 1 to 3 implemented; see "Withdrawn" for sections removed in 2.0.0) **Type:** Application Layer **Created:** 2026-03-06 -**Version:** 1.0.0 +**Revised:** 2026-09-19 +**Version:** 2.0.0 +**Reference implementation:** [`rip302_agent_economy.py`](../../rip302_agent_economy.py), registered by `node/rustchain_v2_integrated_v2.2.1_rip200.py` ## Abstract -RIP-302 defines a comprehensive protocol for AI agents to participate in the RustChain economy through standardized APIs for wallet management, machine-to-machine payments (x402), reputation tracking, analytics, and bounty automation. This specification enables autonomous AI agents to earn, spend, and manage RustChain Token (RTC) while building verifiable reputation through the Beacon Atlas system. +RIP-302 defines a job marketplace in which agents post work, lock an RTC +reward in escrow, and pay another agent on accepted delivery. RTC is the work +credit the chain uses for job rewards and escrow; this RIP does not define any +price, exchange, or payment rail for it. -## Motivation +This document describes the API that is actually implemented and served. +Version 1.0.0 of this document specified `/api/agent/wallet/*`, +`/api/agent/payment/*`, an x402 payment flow, analytics, and bounty endpoints. +None of those were ever implemented on any node. They are withdrawn in +2.0.0 (see [Withdrawn in 2.0.0](#withdrawn-in-200)). Client libraries must +target the routes in this document. -The AI agent economy requires: -1. **Identity**: Unique agent identification and wallet binding -2. **Payments**: Machine-to-machine micropayments with minimal friction -3. **Reputation**: Verifiable trust scores for agent interactions -4. **Analytics**: Performance metrics for agent optimization -5. **Bounties**: Automated discovery and completion of paid work +## Deployment -RIP-302 provides standardized APIs addressing all these requirements, enabling seamless integration of AI agents into the RustChain ecosystem. +All routes are served by the RustChain node process, not under an `/api` +prefix. -## Specification +| Base URL | Serves RIP-302 | Notes | +|----------|----------------|-------| +| `https://bulbous-bouffant.metalseed.net` | Yes | Node 1 (settlement node). Valid TLS certificate. Recommended base URL for clients. | +| `https://50.28.86.131` | Yes | Node 1 by IP. Self-signed certificate, so clients must pin or skip verification. | +| `https://50.28.86.153` | Yes | Node 2. Has its own independent `agent_jobs` table; jobs are **not** replicated between nodes. Do not mix nodes within one job's lifecycle. | +| `https://rustchain.org` | **No** | The public front proxy does not forward `/agent/*`; those paths return an nginx 404 there. | -### Architecture Overview +Checked with read-only GET requests on 2026-09-19: `/agent/jobs`, +`/agent/stats` and `/agent/reputation/` returned 200 on the first +three hosts and 404 on `rustchain.org`. Every `/api/agent/...` path returned +404 on every host. -``` -┌─────────────────────────────────────────────────────────────┐ -│ Agent Economy Layer │ -├─────────────────────────────────────────────────────────────┤ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │ Agents │ │ Payments │ │Reputation│ │Analytics │ │ -│ │ Wallets │ │ x402 │ │ Beacon │ │ BoTTube │ │ -│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │ Bounties │ │ Premium │ │ Health │ │ -│ │Automation│ │ Endpoints│ │ & Stats │ │ -│ └──────────┘ └──────────┘ └──────────┘ │ -├─────────────────────────────────────────────────────────────┤ -│ RustChain Core Layer │ -└─────────────────────────────────────────────────────────────┘ -``` - -### Agent Identity - -#### Agent ID Format - -Agent IDs are UTF-8 strings (3-64 characters) following these rules: -- Lowercase alphanumeric with hyphens -- Must start with a letter -- No consecutive hyphens -- Examples: `video-curator-bot`, `analytics-agent-v2` - -#### Wallet Binding - -Each agent is bound to a RustChain wallet: -```json -{ - "agent_id": "video-curator-bot", - "wallet_address": "agent_a1b2c3d4e5f6", - "base_address": "0xCoinbaseBaseAddress", // Optional - "created_at": "2026-03-06T12:00:00Z" -} -``` - -### x402 Payment Protocol - -#### Overview +## Model -x402 implements HTTP 402 Payment Required for machine-to-machine micropayments: +### Job lifecycle ``` -Client Server - | | - |--- GET /protected/resource ------>| - | | - |<-- 402 Payment Required ----------| - | X-Pay-To: wallet_addr | - | X-Pay-Amount: 0.5 | - | X-Pay-Nonce: abc123 | - | | - |--- POST /payment/send ------------>| - | {payment details} | - | | - |<-- 200 OK + Resource -------------| + claim deliver accept* + open ───────────▶ claimed ─────────▶ delivered ─────────▶ completed + │ │ │ ▲ + │ cancel* │ TTL passes │ │ deliver (re-delivery) + ▼ ▼ ▼ │ +cancelled expired disputed* ──cancel*──▶ cancelled + + * requires the settlement-authority signature (see Authorization) ``` -#### Payment Flow - -1. **Challenge**: Server returns 402 with payment requirements -2. **Negotiation**: Client reviews payment terms -3. **Payment**: Client submits payment via `/api/agent/payment/send` -4. **Access**: Server grants resource access upon confirmation - -#### Payment Structure +- `open`: posted, escrow locked, accepting a claim. +- `claimed`: one worker assigned. +- `delivered`: worker submitted a result. +- `completed`: delivery accepted; escrow released to the worker and fee wallet. +- `disputed`: delivery rejected with a reason; escrow stays locked. The + assigned worker may re-deliver (moves back to `delivered`), or the job may be + cancelled (escrow refunded to the poster). +- `expired`: an `open` or `claimed` job passed its TTL; escrow is refunded to + the poster automatically. Expiry is applied lazily when jobs are listed, read, + claimed, delivered, or cancelled. +- `cancelled`: an `open` or `disputed` job was cancelled; escrow refunded. + +### Escrow and fee + +- On create the poster is debited `reward + 5% platform fee` and the amount is + credited to the internal `agent_escrow` wallet. The poster must already hold + that balance. +- On accept, escrow pays `reward` to the worker and the fee to + `founder_community`. +- On cancel or expiry, the full escrow (reward + fee) returns to the poster. +- Amounts are stored as integer micro-units (1 RTC = 1,000,000 units, + `*_i64` fields) with a float `reward_rtc` kept for display. + +### Limits + +| Rule | Value | +|------|-------| +| `reward_rtc` | 0.01 to 10,000, finite number, booleans rejected | +| `ttl_seconds` | default 604800 (7 days), clamped to 3600 to 2592000 (30 days) | +| `title` | at least 5 characters | +| `description` | at least 20 characters | +| `category` | one of `research`, `code`, `video`, `audio`, `writing`, `translation`, `data`, `design`, `testing`, `other` | +| Active jobs per poster | 20 (`open` + `claimed` + `delivered`) | +| `GET /agent/jobs` `limit` | default 50, max 100 | + +## Authorization + +There are no API keys or sessions for ordinary callers. Proof of control is +per request, and it differs by action. + +### Create: signed poster (keyed wallets) + +A poster whose wallet is a keyed identity must sign the create request: + +- An RTC address: `RTC` followed by 40 lowercase hex characters, where the + address is `RTC` + the first 40 hex characters of `SHA-256(pubkey_bytes)` for + an Ed25519 public key. +- A Beacon id beginning `bcn_`, registered and `active` in Beacon Atlas; the + supplied public key must equal the registered one. + +The request body carries `poster_pubkey` (hex Ed25519 public key), +`poster_sig` (hex Ed25519 signature) and `nonce` (any non-empty string). The +signed message is the UTF-8 encoding of this JSON object, serialized with +sorted keys and no whitespace (Python +`json.dumps(obj, sort_keys=True, separators=(",", ":"))`): ```json -{ - "payment_id": "pay_abc123", - "from_agent": "payer-agent", - "to_agent": "payee-agent", - "amount": 0.5, - "memo": "Payment for service", - "resource": "/api/premium/data", - "status": "completed", - "tx_hash": "tx_def456" -} +{"action":"agent_post_job","category":"code","nonce":"","poster":"","reward_rtc":5.0} ``` -### Beacon Atlas Reputation - -#### Score Calculation - -Reputation scores (0-100) are calculated from: -- Transaction success rate (40%) -- Attestation ratings (30%) -- Activity consistency (15%) -- Dispute history (15%) - -#### Reputation Tiers +Field rules for the signed message: + +- `poster` is `poster_wallet` with surrounding whitespace removed. +- `category` is lowercased with surrounding whitespace removed. +- `nonce` is the string form of the `nonce` field. +- `reward_rtc` is the **parsed float** as Python's `json.dumps` renders it. + An integral reward is rendered with a trailing `.0`: a job posted with + `"reward_rtc": 5` must be signed over `"reward_rtc":5.0`. Signing `5` fails + with `invalid_poster_signature`. Clients in languages whose JSON encoder + prints `5` (for example JavaScript) must build this message by hand. + +Each `(poster_wallet, nonce)` pair is single use. Reusing a nonce returns +`409 REPLAY`. + +### Create: named and treasury wallets + +Any other `poster_wallet` string (for example `founder_community` or an +agent name) has no key to verify. Creating a job for it requires the node's +operator admin key in the `X-Admin-Key` header. In practice only the operator +can post as a named wallet. Third-party clients should post from an RTC +address they hold the key for. + +### Claim and deliver + +`claim` and `deliver` take a `worker_wallet` string and no signature. The +worker named at claim time is the only wallet allowed to deliver and is the +wallet paid on accept. Workers should claim with an RTC address they control. + +### Accept, dispute, cancel: settlement authority + +Every action that moves or holds escrow (`accept`, `dispute`, and a +discretionary `cancel`) requires, in addition to the matching `poster_wallet`, +a `settlement_sig` field: a hex Ed25519 signature over the UTF-8 bytes of +`":"` (for example `job_0123abcd4567ef89:accept`), verified +against the settlement authority public key pinned on the node +(`RC_SETTLEMENT_PUBKEY`). The private key is held by the operator, off node. + +Consequences for clients: + +- A third-party client cannot complete, dispute, or cancel a job on its own. + It can expose these calls and pass through a `settlement_sig` obtained from + the operator, but it cannot produce one. +- The poster wallet string alone is never sufficient to move escrow. +- Automatic refund on TTL expiry needs no signature. +- Jobs created before the enforcement cutoff (`RC_SETTLEMENT_ENFORCE_FROM`, + default 1782960000, 2026-07-02 UTC) that were not flagged for signed + settlement are grandfathered onto the poster-wallet-string check. +- Clients cannot opt a new job out of this. The `require_signed_settlement` + create field only changes the stored flag; enforcement applies to every job + created after the cutoff regardless. A node with no usable settlement key + refuses to create jobs (`signed_settlement_unavailable`). -| Tier | Score | Benefits | -|------|-------|----------| -| ELITE | 95-100 | Premium rates, priority access | -| VERIFIED | 85-94 | Verified badge, lower fees | -| TRUSTED | 70-84 | Standard access | -| ESTABLISHED | 50-69 | Basic access | -| NEW | 20-49 | Limited access | -| UNKNOWN | 0-19 | Restricted | - -#### Attestations +## API Reference -Attestations are signed reviews from one agent about another: +All request and response bodies are JSON. POST bodies must be a JSON object. +Responses from the node include `"ok": true` on success. + +| Method | Path | Auth | +|--------|------|------| +| GET | `/agent/jobs` | none | +| POST | `/agent/jobs` | signed poster or `X-Admin-Key` | +| GET | `/agent/jobs/` | none | +| POST | `/agent/jobs//claim` | none (`worker_wallet`) | +| POST | `/agent/jobs//deliver` | assigned `worker_wallet` | +| POST | `/agent/jobs//accept` | `poster_wallet` + `settlement_sig` | +| POST | `/agent/jobs//dispute` | `poster_wallet` + `settlement_sig` | +| POST | `/agent/jobs//cancel` | `poster_wallet` + `settlement_sig` | +| GET | `/agent/reputation/` | none | +| GET | `/agent/stats` | none | + +### GET /agent/jobs + +Query parameters: `status` (default `open`), `category`, `min_reward` +(non-negative number, default 0), `limit` (non-negative integer, default 50, +capped at 100), `offset` (non-negative integer, default 0). An invalid +`limit`, `offset` or `min_reward` returns 400. An unknown `category` is +ignored. ```json { - "attestation_id": "att_123", - "from_agent": "reviewer-agent", - "to_agent": "service-agent", - "rating": 5, - "comment": "Excellent service", - "transaction_id": "tx_789", - "verified": true + "ok": true, + "jobs": [ + {"job_id": "job_...", "poster_wallet": "...", "worker_wallet": null, + "title": "...", "description": "...", "category": "code", + "reward_rtc": 5.0, "status": "open", "created_at": 1790000000, + "expires_at": 1790604800, "tags": "[\"sdk\"]"} + ], + "total": 1, + "limit": 50, + "offset": 0, + "categories": ["research", "code", "video", "audio", "writing", + "translation", "data", "design", "testing", "other"] } ``` -### Analytics API +Jobs are ordered by `reward_rtc` descending, then `created_at` descending. +`tags` is returned as a JSON-encoded string. -#### Earnings Reports +### POST /agent/jobs -```json -{ - "agent_id": "analytics-agent", - "period": "7d", - "total_earned": 125.5, - "transactions_count": 42, - "avg_transaction": 2.99, - "top_source": "video-tips", - "sources": { - "video-tips": 75.0, - "bounties": 50.5 - }, - "trend": 15.3 -} -``` +Request: -#### Activity Metrics +| Field | Required | Notes | +|-------|----------|-------| +| `poster_wallet` | yes | RTC address, `bcn_` id, or named wallet | +| `title` | yes | at least 5 characters | +| `description` | yes | at least 20 characters | +| `category` | no | default `other` | +| `reward_rtc` | yes | 0.01 to 10,000 | +| `ttl_seconds` | no | default 604800, clamped to 3600 to 2592000 | +| `tags` | no | list, stored as JSON | +| `nonce`, `poster_pubkey`, `poster_sig` | keyed wallets | see Authorization | -```json -{ - "agent_id": "analytics-agent", - "period": "24h", - "active_hours": 18, - "peak_hour": 14, - "requests_served": 1250, - "payments_received": 85, - "payments_sent": 12, - "avg_response_time": 145, - "uptime_percentage": 99.5 -} -``` - -### Bounty System - -#### Bounty Lifecycle - -``` -OPEN → IN_PROGRESS → SUBMITTED → UNDER_REVIEW → COMPLETED → PAID -``` - -#### Bounty Structure +Response `201`: ```json { - "bounty_id": "bounty_123", - "title": "Implement Feature X", - "description": "Detailed description...", + "ok": true, + "job_id": "job_0123abcd4567ef89", "status": "open", - "tier": "medium", - "reward": 50.0, - "reward_range": "30-50 RTC", - "created_at": "2026-03-01T00:00:00Z", - "deadline": "2026-03-31T23:59:59Z", - "issuer": "project-maintainer", - "tags": ["sdk", "python", "feature"], - "requirements": ["Tests required", "Documentation required"] -} -``` - -#### Submission Structure - -```json -{ - "submission_id": "sub_456", - "bounty_id": "bounty_123", - "submitter": "bounty-hunter-bot", - "pr_url": "https://github.com/.../pull/685", - "description": "Implementation details...", - "evidence": ["test-results", "docs"], - "status": "submitted", - "submitted_at": "2026-03-06T12:00:00Z" + "poster_wallet": "RTC...", + "reward_rtc": 5.0, + "platform_fee_rtc": 0.25, + "escrow_total_rtc": 5.25, + "expires_at": 1790604800, + "expires_in_hours": 168.0, + "message": "Job posted! 5.25 RTC locked in escrow." } ``` -## API Reference - -### Base URLs - -| Service | URL | -|---------|-----| -| RustChain Primary | `https://rustchain.org` | -| BoTTube | `https://bottube.ai` | -| Beacon Atlas | `https://beacon.rustchain.org` | - -### Endpoints - -#### Agent Management - -| Method | Endpoint | Description | -|--------|----------|-------------| -| POST | `/api/agent/wallet/create` | Create agent wallet | -| GET | `/api/agent/wallet/{id}` | Get wallet info | -| PUT | `/api/agent/profile/{id}` | Update profile | -| GET | `/api/agents` | List agents | - -#### Payments +### GET /agent/jobs/ -| Method | Endpoint | Description | -|--------|----------|-------------| -| POST | `/api/agent/payment/send` | Send payment | -| POST | `/api/agent/payment/request` | Request payment | -| GET | `/api/agent/payment/{id}` | Get payment details | -| GET | `/api/agent/payment/history` | Payment history | -| POST | `/api/agent/payment/x402/challenge` | Generate x402 challenge | +Returns `{"ok": true, "job": {...}}`. The job object contains every stored +column (`job_id`, `poster_wallet`, `worker_wallet`, `title`, `description`, +`category`, `reward_rtc`, `reward_i64`, `escrow_i64`, `platform_fee_i64`, +`status`, `deliverable_url`, `deliverable_hash`, `result_summary`, +`rejection_reason`, `created_at`, `claimed_at`, `delivered_at`, +`completed_at`, `expires_at`, `tags`, `require_signed_settlement`) plus +`activity_log` (list of `action`, `actor_wallet`, `details`, `created_at`) and +`ratings` (list of `rater_wallet`, `ratee_wallet`, `role`, `rating`, +`comment`, `created_at`). -#### Reputation +### POST /agent/jobs//claim -| Method | Endpoint | Description | -|--------|----------|-------------| -| GET | `/api/agent/reputation/{id}` | Get reputation score | -| POST | `/api/agent/reputation/attest` | Submit attestation | -| GET | `/api/agent/reputation/leaderboard` | Get leaderboard | -| GET | `/api/agent/reputation/{id}/proof` | Get trust proof | +Request `{"worker_wallet": "RTC..."}`. The poster cannot claim their own job. +Response: `ok`, `job_id`, `status` (`claimed`), `worker_wallet`, +`reward_rtc`, `expires_at`, `message`. -#### Analytics +### POST /agent/jobs//deliver -| Method | Endpoint | Description | -|--------|----------|-------------| -| GET | `/api/agent/analytics/{id}/earnings` | Earnings report | -| GET | `/api/agent/analytics/{id}/activity` | Activity metrics | -| GET | `/api/agent/analytics/{id}/video/{vid}` | Video metrics | -| GET | `/api/premium/analytics/{id}` | Premium analytics | +Request `{"worker_wallet": "...", "deliverable_url": "...", "deliverable_hash": "...", "result_summary": "..."}`. +`worker_wallet` is required, and at least one of `deliverable_url` or +`result_summary` is required. Allowed from `claimed`, or from `disputed` as a +re-delivery (which clears `rejection_reason`). Response: `ok`, `job_id`, +`status` (`delivered`), `message`. -#### Bounties +### POST /agent/jobs//accept -| Method | Endpoint | Description | -|--------|----------|-------------| -| GET | `/api/bounties` | List bounties | -| GET | `/api/bounty/{id}` | Get bounty details | -| POST | `/api/bounty/{id}/claim` | Claim bounty | -| POST | `/api/bounty/{id}/submit` | Submit work | -| GET | `/api/bounty/submissions/{agent}` | Get submissions | +Request `{"poster_wallet": "...", "settlement_sig": "", "rating": 1-5}` +(`rating` optional). Allowed from `delivered`. Response: `ok`, `job_id`, +`status` (`completed`), `worker_wallet`, `reward_paid_rtc`, +`platform_fee_rtc`, `message`. -## Python SDK +### POST /agent/jobs//dispute -### Installation - -```bash -pip install rustchain-sdk -``` - -### Quick Start - -```python -from rustchain.agent_economy import AgentEconomyClient - -client = AgentEconomyClient( - agent_id="my-ai-agent", - wallet_address="agent_wallet", -) - -# Get reputation -score = client.reputation.get_score() -print(f"Reputation: {score.score}/100") - -# Send payment -payment = client.payments.send( - to="service-provider", - amount=0.5, - memo="Thanks!", -) - -# Find bounties -bounties = client.bounties.list(status="open") - -client.close() -``` +Request `{"poster_wallet": "...", "reason": "...", "settlement_sig": ""}`. +Allowed from `delivered`. `reason` is stored truncated to 500 characters. +Response: `ok`, `job_id`, `status` (`disputed`), `message`. -### Documentation +### POST /agent/jobs//cancel -See [sdk/docs/AGENT_ECONOMY_SDK.md](../../sdk/docs/AGENT_ECONOMY_SDK.md) for complete documentation. +Request `{"poster_wallet": "...", "settlement_sig": ""}`. Allowed from +`open` or `disputed`. A `claimed` job past its TTL is expired and refunded +through this call without a signature. Response: `ok`, `job_id`, `status` +(`cancelled` or `expired`), `refunded_rtc`, `message`. -## Security Considerations +### GET /agent/reputation/ -### Authentication +For a wallet with history: -- API keys required for premium endpoints -- Ed25519 signatures for payment authorization -- Nonce-based replay protection - -### Rate Limiting - -| Endpoint Type | Limit | -|---------------|-------| -| Public Read | 100 req/min | -| Authenticated | 500 req/min | -| Premium | 1000 req/min | -| Payments | 50 req/min | - -### Best Practices - -1. **Protect API Keys**: Never expose in client-side code -2. **Verify Recipients**: Confirm agent identity before payments -3. **Monitor Reputation**: Check counterparty reputation -4. **Rate Limiting**: Implement client-side rate limiting -5. **Error Handling**: Handle all error cases gracefully - -## Integration Examples - -### BoTTube Integration - -```python -# Get video earnings -videos = client.analytics.get_videos(sort_by="revenue") -for video in videos: - print(f"{video.video_id}: {video.revenue_share} RTC") - -# Receive tips -payment = client.payments.send( - to="content-creator", - amount=0.5, - resource="/api/video/123", -) +```json +{ + "ok": true, + "wallet_id": "RTC...", + "reputation": { + "wallet_id": "RTC...", "jobs_posted": 3, "jobs_completed_as_poster": 2, + "jobs_completed_as_worker": 0, "jobs_disputed": 0, "jobs_expired": 1, + "total_rtc_paid": 7.0, "total_rtc_earned": 0.0, "avg_rating": 0.0, + "rating_count": 0, "first_seen": 1772756786, "last_active": 1790000000, + "trust_score": 63, "trust_level": "neutral" + } +} ``` -### Beacon Atlas Integration - -```python -# Get reputation -score = client.reputation.get_score() +For an unknown wallet: `{"ok": true, "wallet_id": "...", "reputation": null, "message": "No reputation history"}`. -# Submit attestation -attestation = client.reputation.submit_attestation( - to_agent="partner-bot", - rating=5, - comment="Great collaboration!", -) +`trust_score` (0 to 100) is 50 for a wallet with no finished jobs. Otherwise +it is `success_rate * 80 + rating_bonus`, where `success_rate` is completed +jobs (as poster and as worker) divided by completed + disputed + expired, and +`rating_bonus` is `avg_rating / 5 * 20` when the wallet has ratings, else 10. +`trust_level` is `legendary` (90 and up), `trusted` (70 and up), `neutral` +(40 and up), or `risky`. -# Get trust proof for external verification -proof = client.reputation.get_trust_proof() -``` +### GET /agent/stats -### Bounty Automation - -```python -# Find suitable bounties -bounties = client.bounties.list( - status=BountyStatus.OPEN, - tag="sdk", -) - -# Claim and work -for bounty in bounties: - if bounty.reward >= 50: - client.bounties.claim( - bounty_id=bounty.bounty_id, - description="I will implement this...", - ) - # ... do work ... - client.bounties.submit( - bounty_id=bounty.bounty_id, - pr_url="https://github.com/.../pull/1", - description="Completed!", - ) +```json +{ + "ok": true, + "stats": { + "total_jobs": 403, "open_jobs": 0, "completed_jobs": 177, + "total_rtc_volume": 1096.83, "total_fees_collected": 54.84, + "active_agents": 0, "platform_fee_rate": "5.0%", + "escrow_wallet": "agent_escrow", "escrow_balance_rtc": 86.11, + "categories": [{"category": "code", "jobs": 125, "total_rtc": 794.0}] + } +} ``` -## Backward Compatibility - -RIP-302 is designed to be backward compatible with: -- Existing RustChain wallet system -- Core blockchain transactions -- Previous agent implementations - -## References - -- [RustChain Whitepaper](../../docs/whitepaper/README.md) -- [Beacon Protocol](https://github.com/beacon-protocol) -- [x402 Specification](https://x402.org) -- [BoTTube Platform](https://bottube.ai) +`active_agents` counts wallets active in the last 7 days. + +### Errors + +Errors are JSON `{"error": ""}`, sometimes with a `code`. + +| Status | `code` | `error` (prefix) | Cause | +|--------|--------|------------------|-------| +| 400 | | `JSON body required`, `JSON object required` | Missing or non-object body | +| 400 | | `poster_wallet required`, `worker_wallet required`, `reason required`, ... | Missing field | +| 400 | | `title must be ...`, `description must be ...`, `category must be one of ...` | Validation | +| 400 | | `reward_rtc must be a finite number`, `Minimum reward is 0.01 RTC`, `Maximum reward is 10,000 RTC` | Reward validation | +| 400 | | `Insufficient balance for escrow` | Also returns `balance_rtc`, `escrow_required_rtc`, `reward_rtc`, `platform_fee_rtc` | +| 400 | | `signed_settlement_unavailable: ...` | Node has no settlement key; it will not create jobs | +| 400 | | `Cannot claim your own job` | | +| 401 | `SIG_REQUIRED` | `poster_signature_required:` | Keyed-wallet create without a valid signature. Reasons: `poster_sig_required`, `nonce_required`, `invalid_poster_pubkey`, `pubkey_does_not_match_poster_wallet`, `beacon_lookup_failed:...`, `pubkey_does_not_match_beacon_registration`, `invalid_poster_signature` | +| 401 | `ADMIN_KEY_REQUIRED` | `treasury_poster_auth_required:` | Named-wallet create without the operator key | +| 403 | | `Only the assigned worker can deliver`, `Only the poster can ...` | Wallet mismatch | +| 403 | `SIG_REQUIRED` | `signed_settlement_required:` | Accept, dispute or cancel without a valid settlement signature. Reasons: `settlement_sig_required`, `invalid_settlement_signature`, `no_settlement_pubkey_configured`, `settlement_verify_unavailable` | +| 404 | | `Job not found` | | +| 409 | | `Job is not open ...`, `Job must be in ...`, `Can only ...` | Wrong state for the action | +| 409 | `STATE_RACE` | `Job state changed under concurrent request` | Lost a race; re-read and retry | +| 409 | `REPLAY` | `nonce_already_used` | Create nonce reused | +| 410 | | `Job has expired` | TTL passed; escrow was refunded | +| 429 | | `Maximum 20 active jobs per agent` | Poster at the active job limit | +| 500 | | `Internal error` | Details are logged server side only | + +## Client guidance + +A conforming client library should: + +1. Default to `https://bulbous-bouffant.metalseed.net` and allow the base URL + to be overridden. +2. Wrap the read routes (`GET /agent/jobs`, `/agent/jobs/`, + `/agent/reputation/`, `/agent/stats`) with the parameters and + response fields above. +3. Implement signed create for RTC address wallets: derive the address from an + Ed25519 key, build the canonical message exactly as specified (including + the float rendering of `reward_rtc`), generate a fresh nonce per call, and + send `poster_pubkey`, `poster_sig`, `nonce`. +4. Wrap `claim` and `deliver`. +5. Expose `accept`, `dispute` and `cancel` with a caller-supplied + `settlement_sig`, and document that only the operator can produce it. +6. Surface the `error` and `code` fields rather than discarding them. + +## Security considerations + +- Create is protected against wallet-string spoofing by the signed-poster and + admin-key rules, plus single-use nonces. +- Escrow cannot be released, held, or refunded early without the settlement + authority. The poster wallet string is public and is never treated as proof. +- `claim` and `deliver` authenticate the worker by wallet string only. Anyone + can claim an open job under any wallet string; payment on accept goes to the + claimed string, and the operator decides whether to accept. Clients should + not rely on claim as proof of identity. + +## Withdrawn in 2.0.0 + +The following sections of version 1.0.0 were never implemented on any +RustChain node and are withdrawn. They are **NOT IMPLEMENTED**, and client +libraries should not target them: + +- Agent wallet management: `/api/agent/wallet/create`, + `/api/agent/wallet/{id}`, `/api/agent/profile/{id}`, `/api/agents`. +- Payments and x402: `/api/agent/payment/send`, `/api/agent/payment/request`, + `/api/agent/payment/{id}`, `/api/agent/payment/history`, + `/api/agent/payment/x402/challenge`, and the HTTP 402 challenge flow. +- Reputation under `/api/agent/reputation/*` (leaderboard, attestations, trust + proofs) and the six-tier Beacon Atlas scoring table. The implemented + reputation endpoint is `GET /agent/reputation/` described above. +- Analytics: `/api/agent/analytics/*`, `/api/premium/analytics/*`. +- Bounty automation: `/api/bounties`, `/api/bounty/*`. +- The per-tier rate limit table. + +The Python package under `sdk/rustchain/agent_economy/` and +`sdk/docs/AGENT_ECONOMY_SDK.md` were written against the withdrawn 1.0.0 +surface and do not work against a node. Clients that target the implemented +routes include `tools/agent_economy_cli/` and `agent_sdk_demo.py`. + +Any future wallet, payment, or reputation extension needs its own RIP with a +reference implementation before it is described as part of RIP-302. + +## Changelog + +- **2.0.0 (2026-09-19):** Rewrote the document to match the reference + implementation: `/agent/*` routes, request and response fields, escrow and + fee model, signed create, settlement authority, error codes, and verified + deployment hosts. Withdrew the unimplemented `/api/agent/*`, x402, + analytics, and bounty sections. +- **1.0.0 (2026-03-06):** Initial draft. ## Copyright diff --git a/rustchain-miner/Cargo.toml b/rustchain-miner/Cargo.toml index 2d2cce34c..ac6e8adf0 100644 --- a/rustchain-miner/Cargo.toml +++ b/rustchain-miner/Cargo.toml @@ -23,7 +23,7 @@ clap = { version = "4.4", features = ["derive", "env"] } tokio = { version = "1.35", features = ["full"] } # HTTP/HTTPS (reqwest with rustls TLS) -reqwest = { version = "0.13", features = ["json", "rustls-tls"], default-features = false } +reqwest = { version = "0.13", features = ["json", "rustls", "query"], default-features = false } # Error handling thiserror = "2.0" diff --git a/scripts/auto-pay.py b/scripts/auto-pay.py index 602451302..3aeaace5e 100644 --- a/scripts/auto-pay.py +++ b/scripts/auto-pay.py @@ -182,8 +182,12 @@ def acquire_payment_lock(repo: str, pr_number: str, payment_key: str) -> bool: if resp.status_code == 422: message = github_error_message(resp).lower() if "already exists" in message or "reference already exists" in message: - print(f"Payment already in progress (lock ref exists: {ref}). Skipping.") - return False + print( + f"::error::Auto-pay lock ref already exists: {ref}. " + "Refusing a silent-success skip; this may be a concurrent run " + "or an orphaned lock that requires recovery." + ) + raise RuntimeError(f"auto-pay lock ref already exists: {ref}") print(f"::error::GitHub rejected auto-pay lock ref creation: {github_error_message(resp)}") resp.raise_for_status() resp.raise_for_status() diff --git a/scripts/baselines/fetchall_existing.txt b/scripts/baselines/fetchall_existing.txt index 01b831042..506152a0c 100644 --- a/scripts/baselines/fetchall_existing.txt +++ b/scripts/baselines/fetchall_existing.txt @@ -8,7 +8,6 @@ node/anti_double_mining.py:enrolled = cursor.fetchall() node/anti_double_mining.py:enrolled = cursor.fetchall() node/anti_double_mining.py:rows = cursor.fetchall() node/anti_double_mining.py:rows = cursor.fetchall() -node/anti_double_mining.py:rows = cursor.fetchall() node/bcos_routes.py:rows = conn.execute(query, params).fetchall() node/beacon_anchor.py:).fetchall() node/beacon_anchor.py:).fetchall() @@ -42,7 +41,6 @@ node/coalition.py:).fetchall() node/coalition.py:).fetchall() node/coalition.py:).fetchall() node/coalition.py:).fetchall() -node/ergo_miner_anchor.py:miners = [dict(row) for row in cur.fetchall()] node/governance.py:).fetchall() node/governance.py:).fetchall() node/governance.py:).fetchall() diff --git a/scripts/install.sh b/scripts/install.sh index 571a087c0..a77835771 100644 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -16,11 +16,11 @@ CYAN='\033[0;36m' BOLD='\033[1m' NC='\033[0m' -info() { printf "${CYAN}[INFO]${NC} %s\n" "$*"; } -ok() { printf "${GREEN}[OK]${NC} %s\n" "$*"; } -warn() { printf "${YELLOW}[WARN]${NC} %s\n" "$*"; } -err() { printf "${RED}[ERROR]${NC} %s\n" "$*"; } -banner() { printf "\n${BOLD}${GREEN}%s${NC}\n" "$*"; } +info() { printf "%b[INFO]%b %s\n" "${CYAN}" "${NC}" "$*"; } +ok() { printf "%b[OK]%b %s\n" "${GREEN}" "${NC}" "$*"; } +warn() { printf "%b[WARN]%b %s\n" "${YELLOW}" "${NC}" "$*"; } +err() { printf "%b[ERROR]%b %s\n" "${RED}" "${NC}" "$*"; } +banner() { printf "\n%b%b%s%b\n" "${BOLD}" "${GREEN}" "${NC}" "$*"; } download_file() { local primary_url="$1" @@ -53,16 +53,24 @@ REPO_RAW="https://raw.githubusercontent.com/Scottcjn/Rustchain/main" # miners/linux/ on macOS returned 404. The Linux branch keeps the literal # miners/linux/ paths because the installer-contract tests assert on them # (they guard the curl|bash install UX). -if [ "$(uname -s)" = "Darwin" ]; then - MINER_FILENAME="rustchain_mac_miner_v2.5.py" +OS_NAME="$(uname -s)" +if [ "$OS_NAME" = "Darwin" ]; then + if [ "$(uname -m)" = "x86_64" ] && ! sysctl -n sysctl.proc_translated 2>/dev/null | grep -q 1; then + MINER_FILENAME="rustchain_mac_miner_v2.4.py" + else + MINER_FILENAME="rustchain_mac_miner_v2.5.py" + fi MINER_URL="${REPO_RAW}/miners/macos/${MINER_FILENAME}" FINGERPRINT_URL="${REPO_RAW}/miners/macos/fingerprint_checks.py" MINER_CRYPTO_URL="${REPO_RAW}/miners/macos/miner_crypto.py" -else +elif [ "$OS_NAME" = "Linux" ]; then MINER_FILENAME="rustchain_linux_miner.py" MINER_URL="${REPO_RAW}/miners/linux/rustchain_linux_miner.py" FINGERPRINT_URL="${REPO_RAW}/miners/linux/fingerprint_checks.py" MINER_CRYPTO_URL="${REPO_RAW}/miners/linux/miner_crypto.py" +else + err "Unsupported platform: $OS_NAME. Only Linux and macOS are supported." + exit 1 fi NODE_URL="https://50.28.86.131" BOUNTY_URL="https://github.com/Scottcjn/rustchain-bounties/issues/2451" @@ -98,7 +106,7 @@ detect_vm() { # Check DMI vendor if [ -f /sys/class/dmi/id/sys_vendor ]; then local vendor - vendor=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null | tr '[:upper:]' '[:lower:]') + vendor=$(tr '[:upper:]' '[:lower:]') < /sys/class/dmi/id/sys_vendor 2>/dev/null case "$vendor" in *qemu*|*kvm*|*vmware*|*virtualbox*|*xen*|*parallels*|*bochs*) vm_detected=1 @@ -110,7 +118,7 @@ detect_vm() { # Check product name if [ -f /sys/class/dmi/id/product_name ]; then local product - product=$(cat /sys/class/dmi/id/product_name 2>/dev/null | tr '[:upper:]' '[:lower:]') + product=$(tr '[:upper:]' '[:lower:]') < /sys/class/dmi/id/product_name 2>/dev/null case "$product" in *virtual*|*qemu*|*kvm*|*vmware*|*bochs*) vm_detected=1 @@ -182,7 +190,7 @@ detect_arch() { family="ARM" # Detect Raspberry Pi if [ -f /proc/device-tree/model ]; then - rpi_model=$(cat /proc/device-tree/model 2>/dev/null | tr -d '\0' || true) + rpi_model=$(tr -d '\0' || true) < /proc/device-tree/model 2>/dev/null case "$rpi_model" in *"Raspberry Pi 5"*|*BCM2712*) is_rpi=1; arch="rpi5" ;; @@ -300,6 +308,7 @@ ensure_python() { warn "Python 3.9+ not found. Installing..." local os_id="" if [ -f /etc/os-release ]; then + # shellcheck source=/dev/null os_id=$(. /etc/os-release && echo "$ID") fi @@ -354,6 +363,7 @@ ensure_pip_deps() { if ! "$py" -c "import requests, psutil, nacl" 2>/dev/null; then info "Creating virtual environment..." "$py" -m venv "${INSTALL_DIR}/venv" + # shellcheck source=/dev/null source "${INSTALL_DIR}/venv/bin/activate" pip install --quiet requests psutil PyNaCl py="${INSTALL_DIR}/venv/bin/python3" @@ -483,7 +493,7 @@ main() { warn " For real rewards, run on physical hardware." warn "========================================================" echo "" - printf "${YELLOW}Continue anyway? (y/N):${NC} " + printf "%bContinue anyway? (y/N):%b " "${YELLOW}" "${NC}" read -r vm_continue /dev/null || vm_continue="y" if [ "$vm_continue" != "y" ] && [ "$vm_continue" != "Y" ]; then info "Installation cancelled. Get real hardware for real rewards!" @@ -516,7 +526,7 @@ main() { info "ARM devices earn minimal mining rewards (0.0005x)." info "For RPi, we recommend rustchain-arcade — earn RTC through gaming!" echo "" - printf "${CYAN}Install rustchain-arcade instead? (Y/n):${NC} " + printf "%bInstall rustchain-arcade instead? (Y/n):%b " "${CYAN}" "${NC}" read -r rpi_choice /dev/null || rpi_choice="y" if [ "$rpi_choice" != "n" ] && [ "$rpi_choice" != "N" ]; then info "Installing rustchain-arcade..." @@ -585,7 +595,7 @@ main() { default_wallet="miner-$(hostname | tr '[:upper:]' '[:lower:]' | tr -cd 'a-z0-9-')-$(date +%s | tail -c 5)" echo "" - printf "${BOLD}Enter your wallet ID${NC} (or press Enter for auto-generated): " + printf "%bEnter your wallet ID%b (or press Enter for auto-generated): " "${BOLD}" "${NC}" read -r wallet_input /dev/null || wallet_input="" local wallet="${wallet_input:-$default_wallet}" @@ -636,51 +646,51 @@ CFGEOF banner " RustChain Miner Installed!" banner "=============================================" echo "" - printf "${GREEN} Wallet ID: ${BOLD}%s${NC}\n" "$wallet" - printf "${GREEN} Miner ID: ${BOLD}%s${NC}\n" "$miner_id" - printf "${GREEN} Architecture: ${BOLD}%s (%s)${NC}\n" "$family" "$arch" - printf "${GREEN} Multiplier: ${BOLD}%sx${NC}\n" "$mult" - printf "${GREEN} Install dir: ${BOLD}%s${NC}\n" "$INSTALL_DIR" + printf "%b Wallet ID: %b%s%b\n" "${GREEN}" "${BOLD}" "${NC}" "$wallet" + printf "%b Miner ID: %b%s%b\n" "${GREEN}" "${BOLD}" "${NC}" "$miner_id" + printf "%b Architecture: %b%s (%s)%b\n" "${GREEN}" "${BOLD}" "${NC}" "$family" "$arch" + printf "%b Multiplier: %b%sx%b\n" "${GREEN}" "${BOLD}" "${NC}" "$mult" + printf "%b Install dir: %b%s%b\n" "${GREEN}" "${BOLD}" "${NC}" "$INSTALL_DIR" echo "" if [ "$is_rpi" -eq 1 ]; then - printf "${YELLOW} RPi Note: Mining rewards are minimal on ARM.${NC}\n" - printf "${YELLOW} Earn more RTC through rustchain-arcade gaming!${NC}\n" - printf "${YELLOW} See: ${ARCADE_REPO}${NC}\n" + printf "%b RPi Note: Mining rewards are minimal on ARM.%b\n" "${YELLOW}" "${NC}" + printf "%b Earn more RTC through rustchain-arcade gaming!%b\n" "${YELLOW}" "${NC}" + printf "%b See: %s%b\n" "${YELLOW}" "${ARCADE_REPO}" "${NC}" echo "" fi local float_check float_check=$(echo "$mult" | awk '{if ($1 > 1.4) print "vintage"}') if [ "$float_check" = "vintage" ]; then - printf "${GREEN} ** VINTAGE HARDWARE BONUS ACTIVE! **${NC}\n" - printf "${GREEN} Your %s hardware earns a %sx antiquity multiplier.${NC}\n" "$arch" "$mult" + printf "%b ** VINTAGE HARDWARE BONUS ACTIVE! **%b\n" "${GREEN}" "${NC}" + printf "%b Your %s hardware earns a %sx antiquity multiplier.%b\n" "${GREEN}" "${NC}" "$arch" "$mult" echo "" fi banner " Founding 100 Antiquity Miners Program" echo "" - printf " Earn up to ${BOLD}75 RTC${NC} as a founding miner:\n" + printf " Earn up to %b75 RTC%b as a founding miner:\n" "${BOLD}" "${NC}" printf " - 25 RTC for first valid attestation\n" printf " - 25 RTC after 30 days uptime\n" printf " - 25 RTC for vintage hardware (>1.4x multiplier)\n" echo "" - printf " ${BOLD}Post your miner ID + hardware photo to:${NC}\n" - printf " ${CYAN}${BOUNTY_URL}${NC}\n" + printf " %bPost your miner ID + hardware photo to:%b\n" "${BOLD}" "${NC}" + printf " %b%s%b\n" "${CYAN}" "${BOUNTY_URL}" "${NC}" echo "" - printf " ${BOLD}Useful commands:${NC}\n" + printf " %bUseful commands:%b\n" "${BOLD}" "${NC}" if [ "$os_name" = "Linux" ] && command -v systemctl &>/dev/null; then - printf " Status: sudo systemctl status ${SERVICE_NAME}\n" - printf " Logs: sudo journalctl -u ${SERVICE_NAME} -f\n" - printf " Stop: sudo systemctl stop ${SERVICE_NAME}\n" - printf " Restart: sudo systemctl restart ${SERVICE_NAME}\n" + printf " Status: sudo systemctl status %s\n" "${SERVICE_NAME}" + printf " Logs: sudo journalctl -u %s -f\n" "${SERVICE_NAME}" + printf " Stop: sudo systemctl stop %s\n" "${SERVICE_NAME}" + printf " Restart: sudo systemctl restart %s\n" "${SERVICE_NAME}" elif [ "$os_name" = "Darwin" ]; then printf " Status: launchctl list | grep rustchain\n" printf " Logs: tail -f /tmp/rustchain-miner.log\n" printf " Stop: launchctl stop com.rustchain.miner\n" fi echo "" - printf " ${BOLD}Links:${NC}\n" + printf " %bLinks:%b\n" "${BOLD}" "${NC}" printf " Website: https://rustchain.org\n" printf " GitHub: https://github.com/Scottcjn/Rustchain\n" printf " Arcade: https://github.com/Scottcjn/rustchain-arcade\n" diff --git a/scripts/test_auto_pay_idempotency.py b/scripts/test_auto_pay_idempotency.py index dcbec9919..598e15763 100644 --- a/scripts/test_auto_pay_idempotency.py +++ b/scripts/test_auto_pay_idempotency.py @@ -277,7 +277,8 @@ def fake_post(url, headers=None, json=None, timeout=None): # stopped only by the atomic Git ref create, which mirrors the real # concurrent workflow race that comment pre-seeding did not exercise. auto_pay.main() - auto_pay.main() + with pytest.raises(RuntimeError, match="auto-pay lock ref already exists"): + auto_pay.main() assert len(created_refs) == 1 assert len(transfer_calls) == 1 diff --git a/setup_miner.py b/setup_miner.py index 67e2bf3c2..83847efcf 100644 --- a/setup_miner.py +++ b/setup_miner.py @@ -20,7 +20,7 @@ MINER_ARTIFACTS = { "Linux": { "url": "https://raw.githubusercontent.com/Scottcjn/Rustchain/main/miners/linux/rustchain_linux_miner.py", - "sha256": "0260d83334007080bc8e4c1d9084b5e52fdd49f0603684106f5120f875cf00b2", + "sha256": "09752064fce0613c470f9f73b47b2ae72215a4c0f6a19fea25e8db4ee2cb6ead", }, "Darwin": { "url": "https://raw.githubusercontent.com/Scottcjn/Rustchain/main/miners/macos/rustchain_mac_miner_v2.5.py", @@ -28,7 +28,7 @@ }, "Windows": { "url": "https://raw.githubusercontent.com/Scottcjn/Rustchain/main/miners/windows/rustchain_windows_miner.py", - "sha256": "99ac84a489ebc8c1987eddc02dfbaf8672a9d440cc2cc9e1166c6ba25f4e8184", + "sha256": "0c081012fc38683f1ba73b4f110eea726375b765ad433e9006e86cbec9405d62", }, } diff --git a/tests/rip302_auth_helpers.py b/tests/rip302_auth_helpers.py new file mode 100644 index 000000000..2954f6a70 --- /dev/null +++ b/tests/rip302_auth_helpers.py @@ -0,0 +1,57 @@ +# SPDX-License-Identifier: MIT +"""Test harness for RIP-302 under RIP-302-SEC / SEC-2 auth. + +Production requires a pinned settlement-authority signature on +accept/dispute/cancel, and proof of control of ``poster_wallet`` on job +create (Ed25519 for keyed wallets, ``X-Admin-Key`` for named/treasury +wallets). Business-logic tests that predate the hardening post plain +requests, so this module supplies an operator-authorised client. + +Import the fixture into a test module to opt in:: + + from tests.rip302_auth_helpers import rip302_authorized # noqa: F401 + +Tests that check the auth gates themselves should not import it. +""" +import os +import re + +import pytest +from flask import Flask +from flask.testing import FlaskClient +from nacl.signing import SigningKey + +import rip302_agent_economy + +SETTLEMENT_KEY = SigningKey(bytes(range(32))) +_SETTLE_PATH = re.compile(r"^/agent/jobs/([^/?]+)/(accept|dispute|cancel)$") + + +def settlement_sig(job_id, action): + return SETTLEMENT_KEY.sign(f"{job_id}:{action}".encode()).signature.hex() + + +class Rip302AuthorizedClient(FlaskClient): + """Adds the operator credentials a real settlement authority would send.""" + + def open(self, *args, **kwargs): + path = args[0] if args and isinstance(args[0], str) else "" + if kwargs.get("method", "GET").upper() == "POST" and path: + path_only = path.split("?", 1)[0] + if path_only.rstrip("/") == "/agent/jobs": + headers = dict(kwargs.get("headers") or {}) + headers.setdefault("X-Admin-Key", os.environ.get("RC_ADMIN_KEY", "")) + kwargs["headers"] = headers + match = _SETTLE_PATH.match(path_only) + body = kwargs.get("json") + if match and isinstance(body, dict) and "settlement_sig" not in body: + kwargs["json"] = {**body, "settlement_sig": settlement_sig(*match.groups())} + return super().open(*args, **kwargs) + + +@pytest.fixture(autouse=True) +def rip302_authorized(monkeypatch): + monkeypatch.setattr(rip302_agent_economy, "SETTLEMENT_PUBKEY_HEX", + SETTLEMENT_KEY.verify_key.encode().hex()) + monkeypatch.setenv("RC_ADMIN_KEY", os.environ.get("RC_ADMIN_KEY") or "0" * 32) + monkeypatch.setattr(Flask, "test_client_class", Rip302AuthorizedClient) diff --git a/tests/test_agent_dispute_accept_race.py b/tests/test_agent_dispute_accept_race.py index 0448b6c88..cfc4952ce 100644 --- a/tests/test_agent_dispute_accept_race.py +++ b/tests/test_agent_dispute_accept_race.py @@ -6,6 +6,7 @@ from flask import Flask import rip302_agent_economy +from tests.rip302_auth_helpers import rip302_authorized # noqa: F401 (autouse: operator-authorised client) def _make_client(tmp_path: Path): diff --git a/tests/test_agent_dispute_redelivery.py b/tests/test_agent_dispute_redelivery.py index edb80d68d..59159a789 100644 --- a/tests/test_agent_dispute_redelivery.py +++ b/tests/test_agent_dispute_redelivery.py @@ -15,6 +15,7 @@ from flask import Flask import rip302_agent_economy +from tests.rip302_auth_helpers import rip302_authorized # noqa: F401 (autouse: operator-authorised client) def _make_app(tmp_path: Path, poster_balance: int = 5_000_000): diff --git a/tests/test_agent_economy_error_redaction.py b/tests/test_agent_economy_error_redaction.py index 81cae76a8..113ee1ca6 100644 --- a/tests/test_agent_economy_error_redaction.py +++ b/tests/test_agent_economy_error_redaction.py @@ -6,6 +6,7 @@ from flask import Flask import rip302_agent_economy +from tests.rip302_auth_helpers import rip302_authorized # noqa: F401 (autouse: operator-authorised client) SECRET_ERROR = "no such table: balances at /srv/rustchain/private.db with super-secret" diff --git a/tests/test_agent_jobs_query_validation.py b/tests/test_agent_jobs_query_validation.py index e9706ee97..c0f5a7f73 100644 --- a/tests/test_agent_jobs_query_validation.py +++ b/tests/test_agent_jobs_query_validation.py @@ -7,6 +7,7 @@ import rip302_agent_economy from rip302_agent_economy import register_agent_economy +from tests.rip302_auth_helpers import rip302_authorized # noqa: F401 (autouse: operator-authorised client) def make_client(tmp_path: Path): diff --git a/tests/test_beacon_atlas_behavior.py b/tests/test_beacon_atlas_behavior.py index cc7ad20e8..118e8e79e 100644 --- a/tests/test_beacon_atlas_behavior.py +++ b/tests/test_beacon_atlas_behavior.py @@ -172,6 +172,22 @@ def _signed_headers(cls, agent_id, method, path, body): 'X-Agent-Signature': signature, } + def test_far_future_signature_timestamp_is_refused(self): + """A far-future timestamp would outlive its nonce record and be + replayable after the nonce is pruned, so it is refused up front.""" + body = json.dumps({'from': 'bcn_alice_test', 'to': 'bcn_bob_test', + 'type': 'rent', 'amount': 1.0, 'term': '1d'}) + headers = self._signed_headers('bcn_alice_test', 'POST', '/api/contracts', body) + future = str(int(time.time()) + 120) + headers['X-Agent-Timestamp'] = future + message = '\n'.join(['POST', '/api/contracts', hashlib.sha256(body.encode()).hexdigest(), + future, headers['X-Agent-Nonce'], 'bcn_alice_test']).encode() + headers['X-Agent-Signature'] = self.agent_keys['bcn_alice_test'].sign(message).hex() + response = self.client.post('/api/contracts', data=body, + content_type='application/json', headers=headers) + self.assertEqual(response.status_code, 401) + self.assertIn('Stale', response.get_json()['error']) + def test_health_endpoint_returns_ok(self): """Health check endpoint returns status ok.""" response = self.client.get('/api/health') diff --git a/tests/test_ergo_anchor_schema_compat.py b/tests/test_ergo_anchor_schema_compat.py index d32b9aad1..250c69c17 100644 --- a/tests/test_ergo_anchor_schema_compat.py +++ b/tests/test_ergo_anchor_schema_compat.py @@ -205,3 +205,52 @@ def test_pending_tx_query_works_on_the_production_schema(self): if __name__ == "__main__": unittest.main(verbosity=2) + + +class ProductionReadPathTest(unittest.TestCase): + """On the production schema rc_slot is frozen (tied on every row) and the tx + column is tx_id. /anchor/status must show the NEWEST anchor, and proof/interval + lookups must not KeyError on the legacy column names.""" + + class _FakeErgo: + def __init__(self): + self.asked = [] + + def get_transaction(self, tx_id): + self.asked.append(tx_id) + return {"id": tx_id} + + def _service(self, db): + return MOD.AnchorService(db_path=db.tmp.name, ergo_client=self._FakeErgo()) + + def _rows(self): + return [{"commitment": f"c{i}", "miner_count": 10, "rc_slot": 2941199, + "tx_id": f"tx{i}", "status": "confirmed", "created_at": 1_700_000_000 + i} + for i in range(1, 6)] + + def test_last_anchor_is_newest_when_heights_tie(self): + db = _DB(PRODUCTION_SCHEMA, self._rows()) + try: + last = self._service(db).get_last_anchor() + self.assertEqual(last["tx_id"], "tx5") + finally: + db.close() + + def test_anchor_proof_uses_legacy_tx_id_column(self): + db = _DB(PRODUCTION_SCHEMA, self._rows()) + try: + svc = self._service(db) + proof = svc.get_anchor_proof(2941199) + self.assertEqual(proof["tx_id"], "tx5") + self.assertEqual(svc.ergo.asked, ["tx5"]) + self.assertEqual(proof["ergo_transaction"], {"id": "tx5"}) + finally: + db.close() + + def test_should_anchor_reads_legacy_height_column(self): + db = _DB(PRODUCTION_SCHEMA, self._rows()) + try: + svc = self._service(db) + self.assertIsInstance(svc.should_anchor(2941199 + 10_000), bool) + finally: + db.close() diff --git a/tests/test_hardware_binding_v2_security.py b/tests/test_hardware_binding_v2_security.py index 6a1e0e6ec..f03ded6d9 100644 --- a/tests/test_hardware_binding_v2_security.py +++ b/tests/test_hardware_binding_v2_security.py @@ -115,3 +115,58 @@ def test_compare_entropy_profiles_marks_sparse_overlap_low_confidence(): assert reason in ('entropy_ok', 'insufficient_comparable_overlap') # comparable overlap is only one field; ensure score does not imply a strong multi-signal match assert score <= 1.0 + + +def test_concurrent_cross_serial_registration_is_serialized(tmp_path, monkeypatch): + """#71 (Ondrej Nad): two first-time registrations of the same physical + machine under different serials, racing. Pre-fix, both collision scans ran + before either INSERT and both bound. Now exactly one may bind. + + A barrier placed just after the collision scan parks the first thread until + the second has also scanned. Unfixed code lets both scan an empty table; + fixed code blocks the second at BEGIN IMMEDIATE, so the barrier times out, + the first commits, and only then does the second scan (and see it). + """ + import threading + + db = tmp_path / 'hb.db' + monkeypatch.setattr(hb, 'DB_PATH', str(db)) + hb.init_hardware_bindings_v2() + + barrier = threading.Barrier(2, timeout=1.5) + real_check = hb.check_entropy_collision + + def racing_check(*args, **kwargs): + # Scan first, then hold at the barrier: this is the exact race window + # (both scans done, neither INSERT yet). Fixed code never lets the + # second thread scan while the first is parked here. + result = real_check(*args, **kwargs) + try: + barrier.wait() + except threading.BrokenBarrierError: + pass + return result + + monkeypatch.setattr(hb, 'check_entropy_collision', racing_check) + + fp = _mk_fingerprint(clock=0.21, l1=100.0, l2=220.0, thermal=1.9, jitter=0.08) + results = [] + + def register(serial, wallet): + results.append(hb.bind_hardware_v2( + serial=serial, wallet=wallet, arch='x86_64', cores=8, fingerprint=fp)) + + threads = [threading.Thread(target=register, args=('SER-A', 'RTCwalletA')), + threading.Thread(target=register, args=('SER-B', 'RTCwalletB'))] + for t in threads: + t.start() + for t in threads: + t.join(timeout=20) + + reasons = sorted(r[1] for r in results) + assert reasons == ['entropy_collision', 'new_binding'], results + conn = sqlite3.connect(str(db)) + try: + assert conn.execute('SELECT COUNT(*) FROM hardware_bindings_v2').fetchone()[0] == 1 + finally: + conn.close() diff --git a/tests/test_measurement_freshness_binding.py b/tests/test_measurement_freshness_binding.py index 15557b554..fff166ece 100644 --- a/tests/test_measurement_freshness_binding.py +++ b/tests/test_measurement_freshness_binding.py @@ -146,7 +146,12 @@ def test_binding_verdict_does_not_touch_weight_yet(self): if isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == "verify_measurement_binding" ] - self.assertEqual(len(calls), 1, "expected exactly one phase-0 call site") + # sybil_guard records the binding STATE for new-miner probation (a + # second call site). It gates weight only behind + # REQUIRE_MEASUREMENT_BINDING_FOR_NEW_PREMIUM, which ships OFF. + self.assertEqual(len(calls), 2, "expected the phase-0 site + the sybil_guard state site") + self.assertIn("REQUIRE_MEASUREMENT_BINDING_FOR_NEW_PREMIUM = False", + open(os.path.join(os.path.dirname(self.SRC), "sybil_guard.py")).read()) self.assertNotIn("measurement_binding_verdict) *", src) self.assertNotIn("hw_weight * measurement_binding", src) diff --git a/tests/test_miner_keystore_machine_entropy.py b/tests/test_miner_keystore_machine_entropy.py new file mode 100644 index 000000000..c5dba3196 --- /dev/null +++ b/tests/test_miner_keystore_machine_entropy.py @@ -0,0 +1,217 @@ +# SPDX-License-Identifier: MIT +"""Keystore key derivation must be per-machine and never a public constant. + +Regression tests for the Windows keystore bug: with no machine-id branch on +Windows, miner_crypto fell back to sha256("fallback-no-machine-id"), so every +Windows keystore was obscured with the same public key material. +""" +import builtins +import hashlib +import importlib.util +import json +import sys +import types +from pathlib import Path + +import pytest + +nacl_signing = pytest.importorskip("nacl.signing") + +REPO_ROOT = Path(__file__).resolve().parents[1] +CRYPTO_PATHS = { + "linux": REPO_ROOT / "miners" / "linux" / "miner_crypto.py", + "windows": REPO_ROOT / "miners" / "windows" / "miner_crypto.py", +} +LEGACY = hashlib.sha256(b"fallback-no-machine-id").digest() +PASSPHRASE_ENV = "RUSTCHAIN_KEYSTORE_PASSPHRASE" + + +def _load(path, name): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +@pytest.fixture(params=sorted(CRYPTO_PATHS)) +def crypto(request): + return _load(CRYPTO_PATHS[request.param], f"miner_crypto_{request.param}_under_test") + + +def _no_machine_id_files(monkeypatch, module): + real_open = builtins.open + + def fake_open(path, *args, **kwargs): + if str(path) in ("/etc/machine-id", "/var/lib/dbus/machine-id"): + raise FileNotFoundError(path) + return real_open(path, *args, **kwargs) + + monkeypatch.setattr(module, "open", fake_open, raising=False) + + +def _fake_winreg(guid): + mod = types.ModuleType("winreg") + mod.HKEY_LOCAL_MACHINE = object() + mod.KEY_READ = 0x20019 + mod.KEY_WOW64_64KEY = 0x0100 + seen = {} + + class _Key: + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def open_key(root, sub_key, reserved=0, access=0): + seen["open"] = (root, sub_key) + if guid is None: + raise FileNotFoundError(sub_key) + return _Key() + + def query_value_ex(key, name): + seen["value"] = name + return guid, 1 + + mod.OpenKey = open_key + mod.QueryValueEx = query_value_ex + mod.seen = seen + return mod + + +def _as_windows(monkeypatch, module, guid): + monkeypatch.setattr(sys, "platform", "win32") + monkeypatch.delenv(PASSPHRASE_ENV, raising=False) + winreg = _fake_winreg(guid) + monkeypatch.setitem(sys.modules, "winreg", winreg) + _no_machine_id_files(monkeypatch, module) + return winreg + + +def test_windows_uses_machine_guid(monkeypatch, crypto): + guid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301" + winreg = _as_windows(monkeypatch, crypto, guid) + + entropy = crypto._get_machine_entropy() + + assert entropy == hashlib.sha256(guid.encode()).digest() + assert entropy != LEGACY + assert winreg.seen["open"][1] == r"SOFTWARE\Microsoft\Cryptography" + assert winreg.seen["value"] == "MachineGuid" + + +def test_different_machine_guids_give_different_keys(monkeypatch, crypto): + _as_windows(monkeypatch, crypto, "guid-machine-a") + key_a = crypto._get_machine_entropy() + _as_windows(monkeypatch, crypto, "guid-machine-b") + key_b = crypto._get_machine_entropy() + + assert key_a != key_b + + +def test_no_identifier_raises_instead_of_constant(monkeypatch, crypto, tmp_path): + _as_windows(monkeypatch, crypto, None) # MachineGuid missing + + with pytest.raises(RuntimeError, match=PASSPHRASE_ENV): + crypto._get_machine_entropy() + + kp = {"private_key": "11" * 32, "public_key": "22" * 32} + with pytest.raises(RuntimeError): + crypto.save_keystore(kp, str(tmp_path / "miner_key.json")) + assert not (tmp_path / "miner_key.json").exists() + + +def test_no_identifier_with_passphrase_uses_passphrase(monkeypatch, crypto): + _as_windows(monkeypatch, crypto, None) + monkeypatch.setenv(PASSPHRASE_ENV, "correct horse battery staple") + key_1 = crypto._get_machine_entropy() + monkeypatch.setenv(PASSPHRASE_ENV, "another passphrase") + key_2 = crypto._get_machine_entropy() + + assert len(key_1) == 32 + assert key_1 != LEGACY + assert key_1 != key_2 + + +def test_linux_machine_id_derivation_unchanged(monkeypatch, crypto): + """Existing Linux keystores must keep decrypting: key = sha256(machine-id).""" + monkeypatch.setattr(sys, "platform", "linux") + real_open = builtins.open + + def fake_open(path, *args, **kwargs): + if str(path) == "/etc/machine-id": + import io + return io.StringIO("abcdef0123456789\n") + return real_open(path, *args, **kwargs) + + monkeypatch.setattr(crypto, "open", fake_open, raising=False) + + assert crypto._get_machine_entropy() == hashlib.sha256(b"abcdef0123456789").digest() + + +def _legacy_keystore(path): + sk = nacl_signing.SigningKey.generate() + priv = bytes(sk) + pub = bytes(sk.verify_key).hex() + obscured = bytes(a ^ b for a, b in zip(priv, LEGACY)) + path.write_text(json.dumps({ + "version": 1, "public_key": pub, "obscured_private": obscured.hex(), + })) + return priv.hex(), pub + + +def test_legacy_fallback_keystore_loads_and_is_migrated(monkeypatch, crypto, tmp_path, capsys): + guid = "machine-guid-for-migration" + _as_windows(monkeypatch, crypto, guid) + ks = tmp_path / "miner_key.json" + priv, pub = _legacy_keystore(ks) + + loaded = crypto.get_or_create_keypair(str(ks)) + + assert loaded == {"private_key": priv, "public_key": pub} + assert "WARNING" in capsys.readouterr().out + + stored = json.loads(ks.read_text()) + real = hashlib.sha256(guid.encode()).digest() + assert stored["public_key"] == pub + assert bytes.fromhex(stored["obscured_private"]) == bytes( + a ^ b for a, b in zip(bytes.fromhex(priv), real) + ) + # No longer recoverable with the public constant. + assert bytes(a ^ b for a, b in zip(bytes.fromhex(stored["obscured_private"]), LEGACY)).hex() != priv + + # Second load uses the real key directly (no legacy path, no warning). + assert crypto.load_keystore(str(ks)) == {"private_key": priv, "public_key": pub} + assert "WARNING" not in capsys.readouterr().out + + +def test_undecryptable_keystore_is_preserved_not_overwritten(monkeypatch, crypto, tmp_path): + _as_windows(monkeypatch, crypto, "some-guid") + ks = tmp_path / "miner_key.json" + ks.write_text(json.dumps({ + "version": 1, "public_key": "33" * 32, "obscured_private": "44" * 32, + })) + original = ks.read_text() + + kp = crypto.get_or_create_keypair(str(ks)) + + backups = list(tmp_path.glob("miner_key.json.unreadable-*")) + assert len(backups) == 1 and backups[0].read_text() == original + assert json.loads(ks.read_text())["public_key"] == kp["public_key"] + + +@pytest.mark.parametrize("platform_dir,filename", [ + ("linux", "rustchain_linux_miner.py"), + ("windows", "rustchain_windows_miner.py"), +]) +def test_crypto_available_false_when_nacl_missing(monkeypatch, platform_dir, filename): + for name in ("nacl", "nacl.signing", "nacl.encoding"): + monkeypatch.setitem(sys.modules, name, None) # import -> ImportError + monkeypatch.delitem(sys.modules, "miner_crypto", raising=False) + monkeypatch.syspath_prepend(str(REPO_ROOT / "miners" / platform_dir)) + + miner = _load(REPO_ROOT / "miners" / platform_dir / filename, + f"{platform_dir}_miner_nacl_missing_under_test") + + assert miner.CRYPTO_AVAILABLE is False + monkeypatch.delitem(sys.modules, "miner_crypto", raising=False) diff --git a/tests/test_pending_confirm_reports_failures.py b/tests/test_pending_confirm_reports_failures.py new file mode 100644 index 000000000..dc3f47c2b --- /dev/null +++ b/tests/test_pending_confirm_reports_failures.py @@ -0,0 +1,147 @@ +# SPDX-License-Identifier: MIT +"""Regression: /pending/confirm must not report ``ok: true`` when rows failed. + +From 2026-09-22 every confirm on the production node raised inside its +savepoint (``mirror_exceeds_balance``) and was rolled back, so no payout was +delivered. The handler still answered ``{"ok": true, "confirmed_count": 0}`` +— a caller that checks ``ok`` read a total delivery stall as a healthy empty +pass. A row that raised stays ``pending`` and was not delivered; ``ok`` must +say so, and the failed ids must be surfaced. +""" +import sqlite3 +import sys +import time +from contextlib import closing + +import pytest + +integrated_node = sys.modules["integrated_node"] + +ADMIN_KEY = "test-admin-key-pending-confirm" +SENDER = "RTC" + "a" * 40 +RECIPIENT = "RTC" + "b" * 40 + + +def _init_db(db_path): + with closing(sqlite3.connect(db_path)) as conn: + conn.executescript( + """ + CREATE TABLE balances ( + miner_id TEXT PRIMARY KEY, + amount_i64 INTEGER NOT NULL + ); + CREATE TABLE pending_ledger ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + ts INTEGER NOT NULL, + epoch INTEGER NOT NULL, + from_miner TEXT NOT NULL, + to_miner TEXT NOT NULL, + amount_i64 INTEGER NOT NULL, + reason TEXT, + status TEXT DEFAULT 'pending', + created_at INTEGER NOT NULL, + confirms_at INTEGER NOT NULL, + tx_hash TEXT, + voided_by TEXT, + voided_reason TEXT, + confirmed_at INTEGER + ); + """ + ) + conn.execute("INSERT INTO balances VALUES (?, ?)", (SENDER, 10_000_000)) + now = int(time.time()) + for i, amount in enumerate((1_000_000, 2_000_000), start=1): + conn.execute( + """ + INSERT INTO pending_ledger + (ts, epoch, from_miner, to_miner, amount_i64, reason, + created_at, confirms_at, tx_hash) + VALUES (?, 1, ?, ?, ?, 'test', ?, ?, ?) + """, + (now - 100, SENDER, RECIPIENT, amount, now - 100, now - 1, f"tx{i}"), + ) + conn.commit() + + +@pytest.fixture +def client(tmp_path, monkeypatch): + db_path = tmp_path / "confirm.sqlite3" + _init_db(db_path) + monkeypatch.setattr(integrated_node, "DB_PATH", str(db_path)) + monkeypatch.setenv("RC_ADMIN_KEY", ADMIN_KEY) + alerts = [] + monkeypatch.setattr( + integrated_node, "send_sophiacheck_alert", + lambda level, msg, data=None: alerts.append((level, msg)), + ) + integrated_node.app.config["TESTING"] = True + # The admin rate limiter is per-process and keyed by client IP; clear it so + # these admin calls neither trip it nor leak budget into later tests. + integrated_node._ADMIN_RATE_LIMIT_BUCKETS.clear() + with integrated_node.app.test_client() as c: + c.db_path = db_path + c.alerts = alerts + yield c + integrated_node._ADMIN_RATE_LIMIT_BUCKETS.clear() + + +def _statuses(db_path): + with closing(sqlite3.connect(db_path)) as conn: + return dict(conn.execute("SELECT id, status FROM pending_ledger").fetchall()) + + +def test_all_rows_failing_is_not_ok(client, monkeypatch): + def _boom(*_args, **_kwargs): + raise RuntimeError("mirror_exceeds_balance:simulated") + + monkeypatch.setattr(integrated_node, "_settle_account_transfer_in_utxo", _boom) + resp = client.post("/pending/confirm", headers={"X-Admin-Key": ADMIN_KEY}) + + assert resp.status_code == 200 + body = resp.get_json() + assert body["confirmed_count"] == 0 + assert body["ok"] is False, "a pass that delivered nothing because every row raised is not ok" + assert body["failed_count"] == 2 + assert body["failed_ids"] == [1, 2] + assert _statuses(client.db_path) == {1: "pending", 2: "pending"} + assert any(level == "critical" for level, _ in client.alerts) + + +def test_partial_failure_is_not_ok(client, monkeypatch): + real = integrated_node._settle_account_transfer_in_utxo + + def _fail_second(c, from_m, to_m, amount, epoch, tx_hash, now): + if tx_hash == "tx2": + raise RuntimeError("simulated") + return real(c, from_m, to_m, amount, epoch, tx_hash, now) + + monkeypatch.setattr(integrated_node, "_settle_account_transfer_in_utxo", _fail_second) + body = client.post("/pending/confirm", headers={"X-Admin-Key": ADMIN_KEY}).get_json() + + assert body["confirmed_ids"] == [1] + assert body["failed_ids"] == [2] + assert body["ok"] is False + assert _statuses(client.db_path) == {1: "confirmed", 2: "pending"} + + +def test_clean_pass_is_ok(client): + body = client.post("/pending/confirm", headers={"X-Admin-Key": ADMIN_KEY}).get_json() + + assert body["ok"] is True + assert body["confirmed_ids"] == [1, 2] + assert body["failed_count"] == 0 + assert body["failed_ids"] == [] + assert not any(level == "critical" for level, _ in client.alerts) + + +def test_insufficient_balance_void_is_a_resolution_not_a_failure(client): + with closing(sqlite3.connect(client.db_path)) as conn: + conn.execute("UPDATE balances SET amount_i64 = 0") + conn.commit() + + body = client.post("/pending/confirm", headers={"X-Admin-Key": ADMIN_KEY}).get_json() + + assert body["ok"] is True + assert body["failed_count"] == 0 + assert [e["error"] for e in body["errors"]] == ["insufficient_balance"] * 2 + assert _statuses(client.db_path) == {1: "voided", 2: "voided"} diff --git a/tests/test_pending_integrity_ledger_only_wallets.py b/tests/test_pending_integrity_ledger_only_wallets.py new file mode 100644 index 000000000..d34d08ca9 --- /dev/null +++ b/tests/test_pending_integrity_ledger_only_wallets.py @@ -0,0 +1,114 @@ +# SPDX-License-Identifier: MIT +"""Regression: /pending/integrity must see wallets that exist only in the ledger. + +The check walked the ``balances`` table and compared each row to its ledger +sum. A wallet with ledger credits but no balance row was never visited, so RTC +the ledger says was paid — but that no balance row holds — reported +``ok: true``. The check must cover the union of both sides. +""" +import sqlite3 +import sys +from contextlib import closing + +import pytest + +integrated_node = sys.modules["integrated_node"] + +ADMIN_KEY = "test-admin-key-integrity" + + +@pytest.fixture +def client(tmp_path, monkeypatch): + db_path = tmp_path / "integrity.sqlite3" + with closing(sqlite3.connect(db_path)) as conn: + conn.executescript( + """ + CREATE TABLE balances (miner_id TEXT PRIMARY KEY, amount_i64 INTEGER NOT NULL); + CREATE TABLE ledger ( + id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, + epoch INTEGER NOT NULL, miner_id TEXT NOT NULL, + delta_i64 INTEGER NOT NULL, reason TEXT + ); + CREATE TABLE pending_ledger ( + id INTEGER PRIMARY KEY AUTOINCREMENT, from_miner TEXT, + amount_i64 INTEGER, status TEXT + ); + """ + ) + # A consistent wallet: balance == ledger sum. + conn.execute("INSERT INTO balances VALUES ('alice', 3000000)") + conn.execute("INSERT INTO ledger (ts, epoch, miner_id, delta_i64, reason) " + "VALUES (1, 1, 'alice', 3000000, 'epoch_1_reward')") + conn.commit() + monkeypatch.setattr(integrated_node, "DB_PATH", str(db_path)) + monkeypatch.setenv("RC_ADMIN_KEY", ADMIN_KEY) + monkeypatch.setattr(integrated_node, "send_sophiacheck_alert", lambda *a, **k: None) + integrated_node.app.config["TESTING"] = True + # The admin rate limiter is per-process and keyed by client IP; clear it so + # these admin calls neither trip it nor leak budget into later tests. + integrated_node._ADMIN_RATE_LIMIT_BUCKETS.clear() + with integrated_node.app.test_client() as c: + c.db_path = db_path + yield c + integrated_node._ADMIN_RATE_LIMIT_BUCKETS.clear() + + +def _check(client): + resp = client.get("/pending/integrity", headers={"X-Admin-Key": ADMIN_KEY}) + assert resp.status_code == 200 + return resp.get_json() + + +def test_consistent_books_are_ok(client): + body = _check(client) + assert body["ok"] is True + assert body["mismatches"] is None + assert body["total_miners_checked"] == 1 + + +def test_ledger_credit_without_balance_row_is_a_mismatch(client): + with closing(sqlite3.connect(client.db_path)) as conn: + conn.execute("INSERT INTO ledger (ts, epoch, miner_id, delta_i64, reason) " + "VALUES (2, 1, 'bob', 5000000, 'transfer_in:alice:tx')") + conn.commit() + + body = _check(client) + + assert body["ok"] is False, "5 RTC in the ledger with no balance row must not pass" + assert body["total_miners_checked"] == 2 + assert body["mismatches"] == [{ + "miner_id": "bob", + "balance_rtc": 0.0, + "ledger_sum_rtc": 5.0, + "diff_rtc": -5.0, + "balance_row_missing": True, + }] + + +def test_balance_without_ledger_is_still_a_mismatch(client): + with closing(sqlite3.connect(client.db_path)) as conn: + conn.execute("INSERT INTO balances VALUES ('carol', 700000)") + conn.commit() + + body = _check(client) + + assert body["ok"] is False + assert body["mismatches"] == [{ + "miner_id": "carol", + "balance_rtc": 0.7, + "ledger_sum_rtc": 0.0, + "diff_rtc": 0.7, + }] + + +def test_ledger_entries_netting_to_zero_without_balance_row_are_ok(client): + with closing(sqlite3.connect(client.db_path)) as conn: + conn.executemany( + "INSERT INTO ledger (ts, epoch, miner_id, delta_i64, reason) VALUES (?, 1, 'dave', ?, 'x')", + [(3, 1000), (4, -1000)], + ) + conn.commit() + + body = _check(client) + assert body["ok"] is True + assert body["total_miners_checked"] == 2 diff --git a/tests/test_pending_ops.py b/tests/test_pending_ops.py index be5e86cba..7137191da 100644 --- a/tests/test_pending_ops.py +++ b/tests/test_pending_ops.py @@ -147,7 +147,7 @@ def fake_req(method, url, admin_key, payload=None, *, insecure): "insecure": insecure, } ) - return {"confirmed": 2} + return {"ok": True, "confirmed": 2, "overdue_stats_measured": True} monkeypatch.setattr(pending_ops, "_req", fake_req) args = argparse.Namespace(node="https://node.test", admin_key="admin-secret", insecure=False) @@ -160,7 +160,7 @@ def fake_req(method, url, admin_key, payload=None, *, insecure): "payload": {}, "insecure": False, } - assert json.loads(capsys.readouterr().out) == {"confirmed": 2} + assert json.loads(capsys.readouterr().out) == {"ok": True, "confirmed": 2, "overdue_stats_measured": True} def test_main_rejects_missing_admin_key(monkeypatch, capsys): diff --git a/tests/test_pending_ops_cli.py b/tests/test_pending_ops_cli.py index e5f5d2d02..0fd2a191c 100644 --- a/tests/test_pending_ops_cli.py +++ b/tests/test_pending_ops_cli.py @@ -119,7 +119,7 @@ def test_cmd_confirm_posts_empty_payload(capsys): module = load_module() args = argparse.Namespace(node="https://node.example/", admin_key="key", insecure=False) - with patch.object(module, "_req", return_value={"confirmed": 2}) as req: + with patch.object(module, "_req", return_value={"ok": True, "confirmed": 2, "overdue_stats_measured": True}) as req: assert module.cmd_confirm(args) == 0 req.assert_called_once_with( @@ -155,3 +155,59 @@ def raise_http_error(args): assert module.main(["--admin-key", "key", "confirm"]) == 1 assert "HTTP 403: denied" in capsys.readouterr().err + + +def _confirm_with(module, response): + args = argparse.Namespace(node="https://node.example/", admin_key="key", insecure=False) + with patch.object(module, "_req", return_value=response): + return module.cmd_confirm(args) + + +def test_cmd_confirm_exits_nonzero_when_rows_failed(capsys): + """Every row raised and stayed pending: must not exit 0 (false green).""" + module = load_module() + rc = _confirm_with(module, { + "ok": False, "confirmed_count": 0, "failed_count": 2, "failed_ids": [1, 2], + "errors": [{"id": 1, "error": "internal_error"}, {"id": 2, "error": "internal_error"}], + "overdue_stats_measured": True, + }) + assert rc == 1 + assert "failed_ids=[1, 2]" in capsys.readouterr().err + + +def test_cmd_confirm_exits_nonzero_on_unexpected_shape(): + module = load_module() + assert _confirm_with(module, {"confirmed_count": 0}) == 1 + + +def test_cmd_confirm_exits_nonzero_when_queue_unmeasured(capsys): + module = load_module() + rc = _confirm_with(module, { + "ok": True, "confirmed_count": 0, "stale_pending_count": None, + "overdue_stats_measured": False, "overdue_stats_error": "OperationalError: database is locked", + }) + assert rc == 1 + assert "could not be measured" in capsys.readouterr().err + + +def test_cmd_confirm_exits_zero_on_healthy_pass(): + module = load_module() + assert _confirm_with(module, { + "ok": True, "confirmed_count": 3, "failed_count": 0, "failed_ids": [], + "overdue_stats_measured": True, "stale_pending_count": 0, + }) == 0 + + +def test_cmd_confirm_exits_nonzero_when_measurement_missing(capsys): + """No overdue_stats_measured field (old node / proxy body): fail closed.""" + module = load_module() + assert _confirm_with(module, {"ok": True, "confirmed_count": 0}) == 1 + assert "measurement not reported" in capsys.readouterr().err + + +def test_cmd_confirm_exits_nonzero_when_measurement_null(capsys): + module = load_module() + assert _confirm_with(module, { + "ok": True, "confirmed_count": 0, "overdue_stats_measured": None, + }) == 1 + assert "overdue_stats_measured=None" in capsys.readouterr().err diff --git a/tests/test_rewards_module_import.py b/tests/test_rewards_module_import.py new file mode 100644 index 000000000..6bbeed6f8 --- /dev/null +++ b/tests/test_rewards_module_import.py @@ -0,0 +1,121 @@ +# SPDX-License-Identifier: MIT +"""Regression: the node's best-effort rewards import must actually succeed. + +Production ran for months with HAVE_REWARDS False because the node imported +``_epoch_eligible_miners`` (never defined in rewards_implementation_rip200) and +later called ``register_rewards`` (the module defines ``register_rewards_rip200``). +The import sits in try/except, so the only symptom was a "WARN: Rewards module +not loaded" line on every worker start. Fixed on main by #8249; these tests pin it. +""" + +import ast +import sqlite3 +import sys +from pathlib import Path + +import pytest + +import rewards_implementation_rip200 as rewards + +integrated_node = sys.modules["integrated_node"] + +NODE_SRC = Path(__file__).resolve().parent.parent / "node" / "rustchain_v2_integrated_v2.2.1_rip200.py" +ADMIN_KEY = "0" * 32 # set by tests/conftest.py before the node module loads + + +def _node_tree(): + return ast.parse(NODE_SRC.read_text(encoding="utf-8")) + + +def test_every_name_imported_from_rewards_module_exists(): + imported = [ + alias.name + for node in ast.walk(_node_tree()) + if isinstance(node, ast.ImportFrom) and node.module == "rewards_implementation_rip200" + for alias in node.names + ] + assert imported, "node no longer imports from rewards_implementation_rip200" + missing = [name for name in imported if not hasattr(rewards, name)] + assert missing == [], f"node imports names the rewards module does not define: {missing}" + + +def test_node_loads_rewards_module(): + assert integrated_node.HAVE_REWARDS is True + assert integrated_node.settle_epoch.__name__ == "settle_epoch_rip200" + assert integrated_node.settle_epoch.__module__ == "rewards_implementation_rip200" + assert integrated_node.total_balances.__module__ == "rewards_implementation_rip200" + + +def test_node_never_registers_module_routes(): + """register_rewards_rip200 would shadow the native public balance handlers.""" + calls = [ + node.func.id if isinstance(node.func, ast.Name) else node.func.attr + for node in ast.walk(_node_tree()) + if isinstance(node, ast.Call) and isinstance(node.func, (ast.Name, ast.Attribute)) + ] + assert not [c for c in calls if c.startswith("register_rewards")] + + +@pytest.mark.parametrize( + "rule, method, endpoint", + [ + ("/rewards/settle", "POST", "api_rewards_settle"), + ("/consensus/round_robin_status", "GET", "consensus_round_robin_status"), + ("/wallet/balance", "GET", "api_wallet_balance"), + ("/wallet/balances/all", "GET", "api_wallet_balances_all"), + ("/lottery/eligibility", "GET", "lottery_eligibility"), + ], +) +def test_reward_routes_are_the_native_handlers(rule, method, endpoint): + rules = [r for r in integrated_node.app.url_map.iter_rules() if r.rule == rule] + assert len(rules) == 1, f"{rule} registered {len(rules)} times" + assert rules[0].endpoint == endpoint + assert method in rules[0].methods + assert integrated_node.app.view_functions[endpoint].__module__ == "integrated_node" + + +@pytest.fixture +def client(monkeypatch): + monkeypatch.setenv("RC_ADMIN_KEY", ADMIN_KEY) + integrated_node.app.config["TESTING"] = True + with integrated_node.app.test_client() as test_client: + yield test_client + + +@pytest.mark.parametrize( + "method, path", + [("post", "/rewards/settle"), ("get", "/consensus/round_robin_status")], +) +@pytest.mark.parametrize("headers", [{}, {"X-Admin-Key": "wrong"}]) +def test_admin_reward_routes_reject_missing_or_wrong_key(client, method, path, headers): + response = getattr(client, method)(path, headers=headers, json={"epoch": 0}) + assert response.status_code == 401 + + +@pytest.mark.parametrize( + "method, path", + [("post", "/rewards/settle"), ("get", "/consensus/round_robin_status")], +) +def test_admin_reward_routes_disabled_when_admin_key_unset(client, monkeypatch, method, path): + monkeypatch.delenv("RC_ADMIN_KEY", raising=False) + response = getattr(client, method)(path, headers={"X-Admin-Key": ""}, json={"epoch": 0}) + assert response.status_code == 503 + + +def test_settle_fails_closed_without_rewards_module(client, monkeypatch): + monkeypatch.setattr(integrated_node, "HAVE_REWARDS", False) + monkeypatch.setattr(integrated_node, "settle_epoch", None) + unauth = client.post("/rewards/settle", json={"epoch": 0}) + assert unauth.status_code == 401 # auth still checked first + response = client.post("/rewards/settle", headers={"X-Admin-Key": ADMIN_KEY}, json={"epoch": 0}) + assert response.status_code == 503 + assert response.get_json()["code"] == "REWARDS_MODULE_UNAVAILABLE" + + +def test_native_total_balances_matches_module(): + db = sqlite3.connect(":memory:") + assert integrated_node._native_total_balances(db) == rewards.total_balances(db) == 0 # no table + db.execute("CREATE TABLE balances (miner_id TEXT PRIMARY KEY, amount_i64 INTEGER)") + assert integrated_node._native_total_balances(db) == rewards.total_balances(db) == 0 + db.executemany("INSERT INTO balances VALUES (?, ?)", [("a", 1_500_000), ("b", 250)]) + assert integrated_node._native_total_balances(db) == rewards.total_balances(db) == 1_500_250 diff --git a/tests/test_rip302_auth_gates.py b/tests/test_rip302_auth_gates.py new file mode 100644 index 000000000..533449397 --- /dev/null +++ b/tests/test_rip302_auth_gates.py @@ -0,0 +1,138 @@ +# SPDX-License-Identifier: MIT +"""RIP-302-SEC / SEC-2 auth gates. + +Before these gates, poster_wallet and worker_wallet were plain strings: anyone +could post a job as another wallet (moving its balance into escrow) or accept a +delivery as the poster (releasing that escrow). These tests pin the gates shut. +Deliberately does NOT use the operator-authorised client from +rip302_auth_helpers. +""" +import hashlib +import sqlite3 + +import pytest +from flask import Flask +from nacl.signing import SigningKey + +import rip302_agent_economy as r302 +from tests.rip302_auth_helpers import SETTLEMENT_KEY, settlement_sig + +ADMIN_KEY = "a" * 64 +JOB = { + "title": "Write a scraper", + "description": "Scrape the public listing page and return a CSV of rows.", + "category": "code", + "reward_rtc": 1, +} + + +@pytest.fixture +def env(tmp_path, monkeypatch): + monkeypatch.setattr(r302, "SETTLEMENT_PUBKEY_HEX", SETTLEMENT_KEY.verify_key.encode().hex()) + monkeypatch.setenv("RC_ADMIN_KEY", ADMIN_KEY) + db = tmp_path / "jobs.db" + app = Flask(__name__) + r302.register_agent_economy(app, str(db)) + user = SigningKey(bytes([7] * 32)) + pub = user.verify_key.encode().hex() + wallet = "RTC" + hashlib.sha256(bytes.fromhex(pub)).hexdigest()[:40] + with sqlite3.connect(db) as conn: + conn.execute("CREATE TABLE balances (miner_id TEXT PRIMARY KEY, amount_i64 INTEGER NOT NULL)") + conn.executemany("INSERT INTO balances VALUES (?, ?)", + [("poster", 50_000_000), (wallet, 50_000_000)]) + return {"client": app.test_client(), "db": db, "key": user, "pub": pub, "wallet": wallet} + + +def _balance(db, wallet): + with sqlite3.connect(db) as conn: + row = conn.execute("SELECT amount_i64 FROM balances WHERE miner_id = ?", (wallet,)).fetchone() + return row[0] if row else 0 + + +def _signed_create(env, nonce="n1", **over): + body = {**JOB, "poster_wallet": env["wallet"], "nonce": nonce, **over} + reward, _ = r302._parse_job_reward(body["reward_rtc"]) + msg = r302._create_job_message(env["wallet"], nonce, reward, body["category"]) + body["poster_pubkey"] = env["pub"] + body["poster_sig"] = env["key"].sign(msg).signature.hex() + return body + + +def test_named_wallet_create_needs_admin_key(env): + c = env["client"] + r = c.post("/agent/jobs", json={**JOB, "poster_wallet": "poster"}) + assert r.status_code == 401 and r.get_json()["code"] == "ADMIN_KEY_REQUIRED" + r = c.post("/agent/jobs", json={**JOB, "poster_wallet": "poster"}, + headers={"X-Admin-Key": "wrong"}) + assert r.status_code == 401 + assert _balance(env["db"], "poster") == 50_000_000 + r = c.post("/agent/jobs", json={**JOB, "poster_wallet": "poster"}, + headers={"X-Admin-Key": ADMIN_KEY}) + assert r.status_code == 201 + + +def test_keyed_wallet_create_needs_its_own_signature(env): + c = env["client"] + r = c.post("/agent/jobs", json={**JOB, "poster_wallet": env["wallet"]}) + assert r.status_code == 401 and r.get_json()["code"] == "SIG_REQUIRED" + # Someone else's key can't post as this wallet. + forged = _signed_create(env) + forged["poster_pubkey"] = SigningKey(bytes([9] * 32)).verify_key.encode().hex() + assert c.post("/agent/jobs", json=forged).status_code == 401 + # A signature for 1 RTC can't be replayed onto 500 RTC. + tampered = {**_signed_create(env), "reward_rtc": 500} + assert c.post("/agent/jobs", json=tampered).status_code == 401 + assert _balance(env["db"], env["wallet"]) == 50_000_000 + assert c.post("/agent/jobs", json=_signed_create(env)).status_code == 201 + + +def test_create_signature_is_single_use(env): + c = env["client"] + body = _signed_create(env, nonce="once") + assert c.post("/agent/jobs", json=body).status_code == 201 + assert c.post("/agent/jobs", json=body).status_code in (400, 401, 409) + + +def test_create_refused_without_settlement_key(env, monkeypatch): + monkeypatch.setattr(r302, "SETTLEMENT_PUBKEY_HEX", "") + r = env["client"].post("/agent/jobs", json=_signed_create(env)) + assert r.status_code == 400 and "signed_settlement_unavailable" in r.get_json()["error"] + + +def _delivered_job(env): + c = env["client"] + job_id = c.post("/agent/jobs", json=_signed_create(env)).get_json()["job_id"] + assert c.post(f"/agent/jobs/{job_id}/claim", json={"worker_wallet": "worker"}).status_code == 200 + assert c.post(f"/agent/jobs/{job_id}/deliver", json={ + "worker_wallet": "worker", "result_summary": "done", + "deliverable_url": "https://example.com/out.csv"}).status_code == 200 + return job_id + + +@pytest.mark.parametrize("action", ["accept", "dispute"]) +def test_settlement_needs_authority_signature(env, action): + c = env["client"] + job_id = _delivered_job(env) + body = {"poster_wallet": env["wallet"], "reason": "not what I asked for"} + # Knowing the poster string is no longer enough. + assert c.post(f"/agent/jobs/{job_id}/{action}", json=body).status_code in (401, 403) + # A signature for another job or another action doesn't transfer. + for sig in (settlement_sig("other-job", action), + settlement_sig(job_id, "cancel" if action != "cancel" else "accept"), + SigningKey(bytes([3] * 32)).sign(f"{job_id}:{action}".encode()).signature.hex()): + r = c.post(f"/agent/jobs/{job_id}/{action}", json={**body, "settlement_sig": sig}) + assert r.status_code in (401, 403) + assert _balance(env["db"], "worker") == 0 + r = c.post(f"/agent/jobs/{job_id}/{action}", + json={**body, "settlement_sig": settlement_sig(job_id, action)}) + assert r.status_code == 200 + + +def test_cancel_needs_authority_signature(env): + c = env["client"] + job_id = c.post("/agent/jobs", json=_signed_create(env)).get_json()["job_id"] + body = {"poster_wallet": env["wallet"]} + assert c.post(f"/agent/jobs/{job_id}/cancel", json=body).status_code in (401, 403) + r = c.post(f"/agent/jobs/{job_id}/cancel", + json={**body, "settlement_sig": settlement_sig(job_id, "cancel")}) + assert r.status_code == 200 diff --git a/tests/test_sophia_elya_legacy_settlement_guard.py b/tests/test_sophia_elya_legacy_settlement_guard.py new file mode 100644 index 000000000..8badcab60 --- /dev/null +++ b/tests/test_sophia_elya_legacy_settlement_guard.py @@ -0,0 +1,140 @@ +# SPDX-License-Identifier: MIT +"""node/sophia_elya_service.py is a legacy RIP-0005 prototype, not the node. + +It carries its own epoch enrollment + settlement writers with none of the real +node's protections (probation/Sybil holds, anti-double-mining, hardware binding, +fingerprint validation), hands out enrollment tickets from an unauthenticated +/attest/submit, and defaults to the relative DB path "./rustchain_v2.db" -- the +same filename the real node uses. These tests pin that its money paths fail +closed by default, and refuse a consensus-shaped DB even when opted in. +""" +import importlib.util +import os +import sqlite3 +import subprocess +import sys +import time +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +SRC = ROOT / "node" / "sophia_elya_service.py" +ENV = "RUSTCHAIN_SOPHIA_ELYA_LEGACY_SETTLEMENT" + + +@pytest.fixture +def svc(tmp_path, monkeypatch): + monkeypatch.delenv(ENV, raising=False) + spec = importlib.util.spec_from_file_location("sophia_elya_guard_under_test", SRC) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + mod.DB_PATH = str(tmp_path / "rustchain_v2.db") + mod.app.config["TESTING"] = True + return mod + + +def _tables(path): + if not os.path.exists(path): + return set() + with sqlite3.connect(path) as c: + return {r[0] for r in c.execute("SELECT name FROM sqlite_master WHERE type='table'")} + + +def test_money_paths_fail_closed_by_default(svc): + for call in ( + svc.init_db, + lambda: svc.enroll_epoch(1, "miner", 1.0), + lambda: svc.finalize_epoch(1, 1.5), + lambda: svc.inc_epoch_block(1), + ): + with pytest.raises(svc.LegacySettlementDisabled, match="rustchain_v2_integrated"): + call() + assert not os.path.exists(svc.DB_PATH) # nothing created, nothing written + + +def test_enroll_route_refuses_without_consuming_ticket(svc): + svc.tickets_db["t1"] = {"expires_at": time.time() + 60} + resp = svc.app.test_client().post( + "/epoch/enroll", json={"miner_pubkey": "sybil", "ticket_id": "t1"} + ) + assert resp.status_code == 503 + assert resp.get_json()["reason"] == "legacy_settlement_disabled" + assert "t1" in svc.tickets_db + assert "epoch_enroll" not in _tables(svc.DB_PATH) + + +def test_submit_block_route_refuses_before_settlement_or_accounting(svc): + before = svc.LAST_HASH_B3 + resp = svc.app.test_client().post( + "/api/submit_block", + json={"header": {"prev_hash_b3": before, "slot": 5}, "header_ext": {}}, + ) + assert resp.status_code == 503 + assert resp.get_json()["reason"] == "legacy_settlement_disabled" + assert svc.LAST_HASH_B3 == before + assert svc.LAST_EPOCH is None + assert not os.path.exists(svc.DB_PATH) + + +def _make_consensus_db(path, *, with_attest_table): + with sqlite3.connect(path) as c: + c.execute( + "CREATE TABLE balances (miner_id TEXT PRIMARY KEY NOT NULL, " + "amount_i64 INTEGER NOT NULL DEFAULT 0, miner_pk TEXT, " + "balance_rtc REAL DEFAULT 0.0, coinbase_address TEXT)" + ) + c.execute( + "CREATE TABLE epoch_enroll (epoch INTEGER, miner_pk TEXT, weight INTEGER, " + "PRIMARY KEY (epoch, miner_pk))" + ) + c.execute( + "CREATE TABLE epoch_state (epoch INTEGER PRIMARY KEY, accepted_blocks INTEGER " + "DEFAULT 0, finalized INTEGER DEFAULT 0, settled INTEGER DEFAULT 0, settled_ts INTEGER)" + ) + c.execute("INSERT INTO epoch_state VALUES (7, 3, 0, 0, NULL)") + c.execute("INSERT INTO epoch_enroll VALUES (7, 'honest', 1)") + if with_attest_table: + c.execute("CREATE TABLE miner_attest_recent (miner TEXT PRIMARY KEY, ts_ok INTEGER)") + + +@pytest.mark.parametrize("with_attest_table", [True, False]) +def test_opt_in_still_refuses_consensus_node_db(svc, monkeypatch, with_attest_table): + monkeypatch.setenv(ENV, "1") + _make_consensus_db(svc.DB_PATH, with_attest_table=with_attest_table) + with sqlite3.connect(svc.DB_PATH) as c: + before = c.execute("SELECT * FROM epoch_enroll ORDER BY miner_pk").fetchall() + + for call in ( + svc.init_db, + lambda: svc.enroll_epoch(7, "sybil", 2.5), + lambda: svc.finalize_epoch(7, 1.5), + lambda: svc.inc_epoch_block(7), + ): + with pytest.raises(svc.LegacySettlementDisabled, match="consensus node database"): + call() + + with sqlite3.connect(svc.DB_PATH) as c: + assert c.execute("SELECT * FROM epoch_enroll ORDER BY miner_pk").fetchall() == before + assert c.execute("SELECT settled, accepted_blocks FROM epoch_state WHERE epoch=7").fetchone() == (0, 3) + + +def test_opt_in_sandbox_db_still_works(svc, monkeypatch): + monkeypatch.setenv(ENV, "1") + svc.init_db() + svc.inc_epoch_block(9) + svc.enroll_epoch(9, "m", 1.0) + result = svc.finalize_epoch(9, 1.5) + assert result["ok"] is True + assert result["payouts"] == [("m", 1.5)] + + +def test_running_as_main_refuses_to_start(tmp_path): + env = {k: v for k, v in os.environ.items() if k != ENV} + proc = subprocess.run( + [sys.executable, str(SRC)], cwd=tmp_path, env=env, + capture_output=True, text=True, timeout=60, + ) + assert proc.returncode != 0 + assert "refusing to start" in proc.stderr + assert not (tmp_path / "rustchain_v2.db").exists() diff --git a/tests/test_utxo_mempool_eviction_failure_surfaced.py b/tests/test_utxo_mempool_eviction_failure_surfaced.py new file mode 100644 index 000000000..8a1cc969c --- /dev/null +++ b/tests/test_utxo_mempool_eviction_failure_surfaced.py @@ -0,0 +1,447 @@ +# SPDX-License-Identifier: MIT +"""Stale-mempool eviction after a spend must not fail silently (#2819). + +Reported by @expertedgevault-rgb: apply_transaction() swallowed every error +from _evict_stale_data_input_txs() (and the helper itself swallowed its own +errors and returned 0), so a committed spend could report success while +mempool txs depending on the spent boxes silently stayed in the pool. + +Contract pinned here: + * normal cleanup removes every dependent (input claim or data_input), + on both the own-connection and caller-connection paths; + * a cleanup failure never rolls back / corrupts the spend, but is logged + at ERROR (with tx_id + spent box ids) and counted; + * on a caller's connection a failed eviction is all-or-nothing (no + orphaned claim rows riding along on the caller's COMMIT); + * if SQLite aborts the caller's whole transaction during eviction, + apply_transaction() raises instead of returning a false True. + +Failures are injected with real SQLite triggers where possible, so the +real error paths run rather than mocks. +""" +import logging +import sqlite3 + +import pytest + +from node import utxo_db as utxo_mod +from node.utxo_db import UtxoDB + + +@pytest.fixture +def db(tmp_path): + instance = UtxoDB(str(tmp_path / "utxo.db")) + instance.init_tables() + return instance + + +def _mint(db, address, value, height): + assert db.apply_transaction({ + "tx_type": "mining_reward", + "inputs": [], + "outputs": [{"address": address, "value_nrtc": value}], + "fee_nrtc": 0, + "data_inputs": [], + "_allow_minting": True, + }, block_height=height) + conn = db._conn() + try: + return conn.execute( + "SELECT box_id FROM utxo_boxes WHERE owner_address=? AND spent_at IS NULL", + (address,), + ).fetchone()["box_id"] + finally: + conn.close() + + +def _setup(db): + """spend_box gets spent; dep_input spends it in mempool; dep_data reads it.""" + spend_box = _mint(db, "addr_spend", 10_000, 1) + other_box = _mint(db, "addr_other", 20_000, 2) + third_box = _mint(db, "addr_third", 30_000, 3) + # Dependent via data_input only (its own claim is on other_box). + assert db.mempool_add({ + "tx_id": "dep_data", + "tx_type": "transfer", + "inputs": [{"box_id": other_box, "spending_proof": "p"}], + "data_inputs": [spend_box], + "outputs": [{"address": "addr_x", "value_nrtc": 19_900}], + "fee_nrtc": 100, + }) + # Unrelated mempool tx that must survive. + assert db.mempool_add({ + "tx_id": "unrelated", + "tx_type": "transfer", + "inputs": [{"box_id": third_box, "spending_proof": "p"}], + "outputs": [{"address": "addr_y", "value_nrtc": 29_900}], + "fee_nrtc": 100, + }) + spend_tx = { + "tx_type": "transfer", + "inputs": [{"box_id": spend_box, "spending_proof": "p"}], + "outputs": [{"address": "addr_to", "value_nrtc": 9_900}], + "fee_nrtc": 100, + "data_inputs": [], + "timestamp": 1_700_000_000, + } + return spend_box, other_box, spend_tx + + +def _state(db, spend_box, other_box): + conn = db._conn() + try: + return { + "spent_at": conn.execute( + "SELECT spent_at FROM utxo_boxes WHERE box_id=?", (spend_box,) + ).fetchone()["spent_at"], + "confirmed_txs": conn.execute( + "SELECT COUNT(*) AS n FROM utxo_transactions WHERE tx_type='transfer'" + ).fetchone()["n"], + "mempool": {r["tx_id"] for r in conn.execute("SELECT tx_id FROM utxo_mempool")}, + "other_claim": conn.execute( + "SELECT tx_id FROM utxo_mempool_inputs WHERE box_id=?", (other_box,) + ).fetchone(), + } + finally: + conn.close() + + +def _add_trigger(db, action): + conn = db._conn() + try: + conn.execute( + "CREATE TRIGGER fail_mempool_delete BEFORE DELETE ON utxo_mempool " + f"BEGIN SELECT RAISE({action}, 'injected eviction failure'); END" + ) + conn.commit() + finally: + conn.close() + + +SQLITE_SAVEPOINT = getattr(sqlite3, "SQLITE_SAVEPOINT", 32) +EVICT_SAVEPOINT = "utxo_evict_stale_mempool" + + +def _deny_savepoint_op(op): + """Authorizer denying one savepoint operation ('RELEASE' / 'ROLLBACK') + on the eviction savepoint only; everything else (incl. the caller's + BEGIN/COMMIT) is allowed.""" + def auth(action, arg1, arg2, _db, _src): + if (action == SQLITE_SAVEPOINT and arg1 == op + and arg2 == EVICT_SAVEPOINT): + return sqlite3.SQLITE_DENY + return sqlite3.SQLITE_OK + return auth + + +def _apply_on_caller_conn(db, tx, authorizer=None): + """Mimic utxo_endpoints: caller holds the write txn and commits.""" + conn = db._conn() + try: + if authorizer is not None: + conn.set_authorizer(authorizer) + conn.execute("BEGIN IMMEDIATE") + ok = db.apply_transaction(tx, block_height=10, conn=conn) + if ok and conn.in_transaction: + conn.commit() + return ok + finally: + conn.close() + + +# -- normal cleanup ---------------------------------------------------------- + +@pytest.mark.parametrize("caller_conn", [False, True]) +def test_cleanup_removes_every_dependent_and_keeps_unrelated(db, caller_conn): + spend_box, other_box, tx = _setup(db) + before = utxo_mod.mempool_eviction_failure_count() + + ok = (_apply_on_caller_conn(db, tx) if caller_conn + else db.apply_transaction(tx, block_height=10)) + + assert ok is True + st = _state(db, spend_box, other_box) + assert st["spent_at"] is not None + assert st["mempool"] == {"unrelated"} + assert st["other_claim"] is None, "evicted tx's claim rows must go too" + assert utxo_mod.mempool_eviction_failure_count() == before + + +def test_cleanup_evicts_row_whose_claim_rows_are_missing(db): + """Defense in depth: a mempool row spending the box is evicted even if + its utxo_mempool_inputs claim is missing (found via tx_data_json).""" + spend_box, other_box, tx = _setup(db) + conn = db._conn() + try: + conn.execute( + "INSERT INTO utxo_mempool (tx_id, tx_data_json, fee_nrtc, expires_at, submitted_at) " + "VALUES ('orphan', ?, 1, 9999999999, 0)", + ('{"inputs": [{"box_id": "%s"}], "data_inputs": []}' % spend_box,), + ) + conn.commit() + finally: + conn.close() + + assert db.apply_transaction(tx, block_height=10) is True + assert _state(db, spend_box, other_box)["mempool"] == {"unrelated"} + + +# -- injected failures: spend stands, failure is surfaced -------------------- + +@pytest.mark.parametrize("caller_conn", [False, True]) +def test_helper_exception_is_logged_counted_and_spend_stands(db, caplog, monkeypatch, caller_conn): + spend_box, other_box, tx = _setup(db) + + def boom(*_a, **_k): + raise sqlite3.OperationalError("database is locked") + + monkeypatch.setattr(UtxoDB, "_evict_stale_data_input_txs", boom) + before = utxo_mod.mempool_eviction_failure_count() + + with caplog.at_level(logging.ERROR, logger="node.utxo_db"): + ok = (_apply_on_caller_conn(db, tx) if caller_conn + else db.apply_transaction(tx, block_height=10)) + + assert ok is True, "a durable spend must not be reported as failed" + st = _state(db, spend_box, other_box) + assert st["spent_at"] is not None, "spend must not be rolled back" + assert st["confirmed_txs"] == 1 + # Surfaced, not swallowed: + assert utxo_mod.mempool_eviction_failure_count() == before + 1 + errors = [r for r in caplog.records if r.levelno == logging.ERROR] + assert len(errors) == 1 + msg = errors[0].getMessage() + assert tx["tx_id"] in msg and spend_box in msg and "database is locked" in msg + # The stale dependent is (knowingly) still there -- that is what we log. + assert "dep_data" in st["mempool"] + + +@pytest.mark.parametrize("caller_conn", [False, True]) +def test_real_sqlite_failure_mid_eviction_is_atomic(db, caplog, caller_conn): + """Trigger aborts the 2nd DELETE after the claim-row DELETE succeeded. + The eviction must roll back as a unit (no orphaned mempool row without + its claims) while the spend itself commits.""" + spend_box, other_box, tx = _setup(db) + _add_trigger(db, "ABORT") + before = utxo_mod.mempool_eviction_failure_count() + + with caplog.at_level(logging.ERROR, logger="node.utxo_db"): + ok = (_apply_on_caller_conn(db, tx) if caller_conn + else db.apply_transaction(tx, block_height=10)) + + assert ok is True + st = _state(db, spend_box, other_box) + assert st["spent_at"] is not None and st["confirmed_txs"] == 1 + assert st["mempool"] == {"dep_data", "unrelated"} + assert st["other_claim"] is not None and st["other_claim"]["tx_id"] == "dep_data", \ + "partial eviction leaked: claim rows deleted but mempool row kept" + assert utxo_mod.mempool_eviction_failure_count() == before + 1 + assert any("injected eviction failure" in r.getMessage() + for r in caplog.records if r.levelno == logging.ERROR) + + +def test_caller_txn_aborted_during_eviction_fails_closed(db): + """RAISE(ROLLBACK) kills the caller's whole transaction, spend included. + apply_transaction must raise, not return True for a spend that is gone.""" + spend_box, other_box, tx = _setup(db) + _add_trigger(db, "ROLLBACK") + before = utxo_mod.mempool_eviction_failure_count() + + with pytest.raises(sqlite3.Error): + _apply_on_caller_conn(db, tx) + + st = _state(db, spend_box, other_box) + assert st["spent_at"] is None, "nothing was committed" + assert st["confirmed_txs"] == 0 + assert st["mempool"] == {"dep_data", "unrelated"} + assert utxo_mod.mempool_eviction_failure_count() == before + + +def test_own_conn_rollback_trigger_does_not_touch_committed_spend(db, caplog): + """Own-connection path: eviction runs after COMMIT on a fresh connection, + so even a transaction-killing failure there cannot undo the spend.""" + spend_box, other_box, tx = _setup(db) + _add_trigger(db, "ROLLBACK") + before = utxo_mod.mempool_eviction_failure_count() + + with caplog.at_level(logging.ERROR, logger="node.utxo_db"): + assert db.apply_transaction(tx, block_height=10) is True + + st = _state(db, spend_box, other_box) + assert st["spent_at"] is not None and st["confirmed_txs"] == 1 + assert st["other_claim"] is not None + assert utxo_mod.mempool_eviction_failure_count() == before + 1 + + +def test_helper_raises_instead_of_returning_zero(db): + """The helper no longer masks errors as 'nothing evicted'.""" + _setup(db) + _add_trigger(db, "ABORT") + conn = db._conn() + try: + box = conn.execute( + "SELECT box_id FROM utxo_boxes WHERE owner_address='addr_spend'" + ).fetchone()["box_id"] + finally: + conn.close() + with pytest.raises(sqlite3.IntegrityError): + db._evict_stale_data_input_txs([box]) + + +# -- savepoint edge cases (review follow-up) ---------------------------------- + +def test_release_failure_after_successful_rollback_keeps_spend(db, caplog): + """Eviction fails, ROLLBACK TO succeeds, RELEASE is denied. The caller's + writes are intact, so the spend must be kept and the caller's COMMIT + must still succeed (COMMIT closes the leftover savepoint).""" + spend_box, other_box, tx = _setup(db) + _add_trigger(db, "ABORT") + before = utxo_mod.mempool_eviction_failure_count() + + with caplog.at_level(logging.ERROR, logger="node.utxo_db"): + ok = _apply_on_caller_conn(db, tx, authorizer=_deny_savepoint_op("RELEASE")) + + assert ok is True + st = _state(db, spend_box, other_box) # fresh connection: proves COMMIT landed + assert st["spent_at"] is not None and st["confirmed_txs"] == 1 + assert st["mempool"] == {"dep_data", "unrelated"} + assert st["other_claim"] is not None and st["other_claim"]["tx_id"] == "dep_data" + assert utxo_mod.mempool_eviction_failure_count() == before + 1 + msgs = [r.getMessage() for r in caplog.records if r.levelno == logging.ERROR] + assert any("RELEASE SAVEPOINT" in m for m in msgs) + assert any("injected eviction failure" in m for m in msgs) + + +def test_release_failure_after_successful_eviction_keeps_spend_and_eviction(db, caplog): + """No eviction error, only the final RELEASE is denied: the eviction is + complete and must commit with the spend; it is not counted as a failed + eviction, but the RELEASE problem is logged.""" + spend_box, other_box, tx = _setup(db) + before = utxo_mod.mempool_eviction_failure_count() + + with caplog.at_level(logging.ERROR, logger="node.utxo_db"): + ok = _apply_on_caller_conn(db, tx, authorizer=_deny_savepoint_op("RELEASE")) + + assert ok is True + st = _state(db, spend_box, other_box) + assert st["spent_at"] is not None and st["confirmed_txs"] == 1 + assert st["mempool"] == {"unrelated"} + assert st["other_claim"] is None + assert utxo_mod.mempool_eviction_failure_count() == before + assert any("RELEASE SAVEPOINT" in r.getMessage() + for r in caplog.records if r.levelno == logging.ERROR) + + +def test_failed_savepoint_rollback_fails_closed(db): + """Eviction fails and ROLLBACK TO is denied: the partial DELETE cannot + be undone, so apply_transaction must raise _EvictionRollbackFailed rather + than let the partial eviction ride along on the caller's COMMIT.""" + spend_box, other_box, tx = _setup(db) + _add_trigger(db, "ABORT") + before = utxo_mod.mempool_eviction_failure_count() + + with pytest.raises(utxo_mod._EvictionRollbackFailed): + _apply_on_caller_conn(db, tx, authorizer=_deny_savepoint_op("ROLLBACK")) + + st = _state(db, spend_box, other_box) + assert st["spent_at"] is None, "caller never committed" + assert st["confirmed_txs"] == 0 + assert st["mempool"] == {"dep_data", "unrelated"} + assert st["other_claim"] is not None + assert utxo_mod.mempool_eviction_failure_count() == before + + +# -- strategy coverage (review follow-up) -------------------------------------- + +def test_claim_row_strategy_evicts_even_without_inputs_in_json(db): + """Strategy 1 (utxo_mempool_inputs lookup) on its own: the row's + tx_data_json names no inputs, only its claim row ties it to the box.""" + spend_box, other_box, _tx = _setup(db) + conn = db._conn() + try: + conn.execute( + "INSERT INTO utxo_mempool (tx_id, tx_data_json, fee_nrtc, expires_at, submitted_at) " + "VALUES ('claim_only', '{\"tx_id\": \"claim_only\"}', 1, 9999999999, 0)" + ) + conn.execute( + "INSERT INTO utxo_mempool_inputs (box_id, tx_id) VALUES (?, 'claim_only')", + (spend_box,), + ) + conn.commit() + finally: + conn.close() + + # dep_data (data_input) + claim_only (claim row) are the two dependents. + assert db._evict_stale_data_input_txs([spend_box]) == 2 + st = _state(db, spend_box, other_box) + assert st["mempool"] == {"unrelated"} + conn = db._conn() + try: + assert conn.execute( + "SELECT 1 FROM utxo_mempool_inputs WHERE tx_id='claim_only'" + ).fetchone() is None + finally: + conn.close() + + +@pytest.mark.parametrize("caller_conn", [False, True]) +def test_apply_evicts_mempool_tx_spending_same_box_via_claim(db, caller_conn): + """End-to-end Strategy 1: the confirmed tx's own mempool entry holds a + claim on spend_box and must be evicted (with its claim rows).""" + spend_box, other_box, tx = _setup(db) + tx = dict(tx, tx_id="self_tx") + tx.pop("timestamp") + assert db.mempool_add(dict(tx)) + conn = db._conn() + try: + assert conn.execute( + "SELECT tx_id FROM utxo_mempool_inputs WHERE box_id=?", (spend_box,) + ).fetchone()["tx_id"] == "self_tx" + finally: + conn.close() + + ok = (_apply_on_caller_conn(db, tx) if caller_conn + else db.apply_transaction(tx, block_height=10)) + + assert ok is True + st = _state(db, spend_box, other_box) + assert st["mempool"] == {"unrelated"} + conn = db._conn() + try: + assert conn.execute( + "SELECT 1 FROM utxo_mempool_inputs WHERE box_id=?", (spend_box,) + ).fetchone() is None + finally: + conn.close() + + +def test_malformed_rows_do_not_abort_the_scan(db): + """Non-dict / non-JSON / odd-shaped rows are skipped, not fatal: real + dependents are still evicted and the malformed rows are left alone.""" + spend_box, other_box, tx = _setup(db) + garbage = { + "g_list": "[1, 2, 3]", + "g_str": '"just a string"', + "g_null": "null", + "g_badjson": "{not json", + "g_shapes": '{"data_inputs": [["x"], {"a": 1}], "inputs": ["str", [1]]}', + } + conn = db._conn() + try: + for tx_id, body in garbage.items(): + conn.execute( + "INSERT INTO utxo_mempool (tx_id, tx_data_json, fee_nrtc, expires_at, submitted_at) " + "VALUES (?, ?, 1, 9999999999, 0)", + (tx_id, body), + ) + conn.commit() + finally: + conn.close() + before = utxo_mod.mempool_eviction_failure_count() + + assert db.apply_transaction(tx, block_height=10) is True + + st = _state(db, spend_box, other_box) + assert st["mempool"] == {"unrelated"} | set(garbage) + assert st["other_claim"] is None + assert utxo_mod.mempool_eviction_failure_count() == before diff --git a/tests/test_utxo_security_audit.py b/tests/test_utxo_security_audit.py index 2c43d984d..8e0ce59aa 100644 --- a/tests/test_utxo_security_audit.py +++ b/tests/test_utxo_security_audit.py @@ -27,7 +27,12 @@ # rollback_genesis() is a destructive state mutation and now requires an # admin key (bounty #2819). Configure a test key for this suite. -os.environ["RC_ADMIN_KEY"] = "test-rollback-admin-key-2819" +# Use the suite-wide key from tests/conftest.py instead of overwriting it. +# Overwriting at import time (as #8393 did, with a 28-char value) leaked into +# every later module: the node sys.exit(1)s on a key < 32 chars, which killed +# collection of the whole CI "test" job, and tests sending conftest's key got +# 401s. setdefault only fills it in when this file is run on its own. +_ROLLBACK_ADMIN_KEY = os.environ.setdefault("RC_ADMIN_KEY", "0" * 32) from utxo_db import ( UtxoDB, coin_select, compute_box_id, address_to_proposition, @@ -604,7 +609,7 @@ def test_rollback_then_remigrate_idempotent(self): self.assertEqual(db.get_balance('bob'), 50 * UNIT) # Rollback - deleted = rollback_genesis(tmp.name, admin_key="test-rollback-admin-key-2819") + deleted = rollback_genesis(tmp.name, admin_key=_ROLLBACK_ADMIN_KEY) self.assertEqual(deleted, 2) self.assertEqual(db.get_balance('alice'), 0) self.assertEqual(db.get_balance('bob'), 0) @@ -721,7 +726,7 @@ def test_rollback_succeeds_with_correct_key(self): """The happy path still works once authorized.""" from utxo_genesis_migration import rollback_genesis deleted = rollback_genesis( - self.tmp.name, admin_key="test-rollback-admin-key-2819" + self.tmp.name, admin_key=_ROLLBACK_ADMIN_KEY ) self.assertEqual(deleted, 1) self.assertIsNone(self.db.get_box(self.box_id)) diff --git a/tests/test_utxo_transfer_spends_account_mirror.py b/tests/test_utxo_transfer_spends_account_mirror.py index 09c6f9a8f..790b31515 100644 --- a/tests/test_utxo_transfer_spends_account_mirror.py +++ b/tests/test_utxo_transfer_spends_account_mirror.py @@ -239,3 +239,15 @@ def test_non_mirror_box_spends_when_same_wallet_also_has_small_mirror(rig): assert data["to_address"] == "RTC" + "d" * 40 assert utxo_db.get_balance("RTC" + "d" * 40) == 10 * UNIT assert _unspent_mirror_value(db_path, ALICE) == 1 * UNIT + + +def test_request_beyond_whole_wallet_is_plain_insufficient_not_mirror_409(rig): + """The 409 is only for 'short because funds are mirror-locked'. Asking for + more than the whole wallet (mirror boxes included) is ordinary + insufficiency, and must not be mislabeled as a mirror block.""" + client, _, _ = rig + resp = _transfer(client, amount_rtc=MIRROR_NRTC / UNIT + 1000.0) + assert resp.status_code == 400, resp.get_json() + body = resp.get_json() + assert body["error"] == "Insufficient UTXO balance" + assert body["spendable_nrtc"] == 0 diff --git a/tests/test_welcome_bonus_schema.py b/tests/test_welcome_bonus_schema.py index 79ee083d2..f7c1eb953 100644 --- a/tests/test_welcome_bonus_schema.py +++ b/tests/test_welcome_bonus_schema.py @@ -5,6 +5,19 @@ import integrated_node +TRUSTED = {"state": "trusted"} + + +def _graduate(db_path, miner): + """sybil_guard: the bonus is paid at probation exit, authorised from the + persisted miner_probation row. Persist a graduated (trusted) row.""" + integrated_node.sybil_guard.init_schema(str(db_path)) + with sqlite3.connect(db_path) as conn: + conn.execute( + "INSERT INTO miner_probation (miner, state, first_seen, last_seen, updated_at) " + "VALUES (?, 'trusted', 1, 1, 1)", (miner,)) + + def _create_history(conn, miner="miner_welcome"): conn.execute("CREATE TABLE miner_attest_history (miner TEXT NOT NULL)") conn.execute("INSERT INTO miner_attest_history (miner) VALUES (?)", (miner,)) @@ -44,10 +57,11 @@ def test_welcome_bonus_credits_current_account_ledger_schema(tmp_path, monkeypat conn.commit() monkeypatch.setattr(integrated_node, "DB_PATH", str(db_path)) + _graduate(db_path, miner) monkeypatch.setattr(integrated_node, "current_slot", lambda: 144 * 7) monkeypatch.setattr(integrated_node, "slot_to_epoch", lambda slot: slot // 144) - integrated_node._check_welcome_bonus(miner) + integrated_node._check_welcome_bonus(miner, TRUSTED) with sqlite3.connect(db_path) as conn: balances = dict(conn.execute("SELECT miner_id, amount_i64 FROM balances").fetchall()) @@ -62,7 +76,7 @@ def test_welcome_bonus_credits_current_account_ledger_schema(tmp_path, monkeypat (7, miner, bonus_i64, f"welcome_bonus:{integrated_node.WELCOME_BONUS_RTC}_rtc"), ] - integrated_node._check_welcome_bonus(miner) + integrated_node._check_welcome_bonus(miner, TRUSTED) with sqlite3.connect(db_path) as conn: assert conn.execute("SELECT COUNT(*) FROM ledger").fetchone()[0] == 2 @@ -99,8 +113,9 @@ def test_welcome_bonus_keeps_legacy_transfer_ledger_schema(tmp_path, monkeypatch conn.commit() monkeypatch.setattr(integrated_node, "DB_PATH", str(db_path)) + _graduate(db_path, miner) - integrated_node._check_welcome_bonus(miner) + integrated_node._check_welcome_bonus(miner, TRUSTED) with sqlite3.connect(db_path) as conn: balances = dict(conn.execute("SELECT miner_id, amount_i64 FROM balances").fetchall()) diff --git a/tools/check_relative_links.py b/tools/check_relative_links.py new file mode 100755 index 000000000..27c9822a7 --- /dev/null +++ b/tools/check_relative_links.py @@ -0,0 +1,71 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +""" +check_relative_links.py — Verify relative markdown and HTML links across repository. +Fails with non-zero exit code if any internal file or relative link is missing. +""" + +import os +import re +import sys +import glob + +def check_file(file_path: str, repo_root: str) -> list: + broken = [] + with open(file_path, "r", encoding="utf-8", errors="ignore") as f: + content = f.read() + + # Skip inside code blocks (``` ... ```) + # Replace triple-backtick code blocks with empty strings to avoid false positives in templates/examples + clean_content = re.sub(r"```[\s\S]*?```", "", content) + + # Match standard markdown links: [text](link) + md_links = re.findall(r"\[([^\]]*)\]\(([^)]+)\)", clean_content) + file_dir = os.path.dirname(file_path) + + for text, link in md_links: + link = link.strip() + # Ignore external URLs, anchors, mailto, and placeholder variables + if link.startswith(("#", "http://", "https://", "mailto:", "{{")): + continue + # Strip anchor or query params + target = link.split("#")[0].split("?")[0].strip() + if not target: + continue + + # Check path relative to current markdown file + if target.startswith("/"): + target_path = os.path.normpath(os.path.join(repo_root, target.lstrip("/"))) + else: + target_path = os.path.normpath(os.path.join(file_dir, target)) + if not os.path.exists(target_path): + rel_file = os.path.relpath(file_path, repo_root) + broken.append((rel_file, text, link, target)) + + return broken + +def main(): + repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + print(f"Scanning markdown files in {repo_root} for broken relative links...") + + all_broken = [] + for root, dirs, files in os.walk(repo_root): + # Skip .git, venv, and node_modules directories + dirs[:] = [d for d in dirs if d not in (".git", "venv", ".venv", "node_modules", "__pycache__")] + for f in files: + if f.endswith(".md"): + p = os.path.join(root, f) + broken = check_file(p, repo_root) + all_broken.extend(broken) + + if all_broken: + print(f"\n❌ Found {len(all_broken)} broken relative link(s):") + for rel_file, text, link, target in all_broken: + print(f" • {rel_file}: [{text}]({link}) -> '{target}' not found") + sys.exit(1) + + print("\n✅ All relative links resolved successfully.") + sys.exit(0) + +if __name__ == "__main__": + main() diff --git a/tools/pending_ops.py b/tools/pending_ops.py index dd3840218..72384e4be 100644 --- a/tools/pending_ops.py +++ b/tools/pending_ops.py @@ -53,10 +53,38 @@ def cmd_list(args: argparse.Namespace) -> int: return 0 +def confirm_failure_reason(out: dict) -> str | None: + """Return why a /pending/confirm response is NOT a success, or None. + + The exit code is the only signal a cron/CI caller gets. This used to return + 0 for any JSON object, so a pass in which every transfer raised (left + pending, nothing delivered) exited green. Fail closed: + * ``ok`` must be exactly True (a missing ``ok`` is an unexpected shape); + * ``overdue_stats_measured`` must be exactly True. ``false`` means the + node could not measure the queue, and "could not measure" is not + "nothing to do". A missing or null field (a node older than #8233, or + a proxy/error body that dropped it) is equally unmeasured, so it fails + too rather than being read as healthy. + """ + if out.get("ok") is not True: + failed = out.get("failed_ids") + return f"node reported ok={out.get('ok')!r} (failed_ids={failed!r})" + measured = out.get("overdue_stats_measured") + if measured is not True: + if measured is False: + return f"pending queue could not be measured: {out.get('overdue_stats_error')!r}" + return f"pending queue measurement not reported (overdue_stats_measured={measured!r})" + return None + + def cmd_confirm(args: argparse.Namespace) -> int: url = f"{args.node.rstrip('/')}/pending/confirm" out = _req("POST", url, args.admin_key, payload={}, insecure=args.insecure) print(json.dumps(out, indent=2, sort_keys=True)) + reason = confirm_failure_reason(out) + if reason: + print(f"error: confirm pass not healthy: {reason}", file=sys.stderr) + return 1 return 0 diff --git a/tools/probation_admin.py b/tools/probation_admin.py new file mode 100644 index 000000000..86d283c4a --- /dev/null +++ b/tools/probation_admin.py @@ -0,0 +1,274 @@ +#!/usr/bin/env python3 +"""probation_admin.py -- operator tool for the SYBIL-GUARD probation tables. + +Run on the node, next to sybil_guard.py (operator only): + ssh 'cd && python3 - list' < tools/probation_admin.py + ssh 'cd && python3 - show RTCabc...' < tools/probation_admin.py + ssh 'cd && python3 - release RTCabc... --reason "verified G4 owner"' < tools/probation_admin.py + (prints the plan; add --apply to write) + python3 probation_admin.py allowlist + +SCOPE: reads anything it needs, but WRITES ONLY the guard's own tables: + miner_probation (the one row being released) and sybil_guard_admin_audit + (created on first --apply). It never writes balances, ledger, epoch_enroll, + sybil_review_escrow or the cohort table. + +WHAT RELEASE DOES (and does not do) + * clears needs_review / review_reason on the miner's miner_probation row; + * state: -> grandfathered if the miner attested before the cutoff; + -> trusted if --trust (skips the rest of probation; no exit caps); + -> otherwise unchanged (it keeps working through probation normally). + * writes one audit row: who (--operator, default $SUDO_USER/$USER), when, + why (--reason, required), and before/after JSON of the row. + * It does NOT pay anything. Escrow rows record WEIGHT, not funds; restoring + past epochs is a separate, manual operator payment. + * It does NOT make the release permanent against new evidence: a miner that + sends the incident profile again is re-flagged on that attestation. + * Cohort members (sybil_cohort_20260924) are refused unless --force-cohort. + Even then, settlement still holds any wallet listed in the cohort table. + Removing it from that table is a separate operator decision, so the tool + prints that SQL and does not run it. +""" +import argparse +import datetime as _dt +import json +import os +import sqlite3 +import sys + +DEFAULT_DB = "/root/rustchain/rustchain_v2.db" +AUDIT_TABLE = "sybil_guard_admin_audit" + + +def _import_guard(root): + for p in (root, os.path.join(root, "node")): + if p not in sys.path: + sys.path.insert(0, p) + import sybil_guard # noqa: E402 (the node's own module) + return sybil_guard + + +def _ts(v): + if v is None: + return None + try: + return _dt.datetime.fromtimestamp(int(v), _dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ") + except (TypeError, ValueError, OverflowError, OSError): + return str(v) + + +def _ro(db): + return sqlite3.connect(f"file:{db}?mode=ro", uri=True) + + +def _exists(c, name): + return c.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,)).fetchone() is not None + + +def _escrow_units(c): + if not _exists(c, "sybil_review_escrow"): + return {} + return {m: (int(u or 0), int(n)) for m, u, n in c.execute( + "SELECT miner, SUM(would_be_weight_units), COUNT(*) FROM sybil_review_escrow GROUP BY miner")} + + +def cmd_list(db, sg, states=None, limit=200, out=None): + out = out or sys.stdout + c = _ro(db) + try: + if not _exists(c, "miner_probation"): + print("miner_probation does not exist (guarded node not started yet)", file=out) + return [] + esc = _escrow_units(c) + cohort = set() + if _exists(c, sg.INCIDENT_COHORT_TABLE): + cohort = sg._cohort_members(c, [r[0] for r in c.execute("SELECT miner FROM miner_probation")]) + want = states or [sg.STATE_PROBATION, sg.STATE_QUEUED, sg.STATE_ADMISSION_QUEUED] + rows = c.execute( + "SELECT miner, state, reason, needs_review, review_reason, first_seen, last_seen, attest_count, " + "varied_count, anomaly_count FROM miner_probation " + f"WHERE needs_review = 1 OR state IN ({','.join('?' * len(want))}) " + "ORDER BY needs_review DESC, first_seen DESC LIMIT ?", [*want, int(limit)]).fetchall() + finally: + c.close() + out_rows = [] + print(f"{'miner':44} {'state':16} {'review':44} {'first_seen':20} {'att':>4} {'var':>4} {'anom':>4} " + f"{'escrow_units':>14} cohort", file=out) + for (m, st, why, nr, rr, fs, ls, ac, vc, an) in rows: + u, n = esc.get(m, (0, 0)) + rec = {"miner": m, "state": st, "reason": why, "needs_review": bool(nr), "review_reason": rr, + "first_seen": _ts(fs), "last_seen": _ts(ls), "attestations": ac, "varied": vc, + "anomalies": an, "escrow_units": u, "escrow_epochs": n, "cohort": m in cohort} + out_rows.append(rec) + print(f"{m[:44]:44} {st:16} {(rr or '-')[:44]:44} {rec['first_seen'] or '-':20} {ac or 0:>4} " + f"{vc or 0:>4} {an or 0:>4} {u:>14} {'YES' if m in cohort else ''}", file=out) + print(f"\n{len(out_rows)} row(s). Escrow units are WEIGHT (1e9 = 1.0x), not RTC.", file=out) + return out_rows + + +def cmd_show(db, sg, miner, out=None): + out = out or sys.stdout + c = _ro(db) + try: + row = sg._load(c, miner) if _exists(c, "miner_probation") else None + info = { + "miner": miner, + "probation_row": row, + "pre_cutoff_history": sg.has_pre_cutoff_history(c, miner), + "cohort_member": bool(sg._cohort_members(c, [miner])) if _exists(c, sg.INCIDENT_COHORT_TABLE) else False, + "stored_incident_matches": sum(1 for p in sg.fetch_profiles(c, miner) if sg.matches_incident_signature(p)), + "escrow": [dict(zip(("epoch", "units", "reason", "created_at"), r)) for r in c.execute( + "SELECT epoch, would_be_weight_units, reason, created_at FROM sybil_review_escrow " + "WHERE miner=? ORDER BY epoch", (miner,))] if _exists(c, "sybil_review_escrow") else [], + "audit": [dict(zip(("ts", "operator", "action", "reason"), r)) for r in c.execute( + f"SELECT ts, operator, action, reason FROM {AUDIT_TABLE} WHERE miner=? ORDER BY id", + (miner,))] if _exists(c, AUDIT_TABLE) else [], + "allowlisted_in_this_shell": miner in sg.probation_allowlist(), + } + finally: + c.close() + print(json.dumps(info, indent=2, default=str), file=out) + return info + + +def plan_release(c, sg, miner, trust=False, force_cohort=False): + """Pure: returns (plan_dict, error_or_None). Reads only.""" + if not _exists(c, "miner_probation"): + return None, "miner_probation does not exist" + row = sg._load(c, miner) + if row is None: + return None, f"{miner}: no miner_probation row (nothing to release; see `allowlist` for new machines)" + cohort = _exists(c, sg.INCIDENT_COHORT_TABLE) and bool(sg._cohort_members(c, [miner])) + if cohort and not force_cohort: + return None, (f"{miner} is in {sg.INCIDENT_COHORT_TABLE}; refusing without --force-cohort") + pre = sg.has_pre_cutoff_history(c, miner) + if pre: + new_state, new_reason = sg.STATE_GRANDFATHERED, "operator_release:attested_before_cutoff" + elif trust: + new_state, new_reason = sg.STATE_TRUSTED, "operator_release:trusted" + else: + new_state, new_reason = row["state"], row.get("reason") + after = dict(row, needs_review=0, review_reason=None, state=new_state, reason=new_reason) + warnings = [] + if cohort: + warnings.append( + f"still listed in {sg.INCIDENT_COHORT_TABLE}: settlement will KEEP holding it until an operator runs: " + f"DELETE FROM {sg.INCIDENT_COHORT_TABLE} WHERE miner = '{miner}'; (not run by this tool)") + if new_state == sg.STATE_TRUSTED and not pre: + warnings.append("--trust skips the remaining probation checks and exit caps for this miner") + if row["state"] == sg.STATE_ADMISSION_QUEUED and new_state == row["state"]: + warnings.append("still admission_queued: weight stays 0 until admitted; use --trust to lift it") + warnings.append("the miner is re-flagged if it sends the incident profile again") + warnings.append("no funds move: escrow rows record weight only; past epochs need a manual payment") + return {"miner": miner, "before": row, "after": after, "cohort_member": cohort, + "pre_cutoff_history": pre, "warnings": warnings}, None + + +def cmd_release(db, sg, miner, reason, operator, apply=False, trust=False, force_cohort=False, out=None): + out = out or sys.stdout + if not reason or not reason.strip(): + print("REFUSED: --reason is required", file=out) + return 2 + if not apply: + c = _ro(db) + try: + plan, err = plan_release(c, sg, miner, trust, force_cohort) + finally: + c.close() + if err: + print(f"REFUSED: {err}", file=out) + return 2 + print(json.dumps({"DRY_RUN": True, **plan}, indent=2, default=str), file=out) + print("\nDry run: nothing written. Re-run with --apply to release.", file=out) + return 0 + c = sqlite3.connect(db, timeout=30, isolation_level=None) + try: + c.execute(f"""CREATE TABLE IF NOT EXISTS {AUDIT_TABLE} ( + id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, operator TEXT NOT NULL, + action TEXT NOT NULL, miner TEXT NOT NULL, reason TEXT NOT NULL, + before_json TEXT, after_json TEXT)""") + c.execute("BEGIN IMMEDIATE") + try: + plan, err = plan_release(c, sg, miner, trust, force_cohort) + if err: + c.execute("ROLLBACK") + print(f"REFUSED: {err}", file=out) + return 2 + a = plan["after"] + cur = c.execute( + "UPDATE miner_probation SET needs_review = 0, review_reason = NULL, state = ?, reason = ?, " + "updated_at = ? WHERE miner = ?", + (a["state"], a["reason"], int(_dt.datetime.now(_dt.timezone.utc).timestamp()), miner)) + if cur.rowcount != 1: + raise RuntimeError(f"expected 1 row updated, got {cur.rowcount}") + c.execute(f"INSERT INTO {AUDIT_TABLE} (ts, operator, action, miner, reason, before_json, after_json) " + "VALUES (?, ?, ?, ?, ?, ?, ?)", + (int(_dt.datetime.now(_dt.timezone.utc).timestamp()), operator, + "release" + ("+force_cohort" if plan["cohort_member"] else ""), miner, reason.strip(), + json.dumps(plan["before"], default=str), json.dumps(a, default=str))) + c.execute("COMMIT") + except BaseException: + c.execute("ROLLBACK") + raise + finally: + c.close() + print(json.dumps({"RELEASED": True, "miner": miner, "state": a["state"], + "warnings": plan["warnings"]}, indent=2), file=out) + return 0 + + +ALLOWLIST_GUIDE = """\ +RC_PROBATION_ALLOWLIST: for a NEW lab machine (first seen after 2026-09-24 00:00Z) that you +know is real but whose client sends a static profile (e.g. the Python 2.x G4 client), so it +could never graduate by itself. + + * Comma-separated miner ids, read from the node process environment at each attestation: + Environment="RC_PROBATION_ALLOWLIST=dual-g4-new,g5-lab-2" + in /etc/systemd/system/rustchain.service (next to RC_ADMIN_KEY), then: + systemctl daemon-reload && systemctl restart rustchain + * It applies when the miner's miner_probation row is first created (state trusted, + reason operator_allowlist). A miner that ALREADY has a row is not changed by the + env var: use `release --trust --reason ...` instead (audited). + * Allowlisted miners get their full hardware weight, and the welcome bonus once, on the next + attestation. The incident detector still applies (needs_review overrides everything). + * Miners that attested before the cutoff never need this: they are grandfathered. + * Keep the list short and write down why each entry is there. Anyone on it skips probation. +""" + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--db", default=DEFAULT_DB) + ap.add_argument("--root", default=os.environ.get("RUSTCHAIN_ROOT", "/root/rustchain"), + help="directory holding sybil_guard.py") + sub = ap.add_subparsers(dest="cmd", required=True) + p_list = sub.add_parser("list") + p_list.add_argument("--state", action="append") + p_list.add_argument("--limit", type=int, default=200) + p_show = sub.add_parser("show") + p_show.add_argument("miner") + p_rel = sub.add_parser("release") + p_rel.add_argument("miner") + p_rel.add_argument("--reason", required=True) + p_rel.add_argument("--operator", default=os.environ.get("SUDO_USER") or os.environ.get("USER") or "unknown") + p_rel.add_argument("--trust", action="store_true", help="mark trusted (new miners only)") + p_rel.add_argument("--force-cohort", action="store_true") + p_rel.add_argument("--apply", action="store_true", help="write (default is a dry run)") + sub.add_parser("allowlist") + args = ap.parse_args(argv) + if args.cmd == "allowlist": + print(ALLOWLIST_GUIDE) + return 0 + sg = _import_guard(args.root) + if args.cmd == "list": + cmd_list(args.db, sg, args.state, args.limit) + return 0 + if args.cmd == "show": + cmd_show(args.db, sg, args.miner) + return 0 + return cmd_release(args.db, sg, args.miner, args.reason, args.operator, + apply=args.apply, trust=args.trust, force_cohort=args.force_cohort) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/website/package-lock.json b/website/package-lock.json index 98711d5b5..ce35d3860 100644 --- a/website/package-lock.json +++ b/website/package-lock.json @@ -10539,15 +10539,15 @@ } }, "node_modules/image-size": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/image-size/-/image-size-2.0.2.tgz", - "integrity": "sha512-IRqXKlaXwgSMAMtpNzZa1ZAe8m+Sa1770Dhk8VkSsP9LS+iHD62Zd8FQKs8fbPiagBE7BzoFX23cxFnwshpV6w==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/image-size/-/image-size-2.0.4.tgz", + "integrity": "sha512-QRUkFFsRV/6fuESxb9Vkq+a0LkSrgKXuc2NEqfikiXxxN/G3tjWt5EVUlMaImRBZRZK/jRBEbYvpPYZL8t08Zw==", "license": "MIT", "bin": { "image-size": "bin/image-size.js" }, "engines": { - "node": ">=16.x" + "node": ">=18" } }, "node_modules/import-fresh": {