#!/usr/bin/env python3
"""
Auralis Miner - one file, standard library only (no pip install, no other files).

  python auralis_miner.py --address AURyouraddress --name MyMinerName
  python auralis_miner.py --address AUR... --cores 4
  python auralis_miner.py --address AUR... --mine-empty

The Auralis node builds the block and sends this miner a header and a target.
The miner searches for a nonce and sends it back. It holds no keys and no chain
data, and cannot create tokens. Mining pays the fees of the payments you confirm
to YOUR address (there is no block reward).
"""
import argparse
import hashlib
import json
import multiprocessing as mp
import os
import random
import sys
import time
import urllib.error
import urllib.request

VERSION = "2.2"
DEFAULT_NODE = "https://auralisnetwork.org"
COIN = 10 ** 8
POLL = 2.0


def valid_address(a):
    return (isinstance(a, str) and len(a) == 47 and a.startswith("AUR")
            and all(c in "0123456789abcdef" for c in a[3:])
            and hashlib.sha256(a[3:43].encode()).hexdigest()[:4] == a[43:])


def fmt(units):
    whole, frac = divmod(units, COIN)
    s = f"{whole:,}"
    return s + ("." + f"{frac:08d}".rstrip("0") if frac else "")


class Net:
    def __init__(self, nodes):
        self.nodes = [n.strip().rstrip("/") for n in nodes]

    def _call(self, base, path, body=None):
        data = json.dumps(body).encode() if body is not None else None
        req = urllib.request.Request(base + path, data=data, headers={
            "Content-Type": "application/json", "User-Agent": f"auralis-miner/{VERSION}"})
        with urllib.request.urlopen(req, timeout=15) as r:
            return json.loads(r.read(2_000_000))

    @staticmethod
    def _msg(e):
        try:
            return json.loads(e.read()).get("error") or str(e.code)
        except Exception:
            return str(e.code)

    def get(self, path):
        last = None
        for i, base in enumerate(self.nodes):
            try:
                out = self._call(base, path)
                if i:
                    self.nodes.insert(0, self.nodes.pop(i))
                return out
            except urllib.error.HTTPError as e:
                if e.code == 400:
                    raise ValueError(self._msg(e))
                last = e
            except Exception as e:
                last = e
        raise ConnectionError(f"no node reachable ({last})")

    def post(self, path, body):
        try:
            return self._call(self.nodes[0], path, body)
        except urllib.error.HTTPError as e:
            raise ValueError(self._msg(e))


def _worker(head, target, start, step, stop, out, rates, idx):
    sha = hashlib.sha256
    nonce, n, t0 = start, 0, time.time()
    while True:
        d = sha((head + str(nonce)).encode()).hexdigest()
        n += 1
        if int(d, 16) < target:
            rates[idx] = n / max(time.time() - t0, 1e-6)
            out.put(nonce)
            stop.set()
            return
        nonce += step
        if n % 20_000 == 0:
            rates[idx] = n / max(time.time() - t0, 1e-6)      # this core's own measured speed
            if stop.is_set():
                return


class Miner:
    def __init__(self, net, address, cores, mine_empty):
        self.net, self.address, self.cores, self.mine_empty = net, address, cores, mine_empty
        self.ctx = mp.get_context("spawn")
        self.mined = self.earned = 0
        self.hps = 0.0                    # measured hashes per second, reported to the node

    def calibrate(self, seconds=1.0):
        """Measure this PC's hash rate once at start, so it is counted even while waiting for payments."""
        stop, out = self.ctx.Event(), self.ctx.Queue()
        rates = self.ctx.Array("d", self.cores, lock=False)
        procs = [self.ctx.Process(target=_worker, daemon=True,
                                  args=("calibrate|", 0, i, self.cores, stop, out, rates, i))
                 for i in range(self.cores)]
        for p in procs:
            p.start()
        time.sleep(seconds + 0.5)
        stop.set()
        for p in procs:
            p.join(timeout=2)
            if p.is_alive():
                p.terminate()
        self.hps = sum(rates)

    def work(self):
        return self.net.get(f"/api/getwork?address={self.address}&hps={int(self.hps)}")

    def run(self):
        fails = 0
        while True:
            try:
                w = self.work()
                fails = 0
                if w["payments"] == 0 and not self.mine_empty:
                    print(f"\rHeight {w['height'] - 1} | no payments waiting | mined "
                          f"{self.mined} blocks, earned {fmt(self.earned)} AUR   ", end="", flush=True)
                    time.sleep(POLL)
                    continue
                self.round(w)
            except KeyboardInterrupt:
                raise
            except (ConnectionError, urllib.error.URLError, OSError) as e:
                fails += 1
                wait = min(60, 3 * fails)
                print(f"\nCannot reach the node ({e}). Retrying in {wait}s...")
                time.sleep(wait)
            except (ValueError, KeyError) as e:
                print(f"\n{e}")
                time.sleep(5)

    def round(self, w):
        print(f"\nMining block {w['height']} ({w['payments']} payment(s), {self.cores} core(s))...")
        target = int(w["target"], 16)
        stop, out = self.ctx.Event(), self.ctx.Queue()
        rates = self.ctx.Array("d", self.cores, lock=False)
        base = random.randrange(2 ** 40)
        procs = [self.ctx.Process(target=_worker, daemon=True,
                                  args=(w["head"], target, base + i, self.cores, stop, out,
                                        rates, i))
                 for i in range(self.cores)]
        for p in procs:
            p.start()
        started, nonce = time.time(), None
        try:
            while nonce is None:
                try:
                    nonce = out.get(timeout=POLL)
                    break
                except Exception:
                    pass
                try:
                    cur = self.work()
                except Exception:
                    continue
                if cur["tip"] != w["tip"]:
                    return                                   # another miner found a block
                if cur["id"] != w["id"] and time.time() - started > 3:
                    return                                   # new payments: take fresh work
        finally:
            stop.set()
            for p in procs:
                p.join(timeout=2)
                if p.is_alive():
                    p.terminate()
            total = sum(rates)
            if total > 0:
                self.hps = total
        try:
            res = self.net.post("/api/submitwork", {"id": w["id"], "nonce": nonce})
        except ValueError as e:
            print(f"Not accepted: {e}")
            return
        if res.get("status") == "added":
            self.mined += 1
            self.earned += w["payout"]
            print(f"Mined block {w['height']}! You earned {fmt(w['payout'])} AUR in fees "
                  f"(total {fmt(self.earned)} AUR)")
        else:
            print(f"Block {w['height']} was {res.get('status')} (another miner was faster)")


