#!/usr/bin/env python3
"""Check a zcrawl publication and independently repeat sampled mainnet handshakes."""
import argparse
import csv
import gzip
import hashlib
import ipaddress
import json
import re
import secrets
import socket
import sqlite3
import struct
import sys
import time
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
from pathlib import Path

MAGIC = bytes.fromhex("24e92764")
PROTOCOL = 170190
NU7_PREVIOUS = 3543404
DEFAULT_PORT = 8233
TIMEOUT = 3
CLIENTS = ("zebra", "zakura", "zcashd", "other", "unknown")
FAILURES = (
    "connect_timeout", "connect_refused", "connect_unreachable", "connect_error",
    "handshake_timeout", "connection_closed", "connection_reset", "io_error",
    "bad_magic", "bad_command", "bad_checksum", "oversized_message",
    "malformed_message", "too_many_messages", "self_connection",
)


class VerificationError(Exception):
    pass


def endpoint(address, column_port=None, default_port=DEFAULT_PORT):
    if address.startswith("["):
        host, close, suffix = address[1:].partition("]")
        if not close or (suffix and not suffix.startswith(":")):
            raise ValueError("invalid bracketed endpoint")
        embedded_port = int(suffix.removeprefix(":")) if suffix else None
    elif address.count(":") == 1:
        host, port = address.split(":")
        embedded_port = int(port)
    else:
        host, embedded_port = address, None
    ip = ipaddress.ip_address(host)
    port = embedded_port if embedded_port is not None else column_port
    port = default_port if port is None else int(port)
    if not 0 < port <= 65535:
        raise ValueError("invalid port")
    return ip, port


def checksum(payload):
    return hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]


def message(command, payload=b""):
    return MAGIC + struct.pack("<12sI4s", command, len(payload), checksum(payload)) + payload


def net_address(ip, port):
    packed = ip.packed
    if ip.version == 4:
        packed = bytes(10) + b"\xff\xff" + packed
    return bytes(8) + packed + struct.pack(">H", port)


def remaining(deadline):
    seconds = deadline - time.monotonic()
    if seconds <= 0:
        raise TimeoutError
    return seconds


def read_exact(connection, length, deadline):
    chunks = bytearray()
    while len(chunks) < length:
        connection.settimeout(remaining(deadline))
        block = connection.recv(length - len(chunks))
        if not block:
            raise VerificationError("peer closed the handshake")
        chunks.extend(block)
    return bytes(chunks)


def read_message(connection, deadline):
    header = read_exact(connection, 24, deadline)
    magic, field, length, digest = struct.unpack("<4s12sI4s", header)
    command = field.rstrip(b"\0")
    if magic != MAGIC or not re.fullmatch(rb"[a-z0-9]{1,12}", command) or length > 65536:
        raise VerificationError("invalid mainnet message header")
    payload = read_exact(connection, length, deadline)
    if checksum(payload) != digest:
        raise VerificationError("invalid message checksum")
    return command, payload


def read_version(payload, nonce):
    # Fixed fields end at byte 80, followed by a CompactSize-prefixed user agent.
    if len(payload) < 85:
        raise VerificationError("truncated version")
    protocol = struct.unpack_from("<i", payload)[0]
    remote_nonce = struct.unpack_from("<Q", payload, 72)[0]
    if protocol <= 0 or remote_nonce == nonce:
        raise VerificationError("invalid peer version or nonce")
    size = payload[80]
    offset = 81
    if size >= 253:
        width = {253: 2, 254: 4, 255: 8}[size]
        size = int.from_bytes(payload[offset:offset + width], "little")
        offset += width
        if size < {2: 253, 4: 65536, 8: 2**32}[width]:
            raise VerificationError("noncanonical user agent length")
    end = offset + size
    if size > 256 or len(payload) not in (end + 4, end + 5):
        raise VerificationError("invalid version length")
    return protocol, payload[offset:end]


def exchange(connection, ip, port, deadline):
    nonce = secrets.randbits(64)
    agent = b"/zcrawl-verify:1.0/"
    payload = (
        struct.pack("<iQq", PROTOCOL, 0, int(time.time()))
        + net_address(ip, port) + bytes(26) + struct.pack("<Q", nonce)
        + bytes([len(agent)]) + agent + bytes(5)
    )
    connection.settimeout(remaining(deadline))
    connection.sendall(message(b"version", payload))
    version = None
    acknowledged = False
    for _ in range(16):
        command, payload = read_message(connection, deadline)
        if command == b"version" and version is None:
            version = read_version(payload, nonce)
            connection.settimeout(remaining(deadline))
            connection.sendall(message(b"verack"))
        elif command == b"verack" and not payload and not acknowledged:
            acknowledged = True
        elif command in (b"version", b"verack"):
            raise VerificationError("invalid handshake sequence")
        if version is not None and acknowledged:
            return version
    raise VerificationError("handshake incomplete")


