#!/usr/bin/env python3
"""ScannerSend Network Plugin v1.0

Optional plugin for CryptoAnnihilator that reports detected miner wallet
addresses to the ScannerSend Network (net.scannersend.org).

Install: Place this file next to crypto_annihilator.py
  /usr/local/bin/scannersend_network.py

What gets reported:
  - Wallet address and coin type
  - Pool host and port
  - Process name
  - Detection layer number
  - Timestamp

What is NEVER reported:
  - Your IP (we discard reporter IPs server-side)
  - Your hostname, system info, kernel, RAM
  - Usernames, file paths, cmdlines

Disable: Remove this file, or run crypto_annihilator with --no-network
License: MIT
By: Rav-n-Vic
"""

__version__ = "1.0.0"
__author__ = "Rav-n-Vic"
__license__ = "MIT"

import json
import hashlib
import hmac
import re
import urllib.request
import urllib.error
from datetime import datetime, timezone

NETWORK_API = "https://net.scannersend.org"
REPORT_SALT = "scannersend_v1_2026"
TIMEOUT = 10
VERSION = 1


def _get_nonce():
    """Request a single-use nonce from the server."""
    try:
        url = NETWORK_API + "/nonce"
        req = urllib.request.Request(url, method="GET")
        req.add_header("User-Agent", "ScannerSend-Network/" + __version__)
        with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            return data.get("nonce")
    except Exception:
        return None


def _sign_payload(payload_dict, nonce):
    """Create HMAC-SHA256 signature for the payload."""
    canonical = json.dumps(payload_dict, sort_keys=True, separators=(",", ":"))
    sign_data = canonical + nonce + REPORT_SALT
    return hmac.new(
        REPORT_SALT.encode("utf-8"),
        sign_data.encode("utf-8"),
        hashlib.sha256
    ).hexdigest()


def _submit_report(payload):
    """Submit the signed forensic packet to the server."""
    try:
        url = NETWORK_API + "/report"
        body = json.dumps(payload).encode("utf-8")
        req = urllib.request.Request(url, data=body, method="POST")
        req.add_header("Content-Type", "application/json")
        req.add_header("User-Agent", "ScannerSend-Network/" + __version__)
        with urllib.request.urlopen(req, timeout=TIMEOUT) as resp:
            result = json.loads(resp.read().decode("utf-8"))
            return result.get("status") == "accepted"
    except Exception:
        return False


def report(wallet, wallet_type, pool_host="", pool_port=0, process_name="",
           detection_layer=0):
    """Report a detected miner wallet to the ScannerSend Network.

    Returns True if accepted, False otherwise."""
    wallet = str(wallet)[:200]
    wallet_type = str(wallet_type)[:10]
    pool_host = str(pool_host)[:128]
    pool_port = max(0, min(65535, int(pool_port) if isinstance(pool_port, (int, float)) else 0))
    process_name = re.sub(r"[^a-zA-Z0-9_.\-]", "", str(process_name)[:64])
    detection_layer = max(1, min(4, int(detection_layer) if isinstance(detection_layer, (int, float)) else 1))

    nonce = _get_nonce()
    if not nonce:
        return False

    payload = {
        "version": VERSION,
        "nonce": nonce,
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "wallet": wallet,
        "wallet_type": wallet_type,
        "pool_host": pool_host,
        "pool_port": pool_port,
        "process_name": process_name,
        "detection_layer": detection_layer,
    }

    signature = _sign_payload(payload, nonce)
    payload["hmac"] = signature

    return _submit_report(payload)


if __name__ == "__main__":
    print("ScannerSend Network Plugin v" + __version__)
    print("API: " + NETWORK_API)
    print("")
    print("Testing connection...")
    nonce = _get_nonce()
    if nonce:
        print("  Server reachable (nonce: " + nonce[:8] + "...)")
    else:
        print("  Server unreachable (net.scannersend.org not responding)")
    print("")
    print("This plugin is loaded automatically by crypto_annihilator.py")
    print("when placed in the same directory (/usr/local/bin/).")