def ensure_approved(net, address, name):
    """Register a unique miner name (free, nothing goes on the chain) and wait for admin approval."""
    shown = False
    while True:
        st = net.get(f"/api/minerstatus?address={address}")
        s = st.get("status")
        if s == "approved":
            print(f'Approved as "{st.get("name")}".')
            return
        if s in ("rejected", "revoked"):
            sys.exit(f"This address was {s}. Contact the Auralis admin (Telegram @auralisdev).")
        if s == "none":
            while True:
                if not name:
                    if not sys.stdin.isatty():
                        sys.exit("Use --name YourMinerName to register this address.")
                    name = input("Choose a miner name (3-20 letters, numbers, - or _): ").strip()
                try:
                    net.post("/api/minerregister", {"address": address, "name": name})
                    break
                except ValueError as e:
                    print(f"Not accepted: {e}")
                    name = None
                    if not sys.stdin.isatty():
                        sys.exit(1)
            continue
        if not shown:
            print(f'Name "{st.get("name")}" is registered and waiting for admin approval. '
                  "Keep this window open, mining starts automatically once approved.")
            shown = True
        time.sleep(30)


def main():
    ap = argparse.ArgumentParser(description="Auralis public miner")
    ap.add_argument("--address", required=True, help="your AUR address; fees are paid here")
    ap.add_argument("--name", help="your unique miner name (3-20 letters, numbers, - _); asked once, needs admin approval")
    ap.add_argument("--node", action="append", help=f"node URL (repeatable), default {DEFAULT_NODE}")
    ap.add_argument("--cores", type=int, default=1, help="CPU cores to use (default 1)")
    ap.add_argument("--mine-empty", action="store_true", help="also mine when no payment is waiting")
    a = ap.parse_args()
    if not valid_address(a.address):
        sys.exit("--address is not a valid AUR address (starts with AUR, 47 characters)")
    cores = max(1, min(a.cores, os.cpu_count() or 1))
    print(f"Auralis Miner {VERSION}\nFees go to {a.address}")
    print("Note: mining pays transaction fees only, there is no block reward.")
    m = Miner(Net(a.node or [DEFAULT_NODE]), a.address, cores, a.mine_empty)
    try:
        ensure_approved(m.net, a.address, a.name)
    except KeyboardInterrupt:
        sys.exit("\nStopped.")
    except (ConnectionError, ValueError, urllib.error.URLError, OSError) as e:
        sys.exit(f"Cannot reach the node: {e}")
    try:
        w = m.work()
    except (ConnectionError, ValueError, urllib.error.URLError, OSError) as e:
        sys.exit(f"Cannot get work from the node: {e}")
    print(f"Connected. Next block is {w['height']}. Press Ctrl+C to stop.")
    print("Measuring your hash rate (1 second)...")
    m.calibrate()
    print(f"Your hash rate: {m.hps / 1e6:.2f} MH/s ({cores} core(s)). It is added to the network hashrate on the explorer.")
    m.work()
    try:
        m.run()
    except KeyboardInterrupt:
        print("\nStopped.")


if __name__ == "__main__":
    mp.freeze_support()
    main()