def probe(row, dial=socket.create_connection):
    address, stored_port, stored_agent, stored_protocol = row
    try:
        ip, port = endpoint(address, stored_port)
        deadline = time.monotonic() + TIMEOUT
        with dial((str(ip), port), timeout=remaining(deadline)) as connection:
            protocol, agent = exchange(connection, ip, port, deadline)
    except (TimeoutError, socket.timeout):
        return "timeout"
    except (OSError, TypeError, ValueError, AttributeError, VerificationError):
        return "failed"
    if isinstance(stored_agent, str):
        agent = agent.decode("utf-8", errors="replace")
    agent_changed = stored_agent is not None and agent != stored_agent
    protocol_changed = stored_protocol is not None and protocol != stored_protocol
    if agent_changed or protocol_changed:
        return {(True, False): "agent", (False, True): "protocol", (True, True): "both"}[
            agent_changed, protocol_changed]
    return "missing" if stored_agent is None or stored_protocol is None else "match"


def version_label(client, raw):
    if not raw:
        return client
    match = re.fullmatch(r"([0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4})(-.*)?", raw) if isinstance(raw, str) else None
    if not match:
        return client + " *"
    core, qualifier = match.groups()
    if qualifier and not re.fullmatch(r"-(?:modified|(?:rc|alpha|beta)(?:\.?[0-9]{1,3})?)", qualifier):
        qualifier = "-*"
    return client + " " + core + (qualifier or "")


def format_mask(value):
    if isinstance(value, str):
        if re.fullmatch(r"0[xX][0-9a-fA-F]{1,16}", value):
            value = int(value, 16)
        elif re.fullmatch(r"-?[0-9]{1,20}", value):
            value = int(value)
    if type(value) is int and -2**63 <= value < 2**64:
        return hex(value % 2**64)
    return None


def ip_family(value):
    try:
        return "IPv" + str(endpoint(value)[0].version)
    except (ValueError, TypeError, AttributeError):
        return None


def range_matches(con, path, columns):
    def packed(address):
        try:
            return endpoint(address)[0].packed
        except (ValueError, TypeError, AttributeError):
            return None

    con.create_function("packed", 1, packed, deterministic=True)
    peers = {size: iter(con.execute("""
        SELECT * FROM (
            SELECT packed(address) AS ip, client, version_label(client, version), wire_height
            FROM peers
        ) WHERE length(ip)=? ORDER BY ip
    """, (size,))) for size in (4, 16)}
    current = {size: next(cursor, None) for size, cursor in peers.items()}
    previous = {}
    opener = gzip.open if path.suffix == ".gz" else open
    with opener(path, "rt", encoding="utf-8", newline="") as source:
        for row in csv.reader(source, strict=True):
            if not row:
                continue
            if len(row) != columns:
                raise VerificationError("cantidad de columnas inválida en el CSV")
            first, last = (ipaddress.ip_address(value).packed for value in row[:2])
            size = len(first)
            if len(last) != size or first > last or (size in previous and first <= previous[size]):
                raise VerificationError("rangos del CSV inválidos")
            previous[size] = last
            record = current[size]
            while record is not None and record[0] <= last:
                if record[0] >= first:
                    yield row, record[1:]
                record = next(peers[size], None)
            current[size] = record


def geo_summary(con, city_csv, sync, legacy):
    if city_csv is None:
        return [], []
    counts, points = Counter(), []
    for row, (client, label, height) in range_matches(con, city_csv, 8):
        code = row[3]
        if not re.fullmatch(r"[A-Z]{2}", code) or code == "ZZ":
            continue
        counts[code] += 1
        try:
            lat, lon = (float(value) for value in row[6:])
        except ValueError:
            continue
        if not (abs(lat) <= 90 and abs(lon) <= 180):
            continue
        point = [round(lat, 1), round(lon, 1)]
        if not legacy:
            status = "unknown"
            if height is not None:
                offset = height - sync["reference"]
                tolerance = sync["tolerance"]
                status = "near" if abs(offset) <= tolerance else "behind" if offset < 0 else "ahead"
            point.extend([client, label.partition(" ")[2], status, code])
        points.append(point)
    countries = [{"code": code, "count": n} for code, n in sorted(counts.items(), key=lambda item: (-item[1], item[0]))]
    return countries, sorted(points)


def hosting_summary(con, path):
    by_name = Counter()
    for row, _ in range_matches(con, path, 4):
        asn, organization = row[2:]
        if re.fullmatch(r"[0-9]{1,10}", asn) and int(asn) in range(1, 2**32):
            label = re.sub(r"\s+", " ", organization).strip()[:160].rstrip()
            if label:
                by_name[label] += 1
    ranking = sorted(by_name, key=lambda name: (-by_name[name], name))
    total = sum(by_name.values())
    top = [{"name": name, "count": by_name[name]} for name in ranking[:10]]
    if len(ranking) > 10:
        top.append({"name": None, "count": sum(by_name[name] for name in ranking[10:])})
    return {"hosting": top, "hosting_covered": total,
            "hosting_top3": sum(by_name[name] for name in ranking[:3])}


def snapshot(con, publication, limit, legacy):
    if con.execute("PRAGMA user_version").fetchone()[0] != 2:
        raise VerificationError("esquema SQLite incompatible")
    network = con.execute("SELECT value FROM meta WHERE key = 'network'").fetchone()
    if not network or network[0] not in ("mainnet", "testnet") or (limit and network[0] != "mainnet"):
        raise VerificationError("red inválida o distinta de mainnet para un saludo activo")
    rounds = con.execute("""
        WITH recent AS (
            SELECT id, started_at, finished_at, nodes_reached, addresses_tried, hit_time_limit
            FROM rounds WHERE status = 'complete'
            ORDER BY started_at DESC, id DESC LIMIT 168
        )
        SELECT * FROM recent ORDER BY started_at DESC, id DESC
    """).fetchall()
    if not rounds:
        raise VerificationError("no hay rondas completas")
    round_id, started, finished, reached, tried, hit_limit = rounds[0]
    generated = publication.get("generated_at")
    if type(generated) is not int or generated < finished or generated >= 10**11:
        raise VerificationError("fecha de publicación inválida para la última ronda completa")

    fields = {row[1] for row in con.execute("PRAGMA table_info(observations)")}
    agent = next((key for key in ("user_agent", "raw_user_agent", "user_agent_raw") if key in fields), "NULL")
    con.execute("""
        CREATE TEMP TABLE hits AS
        SELECT address, reachable, failure_reason, implementation, version,
            %s AS protocol, %s AS height, %s AS services, %s AS agent, %s AS port
        FROM observations WHERE round_id = ?
    """ % (
        "protocol_version" if "protocol_version" in fields else "NULL",
        "start_height" if "start_height" in fields else "NULL",
        "services" if "services" in fields else "NULL",
        agent, "port" if "port" in fields else "NULL",
    ), (round_id,))
    con.create_function("version_label", 2, version_label, deterministic=True)
    con.create_function("format_mask", 1, format_mask, deterministic=True)
    con.create_function("ip_family", 1, ip_family, deterministic=True)
    con.execute("""
        CREATE TEMP VIEW peers AS SELECT *,
            CASE WHEN implementation IN ('zebra','zakura','zcashd','other','unknown')
                 THEN implementation ELSE 'unknown' END AS client,
            CASE WHEN typeof(protocol)='integer' AND protocol BETWEEN 1 AND 2147483647
                 THEN CAST(protocol AS TEXT) END AS wire_protocol,
            CASE WHEN typeof(height)='integer' AND height BETWEEN 0 AND 2147483647
                 THEN height END AS wire_height,
            format_mask(services) AS service_mask, ip_family(address) AS family
        FROM hits WHERE reachable
    """)

    def counts(query, parameters=()):
        return [{"name": name, "count": n} for name, n in con.execute(query, parameters)]

    def groups(field, maximum, source="peers"):
        return counts(f"""
            SELECT {field} AS name, count(*) AS n FROM {source} WHERE {field} IS NOT NULL
            GROUP BY 1 ORDER BY n DESC, name LIMIT ?
        """, (maximum,))

    def reported(field, maximum):
        count = con.execute(f"SELECT count({field}) FROM peers").fetchone()[0]
        return {"reported": count, "values": groups(field, maximum)}

    failures = counts("""
        SELECT CASE WHEN failure_reason IN (%s) THEN failure_reason ELSE 'other_error' END AS name,
               count(*) AS n
        FROM hits WHERE NOT coalesce(reachable, 0) GROUP BY 1 ORDER BY n DESC, name LIMIT 5
    """ % ",".join("?" for _ in FAILURES), FAILURES)
    height_count, low, high = con.execute("SELECT count(wire_height), min(wire_height), max(wire_height) FROM peers").fetchone()
    height = None
    sync = None
    if height_count:
        median = con.execute("""
            SELECT avg(wire_height) FROM (
                SELECT wire_height FROM peers WHERE wire_height IS NOT NULL ORDER BY wire_height LIMIT ? OFFSET ?
            )
        """, (2 - height_count % 2, (height_count - 1) // 2)).fetchone()[0]
        height = {"reported": height_count, "min": low, "max": high, "median": median}
        low_bound, high_bound = median - 100, median + 100
        near, behind, ahead = con.execute("""
            SELECT sum(wire_height BETWEEN ? AND ?), sum(wire_height < ?), sum(wire_height > ?)
            FROM peers WHERE wire_height IS NOT NULL
        """, (low_bound, high_bound, low_bound, high_bound)).fetchone()
        cluster = con.execute("""
            SELECT wire_height, count(*) AS n FROM peers WHERE wire_height < ?
            GROUP BY wire_height HAVING n >= 3 ORDER BY n DESC, wire_height LIMIT 1
        """, (low_bound,)).fetchone()
        sync = {"reference": median, "tolerance": 100, "near": near, "behind": behind, "ahead": ahead,
                "largest_stall": {"height": cluster[0], "count": cluster[1]} if cluster else None}

    def endpoint_label(address, port):
        ip, port = endpoint(address, port, 8233 if network[0] == "mainnet" else 18233)
        return f"[{ip}]:{port}"

    con.create_function("endpoint_label", 2, endpoint_label, deterministic=True)
    first_completed = con.execute("SELECT min(finished_at) FROM rounds WHERE status='complete'").fetchone()[0]
    port_column = "o.port" if "port" in fields else "NULL"
    distinct_reached = con.execute(f"""
        SELECT count(DISTINCT endpoint_label(o.address, {port_column}))
        FROM observations AS o
        WHERE o.reachable AND o.round_id IN (
            SELECT id FROM rounds WHERE status = 'complete' AND finished_at BETWEEN ? AND ?
        )
    """, (generated - 86400, generated)).fetchone()[0]
    inbound = con.execute("""
        SELECT CASE WHEN EXISTS (SELECT 1 FROM inbound) THEN count(DISTINCT address) END
        FROM inbound WHERE handshake_complete=1 AND observed_at BETWEEN ? AND ?
    """, (generated - 86400, generated)).fetchone()[0]
    expected = {
        "network": network[0],
        "latest": {"started_at": started, "finished_at": finished, "nodes_reached": reached,
                   "addresses_tried": tried, "hit_time_limit": bool(hit_limit)},
        "first_completed_at": first_completed,
        "reached_24h": distinct_reached,
        "inbound_24h": inbound,
        "history": [{"t": entry[2], "reached": entry[3]} for entry in sorted(rounds, key=lambda row: (row[2], row[0]))],
        "implementations": groups("client", len(CLIENTS)),
        "versions": groups("label", 8, "(SELECT version_label(client, version) AS label FROM peers)"),
        "protocols": reported("wire_protocol", 8),
        "height": height,
        "sync": sync,
        "services": reported("service_mask", 5),
        "families": groups("family", 2),
        "failures": failures,
    }
    if not legacy:
        expected["release_versions"] = {
            client: counts("""
                SELECT substr(version_label(client, version), length(client) + 2) AS label, count(*) AS n
                FROM peers WHERE client = ? AND label <> '' GROUP BY label ORDER BY n DESC, label
            """, (client,)) for client in ("zebra", "zakura")
        }
    if network[0] == "mainnet" and not legacy:
        high, low, previous = con.execute("""
            SELECT count(CASE WHEN cast(wire_protocol AS integer) >= ? THEN 1 END),
                   count(CASE WHEN cast(wire_protocol AS integer) < ? THEN 1 END),
                   count(CASE WHEN wire_height = ? THEN 1 END)
            FROM peers
        """, (PROTOCOL, PROTOCOL, NU7_PREVIOUS)).fetchone()
        nu7 = {}
        if high + low:
            nu7.update(at_least=high, below=low)
        if height_count:
            nu7["previous_block"] = previous
        if nu7:
            expected["nu7"] = nu7
    rows = con.execute("SELECT address, port, agent, protocol FROM peers ORDER BY random() LIMIT ?", (limit,)).fetchall()
    return expected, rows


def same_value(actual, expected):
    if isinstance(expected, dict):
        return isinstance(actual, dict) and actual.keys() == expected.keys() and all(
            same_value(actual[key], value) for key, value in expected.items()
        )
    if isinstance(expected, list):
        return isinstance(actual, list) and len(actual) == len(expected) and all(
            same_value(a, b) for a, b in zip(actual, expected)
        )
    if type(expected) in (int, float):
        return type(actual) in (int, float) and actual == expected
    return type(actual) is type(expected) and actual == expected


def same_points(actual, expected):
    if not isinstance(actual, list):
        return False
    try:
        return same_value(sorted(actual), expected)
    except TypeError:
        return False


def main(argv=None, probe_endpoint=probe):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("db", type=Path)
    parser.add_argument("data", type=Path, help="exported data.json")
    parser.add_argument("city_csv", type=Path, nargs="?", help="same DB-IP City Lite CSV used by export.py")
    parser.add_argument("--asn-csv", type=Path, help="same DB-IP ASN Lite CSV used by export.py")
    parser.add_argument("--sample", type=int, choices=range(1, 41), default=20, metavar="1–40")
    parser.add_argument("--interval-minutes", type=int, help="expected configured crawl interval")
    parser.add_argument("--offline", action="store_true", help="recalculate the publication without probing peers")
    args = parser.parse_intermixed_args(argv)
    try:
        with args.data.open(encoding="utf-8") as source:
            publication = json.load(source)
        if not isinstance(publication, dict):
            raise VerificationError("JSON inválido")
        if publication.get("geolocation_enabled") is True and args.city_csv is None:
            raise VerificationError("indica el mismo CSV de ciudades que usó el exportador")
        if "hosting" in publication and args.asn_csv is None:
            raise VerificationError("indica el mismo CSV ASN que usó el exportador")
        modern_fields = {"nu7", "release_versions", "hosting", "hosting_covered", "hosting_top3"}
        legacy = not bool(modern_fields & publication.keys())
        with closing(sqlite3.connect(args.db.resolve().as_uri() + "?mode=ro", uri=True, timeout=5)) as con:
            con.execute("BEGIN")
            expected, rows = snapshot(con, publication, 0 if args.offline else args.sample, legacy)
            expected["geolocation_enabled"] = args.city_csv is not None
            expected["countries"], expected["points"] = geo_summary(con, args.city_csv, expected["sync"], legacy)
            if args.asn_csv is not None:
                expected.update(hosting_summary(con, args.asn_csv))
            con.commit()
    except VerificationError as error:
        print(f"verify.py: {error}", file=sys.stderr)
        return 1
    except (OSError, ValueError, sqlite3.Error, csv.Error):
        print("verify.py: no se pudo leer SQLite, JSON o el CSV", file=sys.stderr)
        return 1

    different = []
    for key, value in expected.items():
        matches = same_points if key == "points" else same_value
        if key not in publication or not matches(publication[key], value):
            different.append(key)
    interval = publication.get("interval_minutes")
    if type(interval) is not int or not 0 < interval < 2**53 or (
            args.interval_minutes is not None and interval != args.interval_minutes):
        different.append("interval_minutes")
    extras = set(publication) - (expected.keys() | {"generated_at", "interval_minutes"})
    if extras:
        different.append("campos inesperados")
    print("Publicación: " + ("diferencias en " + ", ".join(different) if different else "cifras coincidentes"))
    if args.offline:
        print("Modo local: sin saludos de red.")
        return int(bool(different))

    with ThreadPoolExecutor(max_workers=5) as workers:
        results = Counter(workers.map(probe_endpoint, rows))
    incomplete = results["timeout"] + results["failed"]
    print(
        f"Saludo mainnet: {len(rows)} muestreados, {results['match']} coinciden, "
        f"{results['agent']} con otro user agent, {results['protocol']} con otro protocolo, "
        f"{results['both']} con ambos distintos, {results['missing']} con algún valor sin guardar, "
        f"{incomplete} sin saludo completo ({results['timeout']} por tiempo de espera)."
    )
    return int(bool(different or results["agent"] or results["protocol"] or results["both"]))


if __name__ == "__main__":
    sys.exit(main())
