#!/usr/bin/env python3 """GOURDES mining client: reads challenge/effectiveTarget from an RPC, solves on the GPU (gminer.Solver), submits GourdesMiner.mine(nonce), and restarts the search the moment the challenge changes under it. Safety model - DRY-RUN BY DEFAULT: prints solutions, sends nothing. Sending needs --send plus --keyfile. - PINNED CONFIG (--config, JSON): the chain id, the miner contract address, the token address and the keccak256 of both deployed bytecodes are fixed in the config file and verified against the RPC at startup; the chain id is re-checked before every single send. Nothing the RPC says can move the client to another chain, another contract or another token. - HARD GAS CAPS per transaction type (config gas_caps: mine/forward/cancel). An estimate above the cap means the transaction is NOT sent. - SPEND GUARD: max native coin spent per hour and per day (config), measured from the wallet's real balance, not from receipts. Exceeded -> breaker: stop file written, exit 3. - REVERT/UNCONFIRMED CIRCUIT BREAKER: after N consecutive on-chain reverts or unconfirmed sends (config max_consecutive_failures, default 3) -> breaker. - RECEIPTS ARE VERIFIED, never trusted: the receipt's block hash must match the canonical block, a successful mine/forward must carry a log from the pinned contract/token address, and the receipt only counts after `confirmations` blocks. When a second independent RPC is configured (config rpc2) it must agree on every receipt and on the wallet balance; disagreement -> breaker . The pre-send digest check also reads effectiveTarget from rpc2 when available. - The STOP FILE is honoured in every loop, including while a transaction is pending or stuck ; a dangling-symlink stop file or an unreadable one counts as STOP (fail closed). Every receipt wait has an absolute deadline; on expiry the nonce is re-synced from the chain (reorg/nonce recovery). - Mines against effectiveTarget() (the contract's eased difficulty), understands the contract's full custom error set, idles (GPU off) while the contract is not started, and waits a block on OneSolutionPerBlock. The selector table lives in SELECTORS below and is checked against the ABI file named in the config at startup. - Forwarding destination validated at startup: checksummed, not zero, not the hot key, not the token, not the miner, and not a contract unless --allow-contract-forward. - The GPU must be named explicitly (--gpu-uuid); the client refuses to fall back to device 0 . --send without a price source needs an explicit --no-profit-gate. - RPC URLs are never logged (scheme://host only) and are redacted from error strings. The key file must be chmod 600 in a directory owned by this user and not group/world-writable , and all local configuration is validated before the first RPC request. - An RPC outage pauses the GPU and retries with backoff instead of crashing. Exit codes: 0 clean stop / mining finished; 2 configuration or validation error (never worth a systemd restart); 3 safety breaker tripped (the stop file is written first so a restart exits cleanly instead of looping); 1 unexpected crash. Monitoring: structured JSON log lines on stdout; a one-line status file (--status-file) rewritten atomically on every state change. """ import argparse, importlib, json, math, os, re, stat, sys, threading, time, traceback from datetime import datetime, timezone from urllib.parse import urlsplit from zoneinfo import ZoneInfo # --hours defaults to 'always'. A ready-made restricted window, for an operator who wants the card idle on # weekday daytime: weekday nights (19:00 -> 08:00 next morning) and all weekend, in the --tz time zone. # sun-thu evenings wrap into mon-fri mornings; fri evening wraps into sat via the fri rule. NIGHTS_AND_WEEKENDS = 'sun-thu:19:00-08:00,fri:19:00-24:00,sat:00:00-24:00,sun:00:00-24:00' DEFAULT_HOURS = NIGHTS_AND_WEEKENDS # older name for the same window, kept for code that imports it; NOT the --hours default ERC20_ABI = json.loads("""[ {"type":"function","name":"balanceOf","stateMutability":"view","inputs":[{"type":"address"}],"outputs":[{"type":"uint256"}]}, {"type":"function","name":"transfer","stateMutability":"nonpayable", "inputs":[{"name":"to","type":"address"},{"name":"amount","type":"uint256"}],"outputs":[{"type":"bool"}]} ]""") # Functions run.py calls; all must exist in the configured ABI (startup self-check). REQUIRED_FUNCTIONS = ('challenge', 'effectiveTarget', 'currentReward', 'solutionCount', 'TOKEN', 'started', 'mine', 'digestFor') # ----------------------------------------------------------------------------- logging / redaction _REDACT = [] # (secret_url, safe_form) def safe_url(u): p = urlsplit(u) host = p.hostname or '?' return f'{p.scheme}://{host}' + (f':{p.port}' if p.port else '') def register_secret_url(u): """Remember an RPC URL so it never reaches a log line. Besides the full URL, the path+query part and any userinfo are registered too: urllib3/requests error strings carry the path separately from the host ("... url: /v2/KEY"), so replacing only the full URL is not enough.""" if not u: return _REDACT.append((u, safe_url(u))) p = urlsplit(u) tail = p.path + ('?' + p.query if p.query else '') if len(tail) > 1: _REDACT.append((tail, '/')) if p.query: _REDACT.append((p.query, '')) if p.password: _REDACT.append((p.password, '')) if p.username: _REDACT.append((p.username, '')) _REDACT.sort(key=lambda x: -len(x[0])) # longest first so the full URL wins over its parts def redact(s): s = str(s) for url, safe in _REDACT: s = s.replace(url, safe) s = re.sub(r'(https?://)[^/\s"\'<>]*@', r'\1@', s) # any userinfo in any URL return s def log(ev, **kw): print(json.dumps({'ts': datetime.now(timezone.utc).isoformat(timespec='seconds'), 'ev': ev, **kw}), flush=True) def fatal(msg): """Configuration / validation error: exit 2 (systemd: RestartPreventExitStatus=2).""" log('fatal', error=redact(msg)[:400]) sys.exit(2) def transient(msg): """Startup failure a restart may fix (RPC unreachable): exit 1, so systemd retries with its back-off and start limit instead of treating an outage as a permanent config error.""" log('startup_unreachable', error=redact(msg)[:400]) sys.exit(1) GPU_UUID_RE = re.compile(r'^GPU-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$') class MiningFinishedError(Exception): pass # ----------------------------------------------------------------------------- contract error set def _keccak(data: bytes) -> bytes: from Crypto.Hash import keccak return keccak.new(digest_bits=256, data=data).digest() def _selector(sig: str) -> str: return '0x' + _keccak(sig.encode())[:4].hex() # Single source of truth for GourdesMiner's custom errors. Checked against the ABI file # named in the config at startup; a contract change that touches the error set fails loudly there. ERROR_SIGS = ('ZeroAddress()', 'BadParams()', 'InvalidSolution()', 'MiningFinished()', 'NotStarted()', 'AlreadyStarted()', 'NotStarter()', 'OneSolutionPerBlock()') SELECTORS = {sig.split('(')[0]: _selector(sig) for sig in ERROR_SIGS} def classify_revert(exc): """Name of the custom error carried by a revert, or None. Custom errors surface as a 4-byte selector in the revert data, not by name.""" blob = f'{getattr(exc, "data", "")} {exc}' for name, sel in SELECTORS.items(): if sel in blob or sel[2:] in blob or name in blob: return name return None # ----------------------------------------------------------------------------- time window DAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] _TIME_RE = re.compile(r'^([01][0-9]|2[0-4]):([0-5][0-9])$') def _minute(s, allow24): m = _TIME_RE.match(s) if not m: raise ValueError(f'bad time {s!r}: need two-digit ASCII HH:MM between 00:00 and 24:00') h, mm = int(m.group(1)), int(m.group(2)) if h == 24 and (mm != 0 or not allow24): raise ValueError(f'bad time {s!r}: 24:00 is only valid as the end of a span') return h * 60 + mm def parse_hours(spec: str): """'mon-fri:19:00-08:00,sat:00:00-24:00' -> list of [start,end) minute intervals on a weekly 10080-minute circle. A span whose end <= start wraps overnight into the NEXT day. Returns None only for the explicit literal 'always'. Fails closed: an empty or malformed spec is an error, a zero-length span is an error.""" s = spec.strip() if not s: raise ValueError("--hours is empty; write 'always' explicitly to run with no window") if not s.isascii(): raise ValueError('--hours must be ASCII') if s.lower() == 'always': return None iv = [] for rule in s.split(','): rule = rule.strip() if not rule: raise ValueError(f'empty rule in --hours {spec!r}') try: days_s, span = rule.split(':', 1) start_s, end_s = span.rsplit('-', 1) except ValueError: raise ValueError(f'bad rule {rule!r}: need day[-day]:HH:MM-HH:MM') from None if '-' in days_s: a, b = days_s.split('-', 1) if a not in DAYS or b not in DAYS: raise ValueError(f'bad day range {days_s!r} (days are {DAYS})') d0, d1 = DAYS.index(a), DAYS.index(b) days = list(range(d0, d1 + 1)) if d1 >= d0 else list(range(d0, 7)) + list(range(0, d1 + 1)) else: if days_s not in DAYS: raise ValueError(f'bad day {days_s!r} (days are {DAYS})') days = [DAYS.index(days_s)] start, end = _minute(start_s, allow24=False), _minute(end_s, allow24=True) if start == end: raise ValueError(f'zero-length span {span!r} in {rule!r}') for d in days: if end > start: iv.append((d * 1440 + start, d * 1440 + end)) else: # overnight wrap into the next day iv.append((d * 1440 + start, d * 1440 + 1440)) nd = (d + 1) % 7 if end > 0: iv.append((nd * 1440, nd * 1440 + end)) return iv def in_window(intervals, tz) -> bool: if intervals is None: return True now = datetime.now(tz) wm = now.weekday() * 1440 + now.hour * 60 + now.minute return any(a <= wm < b for a, b in intervals) # ----------------------------------------------------------------------------- config (pins) class Config: DEFAULT_GAS_CAPS = {'mine': 200_000, 'forward': 80_000, 'cancel': 25_000} KEYS = {'chain_id', 'contract', 'token', 'contract_code_hash', 'token_code_hash', 'abi_file', 'rpc2', 'confirmations', 'gas_caps', 'max_native_per_hour_wei', 'max_native_per_day_wei', 'max_consecutive_failures', 'unconfirmed_deadline_s'} def __init__(self, path): try: raw = json.load(open(path)) except (OSError, ValueError) as e: fatal(f'config {path}: {e}') from web3 import Web3 if not isinstance(raw, dict): fatal(f'config {path}: top level must be a JSON object') unknown = sorted(k for k in raw if not k.startswith('_') and k not in self.KEYS) if unknown: # a typo must not silently fall back to a default (e.g. a spend cap) fatal(f'config {path}: unknown keys {unknown} (known: {sorted(self.KEYS)})') def addr(k): v = raw.get(k) if not isinstance(v, str) or not Web3.is_checksum_address(v): fatal(f'config {k} must be a checksummed address, got {v!r}') if int(v, 16) == 0: fatal(f'config {k} is the zero address; fill in the deployed address') return v def h32(k): v = raw.get(k, '') if not isinstance(v, str) or not re.fullmatch(r'0x[0-9a-fA-F]{64}', v): fatal(f'config {k} must be a 0x 32-byte hex hash, got {v!r}') return v.lower() def posint(k, default=None): v = raw.get(k, default) if not isinstance(v, int) or isinstance(v, bool) or v <= 0: fatal(f'config {k} must be a positive integer, got {v!r}') return v self.chain_id = posint('chain_id', 8453) self.contract = addr('contract') self.token = addr('token') self.contract_code_hash = h32('contract_code_hash') self.token_code_hash = h32('token_code_hash') abi_file = raw.get('abi_file') if not abi_file or not isinstance(abi_file, str): fatal('config abi_file is required (path to the compiled GourdesMiner artifact or ABI)') if not os.path.isabs(abi_file): abi_file = os.path.join(os.path.dirname(os.path.abspath(path)), abi_file) try: art = json.load(open(abi_file)) except (OSError, ValueError) as e: fatal(f'config abi_file {abi_file}: {e}') self.abi = art.get('abi') if isinstance(art, dict) else art if not isinstance(self.abi, list) or not all(isinstance(i, dict) for i in self.abi): fatal(f'config abi_file {abi_file}: not an ABI list (or artifact with "abi")') self.rpc2 = raw.get('rpc2') or None if self.rpc2 is not None and (not isinstance(self.rpc2, str) or urlsplit(self.rpc2).scheme not in ('http', 'https')): fatal('config rpc2 must be an http(s) URL string or null') self.confirmations = posint('confirmations', 2) caps = dict(self.DEFAULT_GAS_CAPS) gc = raw.get('gas_caps', {}) if not isinstance(gc, dict): fatal(f'config gas_caps must be an object {{"mine":..,"forward":..,"cancel":..}}, got {gc!r}') for k, v in gc.items(): if k not in caps or not isinstance(v, int) or isinstance(v, bool) or v <= 0: fatal(f'config gas_caps: unknown key or non-positive value {k}={v!r}') caps[k] = v if caps['cancel'] < 21_000: fatal('config gas_caps.cancel must be at least 21000 (a plain transfer)') self.gas_caps = caps # Spend defaults (native wei; the default chain is Base, so ETH). Measured mine gas is 74,671 # typical / 160,171 worst on a local test chain. The worst case of ONE send at the 5 gwei default # ceiling is the 200k cap x 5 gwei = 0.001 native, so 0.01/hour allows about ten worst-case sends # (or ~130 typical ones) per hour and 0.05/day five hours of that. At Base's usual ~0.01-0.05 # gwei the real cost of one solution is ~1e12-4e12 wei, far below both caps. self.max_native_per_hour_wei = posint('max_native_per_hour_wei', 10 * 10**15) # 0.01 self.max_native_per_day_wei = posint('max_native_per_day_wei', 50 * 10**15) # 0.05 self.max_consecutive_failures = posint('max_consecutive_failures', 3) self.unconfirmed_deadline_s = posint('unconfirmed_deadline_s', 60) if self.max_native_per_hour_wei > self.max_native_per_day_wei: fatal('config max_native_per_hour_wei must not exceed max_native_per_day_wei') if self.confirmations > 64: fatal('config confirmations must be <= 64') if 'mine' in raw.get('gas_caps', {}) and self.gas_caps['mine'] < 50_000: fatal('config gas_caps.mine below 50000 cannot fit a mine() call (measured ~75k)') self.check_abi() def check_abi(self): """SELECTORS (the table the client acts on) must equal the error set in the configured ABI, and every function the client calls must exist there.""" abi_errors = {} fns = set() for item in self.abi: if item.get('type') == 'error': sig = item['name'] + '(' + ','.join(i['type'] for i in item.get('inputs', [])) + ')' abi_errors[item['name']] = _selector(sig) elif item.get('type') == 'function': fns.add(item.get('name')) if abi_errors != SELECTORS: missing = set(SELECTORS) - set(abi_errors) extra = set(abi_errors) - set(SELECTORS) changed = {n for n in set(abi_errors) & set(SELECTORS) if abi_errors[n] != SELECTORS[n]} fatal(f'contract error set changed: ABI vs client table — missing from ABI: {sorted(missing)}, ' f'new in ABI: {sorted(extra)}, selector changed: {sorted(changed)}. ' f'Update SELECTORS in run.py for the final contract.') lacking = [f for f in REQUIRED_FUNCTIONS if f not in fns] if lacking: fatal(f'configured ABI lacks functions the client needs: {lacking}') # ----------------------------------------------------------------------------- chain watcher class Watcher(threading.Thread): """Polls started/challenge/effectiveTarget/currentReward every interval; the solver aborts when the challenge moves. Tracks the time of the last good read so the client can idle the GPU during an RPC outage.""" def __init__(self, miner_c, interval): super().__init__(daemon=True) self.miner_c = miner_c; self.interval = interval self.lock = threading.Lock() self.challenge = None; self.target = None; self.reward = None; self.started_flag = None self.last_ok = 0.0 self.ok = threading.Event(); self.stopped = threading.Event() def run(self): while not self.stopped.is_set(): try: st = self.miner_c.functions.started().call() ch = self.miner_c.functions.challenge().call() tg = self.miner_c.functions.effectiveTarget().call() rw = self.miner_c.functions.currentReward().call() with self.lock: self.challenge, self.target, self.reward, self.started_flag = bytes(ch), tg, rw, st self.last_ok = time.time() self.ok.set() except Exception as e: # RPC hiccup: keep last-known state, retry log('watcher_rpc_error', error=redact(e)[:200]) self.stopped.wait(self.interval) def snap(self): with self.lock: return self.challenge, self.target, self.reward, self.started_flag def stale(self): return time.time() - self.last_ok > max(10 * self.interval, 15.0) # ----------------------------------------------------------------------------- client class Client: def __init__(self, a, cfg): from web3 import Web3 self.Web3 = Web3 self.a = a self.cfg = cfg # Everything local (key, addresses, numbers) is already validated before this point; # the first network request happens in startup_checks(). self.acct = None if a.send: self.acct = self._load_key(a.keyfile) self.sender = self.acct.address else: if not a.sender: fatal('dry-run needs --sender (the address solutions are solved for)') if not Web3.is_checksum_address(a.sender): fatal(f'--sender {a.sender!r} is not a checksummed address') self.sender = a.sender self._validate_forward_local() register_secret_url(a.rpc) register_secret_url(cfg.rpc2) self.w3 = Web3(Web3.HTTPProvider(a.rpc, request_kwargs={'timeout': 10})) self.w3b = Web3(Web3.HTTPProvider(cfg.rpc2, request_kwargs={'timeout': 10})) if cfg.rpc2 else None self.miner_c = self.w3.eth.contract(address=cfg.contract, abi=cfg.abi) self.miner_b = self.w3b.eth.contract(address=cfg.contract, abi=cfg.abi) if self.w3b else None self.token_c = self.w3.eth.contract(address=cfg.token, abi=ERC20_ABI) self.price_hook = self._make_price_hook(a) self.hours = parse_hours(a.hours) self.tz = ZoneInfo(a.tz) self.next_nonce = None self._last_receipt = None self.recent_accepts = [] # [(txh, blockNumber, blockHash)] re-checked for reorgs self._last_reorg_check = 0.0 self.failures = 0 # consecutive on-chain reverts / unconfirmed sends self.samples = [] # (t, confirmed native balance) for the spend guard self._last_sample = 0.0 # Own txs not yet seen mined at the confirmed block: nonce -> worst-case fee (wei) of the # newest tx at that nonce. Reserved against the spend headroom, never gap-filled, never # reused by resync_nonce. self.inflight = {} self.stats = {'accepted': 0, 'reverted': 0, 'stale_aborts': 0, 'stale_discards': 0, 'replacements': 0, 'cancels': 0, 'forwards': 0, 'skipped_unprofitable': 0, 'unconfirmed': 0, 'gas_cap_skips': 0, 'spend_cap_waits': 0, 'reorged_out': 0, 'unrewarded': 0, 'gap_fills': 0, 'hashes': 0} self.t_start = time.time() self.wait_deadline_s = max(2 * a.replace_after, float(cfg.unconfirmed_deadline_s)) self.watch = Watcher(self.miner_c, a.poll_interval) self.solver = None # created lazily, after CUDA_VISIBLE_DEVICES is set # ---- local validation --------------------------------------------------- @staticmethod def _load_key(path): from eth_account import Account if not path: fatal('--send requires --keyfile') try: st = os.stat(path) except OSError as e: fatal(f'keyfile {path}: {e.strerror}') if not stat.S_ISREG(st.st_mode) or (st.st_mode & 0o077): fatal(f'keyfile {path} must be a regular file with mode 600 (is {oct(st.st_mode & 0o777)})') d = os.path.dirname(os.path.abspath(path)) or '.' sd = os.stat(d) if sd.st_uid != os.getuid() or (sd.st_mode & 0o022): fatal(f'keyfile directory {d} must be owned by uid {os.getuid()} and not group/world-' f'writable (is uid {sd.st_uid}, mode {oct(sd.st_mode & 0o777)})') key = open(path).read().strip() try: acct = Account.from_key(key) except Exception as e: # never echo the key material in the error fatal(f'keyfile {path}: not a valid private key ({type(e).__name__})') del key return acct def _validate_forward_local(self): a, cfg = self.a, self.cfg if not a.forward_to: return if not self.Web3.is_checksum_address(a.forward_to): fatal(f'--forward-to {a.forward_to!r} must be a checksummed address (checksum verified)') bad = {'0x' + '00' * 20: 'the zero address', cfg.token: 'the token contract', cfg.contract: 'the miner contract', self.sender: 'the hot key itself'} if a.forward_to in bad: fatal(f'--forward-to {a.forward_to} is {bad[a.forward_to]}; refusing') @staticmethod def _make_price_hook(a): """Returns f(reward_token_wei) -> value in native-coin wei.""" if a.price_hook: mod, fn = a.price_hook.rsplit(':', 1) f = getattr(importlib.import_module(mod), fn) return lambda r: int(f(r)) if a.price_wei_per_gourde is not None: return lambda r: r * a.price_wei_per_gourde // 10**18 return None # ---- startup chain checks (pinned chain, contract, token) ----------------------- def startup_checks(self): cfg = self.cfg pairs = [('rpc', self.w3)] + ([('rpc2', self.w3b)] if self.w3b else []) for name, w3 in pairs: try: cid = w3.eth.chain_id except Exception as e: transient(f'{name} unreachable: {redact(e)[:200]}') if cid != cfg.chain_id: fatal(f'{name} chain id mismatch: RPC reports {cid}, config pins {cfg.chain_id}') for what, address, want in (('contract', cfg.contract, cfg.contract_code_hash), ('token', cfg.token, cfg.token_code_hash)): try: code = bytes(w3.eth.get_code(address)) except Exception as e: transient(f'{name} get_code failed: {redact(e)[:200]}') got = '0x' + _keccak(code).hex() if got != want: fatal(f'{name}: {what} code hash mismatch at {address}: got {got}, config pins {want} ' f'(code length {len(code)})') for name, mc in (('rpc', self.miner_c), ('rpc2', self.miner_b)): if mc is None: continue onchain_token = mc.functions.TOKEN().call() if self.Web3.to_checksum_address(onchain_token) != cfg.token: fatal(f'{name}: TOKEN() reported by the contract ({onchain_token}) disagrees with the ' f'pinned token {cfg.token}; the client never uses an RPC-supplied token address') if self.a.forward_to and not self.a.allow_contract_forward: code = bytes(self.w3.eth.get_code(self.a.forward_to)) if code: fatal(f'--forward-to {self.a.forward_to} has code on chain (a contract); tokens sent there ' f'may be lost. Use --allow-contract-forward only if this is intended.') if self.a.send: self.next_nonce = self.w3.eth.get_transaction_count(self.sender, 'pending') self.sample_spend(force=True) # ---- monitoring --------------------------------------------------------- def status(self, state, **kw): s = self.stats mhs = s['hashes'] / max(time.time() - self.t_start, 1e-9) / 1e6 line = (f"{datetime.now(timezone.utc).isoformat(timespec='seconds')} state={state} " f"accepted={s['accepted']} reverted={s['reverted']} stale_aborts={s['stale_aborts']} " f"stale_discards={s['stale_discards']} replacements={s['replacements']} cancels={s['cancels']} " f"forwards={s['forwards']} skipped_unprofitable={s['skipped_unprofitable']} " f"unconfirmed={s['unconfirmed']} failures={self.failures} " f"hashrate_mhs={mhs:.0f}" + ''.join(f' {k}={v}' for k, v in kw.items())) tmp = self.a.status_file + '.tmp' with open(tmp, 'w') as f: f.write(line + '\n') os.replace(tmp, self.a.status_file) def stop_requested(self): """Fail closed: a dangling symlink IS a stop request, and so is a stop file we cannot stat (permissions yanked).""" try: os.lstat(self.a.stop_file) return True except FileNotFoundError: return False except OSError: return True def breaker(self, reason, **kw): """Safety circuit breaker: write the stop file FIRST so a systemd restart exits cleanly instead of resuming the same loop, then exit 3.""" log('breaker_tripped', reason=reason, **kw) try: with open(self.a.stop_file, 'w') as f: f.write(f'breaker {reason} at {datetime.now(timezone.utc).isoformat()}\n') except OSError as e: log('breaker_stop_file_error', error=redact(e)[:200]) try: self.status('breaker', reason=reason) except Exception: pass self.watch.stopped.set() log('exit', breaker=reason, **{k: v for k, v in self.stats.items()}) sys.exit(3) # ---- spend guard -------------------------------------------------- def _common_block(self): """Highest block both RPCs have; balances are compared AT that block so ordinary head lag between two honest providers is never mistaken for a disagreement.""" h = self.w3.eth.block_number if self.w3b is not None: h = min(h, self.w3b.eth.block_number) return h def confirmed_balance(self): """The wallet's real native balance. With rpc2 configured both providers must report the same balance at the same block; any difference trips the breaker.""" blk = self._common_block() b1 = self.w3.eth.get_balance(self.sender, blk) if self.w3b is not None: b2 = self.w3b.eth.get_balance(self.sender, blk) if b2 != b1: self.breaker('balance_disagreement', block=blk, rpc1_wei=str(b1), rpc2_wei=str(b2)) return b1 def token_balance(self): """Hot key's token balance, cross-checked on rpc2 at the same block when configured.""" blk = self._common_block() t1 = self.token_c.functions.balanceOf(self.sender).call(block_identifier=blk) if self.w3b is not None: tb = self.w3b.eth.contract(address=self.cfg.token, abi=ERC20_ABI) t2 = tb.functions.balanceOf(self.sender).call(block_identifier=blk) if t2 != t1: self.breaker('token_balance_disagreement', block=blk, rpc1=str(t1), rpc2=str(t2)) return t1 def sample_spend(self, force=False): if not self.a.send: return now = time.time() if not force and now - self._last_sample < 10: return try: bal = self.confirmed_balance() except SystemExit: raise except Exception as e: log('balance_read_error', error=redact(e)[:200]) return self._last_sample = now self.samples.append((now, bal)) # keep the newest sample older than a day plus everything younger cut = 0 for i, (t, _) in enumerate(self.samples): if t <= now - 86400: cut = i self.samples = self.samples[cut:] cfg = self.cfg for window, cap, name in ((3600, cfg.max_native_per_hour_wei, 'hour'), (86400, cfg.max_native_per_day_wei, 'day')): base = None for t, b in self.samples: if t <= now - window: base = b else: break if base is None: base = self.samples[0][1] # client younger than the window: measure from start spent = base - bal if spent > cap: self.breaker('spend_cap_exceeded', window=name, spent_wei=str(spent), cap_wei=str(cap)) def spend_headroom(self): """Native wei still spendable before the hourly or daily cap is hit, from a fresh balance.""" self.sample_spend(force=True) if not self.samples: return 0 # no balance reading at all: fail closed, send nothing now, bal = self.samples[-1] if time.time() - now > 30: return 0 # the fresh read failed: an old balance would overstate the room room = None for window, cap in ((3600, self.cfg.max_native_per_hour_wei), (86400, self.cfg.max_native_per_day_wei)): base = self.samples[0][1] for t, b in self.samples: if t <= now - window: base = b else: break r = cap - (base - bal) room = r if room is None else min(room, r) return room def spend_allows(self, gas_limit, max_fee, kind, nonce): """Pre-send half of the spend guard: a tx whose worst-case fee (gas limit x max fee), plus the worst case of every other own tx still in flight, would push the hour/day spend over its cap is not sent at all. A tx at a nonce already in flight replaces that reservation.""" room = self.spend_headroom() self.purge_inflight() room -= sum(v for n, v in self.inflight.items() if n != nonce) worst = gas_limit * max_fee if worst > room: self.stats['spend_cap_waits'] += 1 log('spend_cap_wait', kind=kind, worst_case_wei=str(worst), headroom_wei=str(room)) return False return True def note_outcome(self, outcome): if outcome == 'accepted': self.failures = 0 elif outcome in ('reverted', 'unconfirmed'): self.failures += 1 log('consecutive_failures', count=self.failures, limit=self.cfg.max_consecutive_failures) self.sample_spend(force=True) if self.failures >= self.cfg.max_consecutive_failures: self.breaker('consecutive_failures', count=self.failures) def resync_nonce(self): try: pend = self.w3.eth.get_transaction_count(self.sender, 'pending') self.purge_inflight() # an own tx that is still unresolved keeps its nonce: never replace it by accident with # the next send (an RPC whose 'pending' count lags or equals 'latest') self.next_nonce = max([pend] + [n + 1 for n in self.inflight]) log('nonce_resync', nonce=self.next_nonce, rpc_pending=pend, inflight=sorted(self.inflight)) except Exception as e: log('nonce_resync_error', error=redact(e)[:200]) # ---- gas / profit ------------------------------------------------------- def fees(self): base = self.w3.eth.get_block('latest')['baseFeePerGas'] tip = min(self.a.priority_fee_wei, self.a.max_fee_wei) max_fee = min(2 * base + tip, self.a.max_fee_wei) return base, tip, max_fee def profitable(self, gas, max_fee, reward): """True when gas cost <= fraction * reward value. The gate cannot be silently off: --send without a price source requires an explicit --no-profit-gate.""" if self.price_hook is None: return True cost = gas * max_fee value = self.price_hook(reward) ok = cost <= int(self.a.max_gas_reward_fraction * value) if not ok: self.stats['skipped_unprofitable'] += 1 log('skip_unprofitable', gas=gas, max_fee=max_fee, cost_wei=cost, reward_value_wei=value) return ok # ---- tx machinery ------------------------------------------------------- def _send(self, tx): # The chain id is pinned in config and re-checked against the RPC before EVERY send. for name, w3 in (('rpc', self.w3), ('rpc2', self.w3b)): if w3 is None: continue cid = w3.eth.chain_id if cid != self.cfg.chain_id: self.breaker('chain_id_changed', rpc=name, rpc_chain_id=cid, pinned=self.cfg.chain_id) assert tx.get('chainId') == self.cfg.chain_id, 'tx built with a non-pinned chain id' signed = self.acct.sign_transaction({k: v for k, v in tx.items() if k != 'from'}) h = self.w3.eth.send_raw_transaction(signed.raw_transaction) self.inflight[tx['nonce']] = tx['gas'] * tx['maxFeePerGas'] return h def purge_inflight(self): """Drops reservations for nonces already used at the confirmed block (their cost is in the balance there). A failed read keeps every reservation (fails toward sending less).""" if not self.inflight: return try: used = self.w3.eth.get_transaction_count(self.sender, self._common_block()) except SystemExit: raise except Exception: return for n in [n for n in self.inflight if n < used]: del self.inflight[n] def check_receipt(self, txh, kind): """('none'|'pending'|'ok'|'fake', receipt). The receipt's block hash must match the canonical block, a successful mine/forward must log from the pinned address, confirmations must be met, and rpc2 (when configured) must agree — disagreement trips the breaker.""" try: r = self.w3.eth.get_transaction_receipt(txh) except Exception: return 'none', None if r is None or r.get('blockNumber') is None: return 'none', None try: blk = self.w3.eth.get_block(r['blockNumber']) head = self.w3.eth.block_number except Exception: return 'none', None if bytes(blk['hash']) != bytes(r['blockHash']): return 'fake', None # fabricated receipt, or the block was reorged away if head - r['blockNumber'] + 1 < self.cfg.confirmations: return 'pending', r if r['status'] == 1: need = {'mine': self.cfg.contract, 'forward': self.cfg.token}.get(kind) if need is not None and not any(lg['address'] == need for lg in r['logs']): return 'fake', None # a "successful" mine/forward with no event from the pinned address if self.w3b is not None: try: r2 = self.w3b.eth.get_transaction_receipt(txh) except Exception: r2 = None if r2 is None or r2.get('blockNumber') is None: return 'pending', r # second RPC has not seen it yet; the wait deadline bounds this if bytes(r2['blockHash']) != bytes(r['blockHash']) or r2['status'] != r['status']: self.breaker('rpc_receipt_disagreement', tx=txh.hex()) return 'ok', r def _nonce_hole(self, nonce): """Nonces below `nonce` that no executable tx of ours fills (a reorg or a node dropped an earlier tx): the pending tx at `nonce` can then never be mined. None when there is no hole.""" try: pend = self.w3.eth.get_transaction_count(self.sender, 'pending') if self.w3b is not None: # both RPCs must see the hole (one lagging backend is not a hole) pend = max(pend, self.w3b.eth.get_transaction_count(self.sender, 'pending')) except Exception: return None self.purge_inflight() holes = [n for n in range(pend, nonce) if n not in self.inflight] return holes or None def _fill_nonce_hole(self, holes): """Nonce recovery: a 0-value self-transfer at every hole nonce, so the waiting tx becomes executable again and the existing receipt/stale/cancel logic resolves it. Each fill is a 21,000-gas tx under the cancel gas cap and the spend guard; a reorged original that a node re-injects is outbid by the bumped fee.""" base, tip, max_fee = self.fees() fee = min(max(max_fee, 2 * base + tip) * 9 // 8 + 1, self.a.max_fee_wei) tip = min(max(tip, 1) * 9 // 8 + 1, fee) for n in holes: if self.stop_requested(): return if 21000 > self.cfg.gas_caps['cancel'] or not self.spend_allows(21000, fee, 'gap_fill', n): return tx = {'chainId': self.cfg.chain_id, 'to': self.sender, 'value': 0, 'gas': 21000, 'maxFeePerGas': fee, 'maxPriorityFeePerGas': tip, 'nonce': n, 'type': 2} try: h = self._send(tx) self.stats['gap_fills'] += 1 log('nonce_gap_fill', nonce=n, tx=h.hex()) except SystemExit: raise except Exception as e: log('nonce_gap_fill_failed', nonce=n, error=redact(e)[:200]) def _wait_mined(self, txh, solved_challenge, tx, kind='mine'): """Waits for the account nonce to resolve. The stop file is honoured on every iteration and the whole wait has an absolute deadline; on expiry the caller re-syncs the nonce and counts an unconfirmed send. On replace-timeout the fee is bumped; a mine whose solution went stale is replaced by a self-cancel at the same nonce. All txs ever sent for this nonce are watched (a replaced original can still win the race). Returns 'accepted' | 'reverted' | 'cancelled' | 'stopped' | 'unconfirmed'.""" sent = [(txh, kind)] t0 = time.time() replace_deadline = t0 + self.a.replace_after abs_deadline = t0 + self.wait_deadline_s warned_fake = set() next_hole_check = t0 + 2.0; hole_seen = 0 while True: if self.stop_requested(): log('stop_during_wait', kind=kind, pending=sent[-1][0].hex()) return 'stopped' if time.time() >= next_hole_check: # A hole below our nonce (seen twice, 2 s apart, so propagation lag is not a hole) next_hole_check = time.time() + 2.0 holes = self._nonce_hole(tx['nonce']) hole_seen = hole_seen + 1 if holes else 0 if hole_seen >= 2: log('nonce_gap', waiting_nonce=tx['nonce'], holes=holes) self._fill_nonce_hole(holes) hole_seen = 0 waiting_confs = False for h, k in sent: state, r = self.check_receipt(h, k) if state == 'ok': self._last_receipt = r if k == 'cancel': return 'cancelled' return 'accepted' if r['status'] == 1 else 'reverted' if state == 'pending': waiting_confs = True elif state == 'fake' and h not in warned_fake: warned_fake.add(h) log('fake_receipt_ignored', tx=h.hex(), kind=k) now = time.time() if now >= abs_deadline: log('wait_deadline', kind=kind, tx=sent[-1][0].hex(), waited_s=round(now - t0, 1)) return 'unconfirmed' if now >= replace_deadline and not waiting_confs: bumped = min(int(tx['maxFeePerGas'] * 9 // 8) + 1, self.a.max_fee_wei) bumped_tip = min(int(tx['maxPriorityFeePerGas'] * 9 // 8) + 1, bumped) ch = self.watch.snap()[0] stale = (kind == 'mine' and solved_challenge is not None and ch is not None and ch != solved_challenge) if stale: cancel = {'chainId': self.cfg.chain_id, 'to': self.sender, 'value': 0, 'gas': 21000, 'maxFeePerGas': bumped, 'maxPriorityFeePerGas': bumped_tip, 'nonce': tx['nonce'], 'type': 2} try: h = self._send(cancel); tx = cancel sent.append((h, 'cancel')) self.stats['cancels'] += 1 log('cancel_sent', nonce=tx['nonce'], tx=h.hex()) except SystemExit: raise except Exception as e: log('cancel_failed', error=redact(e)[:200]) # original may have just mined elif bumped > tx['maxFeePerGas'] and not self.spend_allows(tx['gas'], bumped, 'replace', tx['nonce']): pass # a bump that would break the spend cap is not sent; keep waiting elif bumped > tx['maxFeePerGas']: tx = dict(tx, maxFeePerGas=bumped, maxPriorityFeePerGas=bumped_tip) try: h = self._send(tx) sent.append((h, kind)) self.stats['replacements'] += 1 log('replaced', nonce=tx['nonce'], max_fee=bumped, tx=h.hex()) except SystemExit: raise except Exception as e: log('replace_failed', error=redact(e)[:200]) else: log('replace_skipped_at_ceiling', tx=sent[-1][0].hex()) replace_deadline = time.time() + self.a.replace_after time.sleep(self.a.poll_interval) def submit(self, nonce_int, solved_challenge, reward): """Final gates + send. Returns 'accepted' | 'discard' | 'skip' | 'reverted' | 'unconfirmed' | 'stopped' | 'same_block' | 'not_started'.""" from web3.exceptions import ContractLogicError if self.stop_requested(): return 'stopped' # Gate 1: fresh challenge read straight from the node (not the watcher cache), and from the # independent RPC when configured, so a challenge the primary invented is never solved for. for mc in (self.miner_c, self.miner_b): if mc is None: continue ch_now = bytes(mc.functions.challenge().call()) if ch_now != solved_challenge: self.stats['stale_discards'] += 1 log('stale_discard', reason='challenge_moved_before_send') return 'discard' # Gate 2: local digest check against effectiveTarget (from the independent RPC when given): # a solution that only satisfies a target the primary RPC invented never leaves the client. src = self.miner_b if self.miner_b is not None else self.miner_c try: eff = src.functions.effectiveTarget().call() except Exception as e: log('submit_error', error=redact(e)[:200]) return 'discard' digest = _keccak(solved_challenge + bytes.fromhex(self.sender[2:]) + nonce_int.to_bytes(32, 'big')) if int.from_bytes(digest, 'big') > eff: self.stats['stale_discards'] += 1 log('stale_discard', reason='digest_above_effective_target') return 'discard' fn = self.miner_c.functions.mine(nonce_int) # Gate 3: simulate against current state; a stale solution reverts here, nothing is sent. try: gas = fn.estimate_gas({'from': self.sender}) except ContractLogicError as e: name = classify_revert(e) if name == 'MiningFinished': raise MiningFinishedError(str(e)[:120]) from e if name == 'NotStarted': log('not_started_at_submit') return 'not_started' if name == 'OneSolutionPerBlock': log('same_block_wait') return 'same_block' self.stats['stale_discards'] += 1 log('stale_discard', reason='estimate_reverted', revert=name or 'unknown', error=redact(e)[:120]) return 'discard' # Gate 4: hard gas cap. An estimate above the cap means DO NOT SEND. cap = self.cfg.gas_caps['mine'] if gas > cap: self.stats['gas_cap_skips'] += 1 log('gas_cap_exceeded', kind='mine', estimate=gas, cap=cap) time.sleep(max(self.a.poll_interval, 1.0)) return 'skip' base, tip, max_fee = self.fees() if base > self.a.max_fee_wei: log('gas_over_ceiling', base_fee=base, ceiling=self.a.max_fee_wei) time.sleep(self.a.poll_interval) return 'skip' if not self.profitable(gas, max_fee, reward): time.sleep(self.a.poll_interval) return 'skip' gas_limit = min(int(gas * 12 // 10), cap) # Gate 5: spend guard, worst case of THIS tx included; the bump/cancel path is bounded by the # same max fee, so one nonce can never cost more than gas_limit x max_fee_wei. if not self.spend_allows(gas_limit, self.a.max_fee_wei, 'mine', self.next_nonce): self.status('spend_cap_wait') time.sleep(max(self.a.poll_interval, 5.0)) return 'skip' if self.stop_requested(): return 'stopped' tok0 = self.token_balance() tx = fn.build_transaction({ 'from': self.sender, 'chainId': self.cfg.chain_id, 'nonce': self.next_nonce, 'gas': gas_limit, 'maxFeePerGas': max_fee, 'maxPriorityFeePerGas': tip, 'type': 2, }) txh = self._send(tx) log('submitted', nonce=self.next_nonce, tx=txh.hex(), gas=tx['gas'], max_fee=max_fee) outcome = self._wait_mined(txh, solved_challenge, tx, kind='mine') self.resync_nonce() if outcome == 'unconfirmed': self.stats['unconfirmed'] += 1 if outcome == 'accepted': # Success is the wallet's real token balance going up (read at a common block # on both RPCs), not the receipt's status field. try: gained = self.token_balance() - tok0 except SystemExit: raise except Exception as e: log('balance_read_error', error=redact(e)[:200]); gained = 0 if gained > 0: self.stats['accepted'] += 1 r = self._last_receipt self.recent_accepts.append((r['transactionHash'], r['blockNumber'], bytes(r['blockHash']))) log('accepted', total=self.stats['accepted'], reward_wei=str(gained), tx=txh.hex(), block=r['blockNumber']) else: self.stats['unrewarded'] += 1 log('accepted_without_reward', tx=txh.hex(), token_delta=str(gained)) outcome = 'unconfirmed' elif outcome == 'reverted': self.stats['reverted'] += 1 log('reverted_onchain', tx=txh.hex()) self.note_outcome(outcome) return outcome def reconcile_reorgs(self, force=False): """An accepted solution only stays counted while its receipt is still in the canonical chain. Re-checks the recent ones; a receipt that disappeared or moved block is a reorg: un-count it and re-sync the nonce from the chain (reorged txs may have been dropped).""" now = time.time() if not self.recent_accepts or (not force and now - self._last_reorg_check < 2.0): return self._last_reorg_check = now try: head = self.w3.eth.block_number except Exception: return keep, lost = [], 0 for txh, bn, bh in self.recent_accepts: try: r = self.w3.eth.get_transaction_receipt(txh) except Exception: r = None gone = r is None or r.get('blockNumber') is None or bytes(r['blockHash']) != bh if not gone: try: gone = bytes(self.w3.eth.get_block(bn)['hash']) != bh except Exception: keep.append((txh, bn, bh)); continue if gone: lost += 1 log('reorged_out', tx=bytes(txh).hex(), block=bn) elif head - bn < 64: keep.append((txh, bn, bh)) self.recent_accepts = keep if lost: self.stats['accepted'] -= lost self.stats['reorged_out'] += lost self.resync_nonce() def forward_rewards(self): if self.stop_requested(): return bal = self.token_balance() if bal == 0: return fn = self.token_c.functions.transfer(self.a.forward_to, bal) gas = fn.estimate_gas({'from': self.sender}) cap = self.cfg.gas_caps['forward'] if gas > cap: self.stats['gas_cap_skips'] += 1 log('gas_cap_exceeded', kind='forward', estimate=gas, cap=cap) return base, tip, max_fee = self.fees() if base > self.a.max_fee_wei: log('gas_over_ceiling', base_fee=base, ceiling=self.a.max_fee_wei) return gas_limit = min(int(gas * 12 // 10), cap) if not self.spend_allows(gas_limit, self.a.max_fee_wei, 'forward', self.next_nonce): return tx = fn.build_transaction({ 'from': self.sender, 'chainId': self.cfg.chain_id, 'nonce': self.next_nonce, 'gas': gas_limit, 'maxFeePerGas': max_fee, 'maxPriorityFeePerGas': tip, 'type': 2, }) txh = self._send(tx) log('forward_submitted', nonce=self.next_nonce, tx=txh.hex(), gas=tx['gas']) outcome = self._wait_mined(txh, None, tx, kind='forward') self.resync_nonce() if outcome == 'accepted': try: left = self.token_balance() except SystemExit: raise except Exception: left = bal if left >= bal: # receipt said success but the tokens did not move: do not believe it log('forward_without_effect', tx=txh.hex(), balance_wei=str(left)) self.stats['unconfirmed'] += 1 self.note_outcome('unconfirmed') return self.stats['forwards'] += 1 log('forwarded', to=self.a.forward_to, amount_wei=str(bal - left), tx=txh.hex()) self.note_outcome('accepted') elif outcome == 'reverted': log('forward_reverted', tx=txh.hex()) self.note_outcome('reverted') elif outcome == 'unconfirmed': self.stats['unconfirmed'] += 1 self.note_outcome('unconfirmed') # ---- main loop ---------------------------------------------------------- def run(self): a = self.a log('startup', rpc=safe_url(a.rpc), rpc2=safe_url(self.cfg.rpc2) if self.cfg.rpc2 else None, chain_id=self.cfg.chain_id, contract=self.cfg.contract, token=self.cfg.token, sender=self.sender, mode='send' if a.send else 'dry-run', devices=[':'.join(str(x) for x in d) for d in a.devices], hours=a.hours, batch=a.batch, gas_caps=self.cfg.gas_caps, confirmations=self.cfg.confirmations) if self.stop_requested(): # before any network request: a breaker's stop file keeps a log('stopped', reason='stop_file_at_start', path=a.stop_file) # restarted unit down self.status('stopped'); return self.startup_checks() self.watch.start() if not self.watch.ok.wait(15): fatal('RPC unreachable: watcher never got a first read') if a.single_gpu: import gminer # after CUDA_VISIBLE_DEVICES is final self.solver = gminer.Solver(batch=a.batch) try: # The one visible device must BE the uuid we were given (PCI bus id match) info = self.solver.verify_uuid(os.environ['CUDA_VISIBLE_DEVICES']) except Exception as e: fatal(f'GPU check failed: {e}') log('gpu_device', name=self.solver.dev.name, **info) else: import msolver try: # every GPU process proves its own card; any failure refuses to start self.solver = msolver.MultiSolver(a.devices, batch=a.batch) except Exception as e: fatal(f'device check failed: {e}') for d in self.solver.devices: log('mining_device', **d) rpc_backoff = 1.0 while True: if self.stop_requested(): log('stopped', reason='stop_file', path=a.stop_file) self.status('stopped'); break if self.watch.stale(): # Outage pauses the GPU, never crashes the client self.status('rpc_wait') time.sleep(rpc_backoff) rpc_backoff = min(rpc_backoff * 2, 30.0) continue rpc_backoff = 1.0 if a.send: self.reconcile_reorgs() challenge, target, reward, started = self.watch.snap() if not started: # Contract not start()ed yet — idle, no GPU self.status('not_started') time.sleep(max(a.poll_interval, 2)) continue if not in_window(self.hours, self.tz): self.status('window_wait') time.sleep(min(30, max(a.poll_interval, 1))); continue if reward == 0: try: sols = self.miner_c.functions.solutionCount().call() except Exception: sols = None log('mining_finished', reason='reward_zero_budget_or_halving', solutions=sols) self.status('finished'); break if a.send: # pre-solve economics gate (rough gas guess; the exact check runs again before sending) try: base, tip, max_fee = self.fees() except Exception as e: log('rpc_error', error=redact(e)[:200]) self.status('rpc_wait'); time.sleep(2); continue if base > a.max_fee_wei: log('gas_over_ceiling', base_fee=base, ceiling=a.max_fee_wei) self.status('gas_wait'); time.sleep(max(a.poll_interval, 2)); continue if not self.profitable(150_000, max_fee, reward): self.status('unprofitable_wait'); time.sleep(max(a.poll_interval, 2)); continue self.sample_spend() self.status('mining', challenge='0x' + challenge.hex()[:16]) solved_for = challenge abort = lambda: (self.watch.snap()[0] != solved_for or self.stop_requested() or not in_window(self.hours, self.tz) or self.watch.stale()) sender_b = bytes.fromhex(self.sender[2:]) res = self.solver.solve(challenge, sender_b, target, stats=self.stats, should_abort=abort, sleep_between=a.sleep_between, max_seconds=a.max_solve_seconds) if res is None: if self.watch.snap()[0] != solved_for: self.stats['stale_aborts'] += 1 log('stale_abort', challenge='0x' + solved_for.hex()[:16]) continue nonce_int, digest = res log('solution', nonce=str(nonce_int), digest='0x' + digest.hex(), challenge='0x' + solved_for.hex()) if not a.send: # dry-run: wait for the challenge to move (someone else mining) before solving again self.status('dry_run_solved') while (self.watch.snap()[0] == solved_for and not self.stop_requested()): time.sleep(a.poll_interval) continue outcome = None finished = False for attempt in range(5): try: outcome = self.submit(nonce_int, solved_for, reward) except MiningFinishedError: log('mining_finished', reason='MiningFinished_revert') finished = True break except SystemExit: raise except Exception as e: log('submit_error', error=redact(e)[:300]) time.sleep(1) # transient RPC trouble: no tight crash loop self.resync_nonce() outcome = 'error' break if outcome == 'same_block': # one solution per block: wait for the next block, then retry the SAME solution # as long as the challenge has not moved try: b0 = self.w3.eth.block_number except Exception: b0 = None t_w = time.time() while time.time() - t_w < 30 and not self.stop_requested(): try: if b0 is None or self.w3.eth.block_number > b0: break except Exception: pass time.sleep(max(a.poll_interval, 0.25)) if self.watch.snap()[0] != solved_for: self.stats['stale_discards'] += 1 log('stale_discard', reason='challenge_moved_during_same_block_wait') outcome = 'discard' break continue break if finished: self.status('finished'); break if outcome == 'stopped': log('stopped', reason='stop_file', path=a.stop_file) self.status('stopped'); break if outcome == 'accepted': if a.forward_to and self.stats['accepted'] % a.forward_every == 0: try: self.forward_rewards() except SystemExit: raise except Exception as e: log('forward_error', error=redact(e)[:300]) self.resync_nonce() # our own accepted solution changed the challenge; wait for the watcher to see the # new one so the next search never starts on the old challenge t_w = time.time() while self.watch.snap()[0] == solved_for and time.time() - t_w < 5: time.sleep(a.poll_interval / 4) self.watch.stopped.set() if a.send: self.reconcile_reorgs(force=True) log('exit', **self.stats) # ----------------------------------------------------------------------------- sandbox self-check def check_sandbox(keep_paths): """--require-sandbox: refuse to run unless the service sandbox really took effect. A systemd user unit whose mount namespace cannot be set up (e.g. AppArmor restrict_unprivileged_userns=1) starts anyway with ProtectHome/BindPaths silently ignored; this check turns that into exit 2. Asserts: NoNewPrivs and a seccomp filter are active, and along every path from $HOME to a kept path (working dir, keyfile) each directory lists only the next component of a kept path, i.e. nothing else in the home directory is visible.""" st = {} for line in open('/proc/self/status'): k, _, v = line.partition(':') st[k] = v.strip() problems = [] if st.get('NoNewPrivs') != '1': problems.append('NoNewPrivs is not set') if st.get('Seccomp') != '2': problems.append('no seccomp system call filter') home = os.path.realpath(os.path.expanduser('~')) allowed = {} # dir -> set of visible child names permitted for p in keep_paths: rp = os.path.abspath(p) rel = os.path.relpath(rp, home) if rel.startswith('..'): continue parts = rel.split(os.sep) cur = home for part in parts: allowed.setdefault(cur, set()).add(part) cur = os.path.join(cur, part) for d, names in sorted(allowed.items()): try: extra = sorted(set(os.listdir(d)) - names) except OSError as e: problems.append(f'cannot list {d}: {type(e).__name__}') continue if extra: problems.append(f'{d} shows {len(extra)} entries outside the sandbox (e.g. {extra[:3]})') if problems: fatal('--require-sandbox: the service sandbox is NOT in effect: ' + '; '.join(problems) + '. On a host that blocks unprivileged user namespaces a systemd --user unit silently skips ' 'ProtectHome/BindPaths; install gourdes-miner.service as a system unit (User=) instead.') return True # ----------------------------------------------------------------------------- CLI def _range_check(cast, lo=None, hi=None, what='value'): def f(s): try: v = cast(s) except ValueError: raise argparse.ArgumentTypeError(f'{what}: {s!r} is not a number') if isinstance(v, float) and not math.isfinite(v): # nan/inf pass every < and > test raise argparse.ArgumentTypeError(f'{what}: {s!r} is not a finite number') if lo is not None and v < lo: raise argparse.ArgumentTypeError(f'{what}: {v} is below the minimum {lo}') if hi is not None and v > hi: raise argparse.ArgumentTypeError(f'{what}: {v} is above the maximum {hi}') return v return f def build_parser(): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument('--rpc', required=True, help='HTTP JSON-RPC endpoint (never logged beyond scheme://host)') ap.add_argument('--config', required=True, help='JSON file pinning chain_id, contract, token, code hashes, abi_file, gas caps, ' 'spend limits, optional rpc2 (see config.example.json)') ap.add_argument('--sender', help='address to solve for (dry-run only; ignored with --send)') ap.add_argument('--send', action='store_true', help='actually submit transactions (default: dry-run)') ap.add_argument('--keyfile', help='path to a mode-600 file holding the hot key (hex); required with --send') ap.add_argument('--max-fee-gwei', type=_range_check(float, 0.01, 10_000, '--max-fee-gwei'), default=5.0, help='hard gas price ceiling (>= 0.01)') ap.add_argument('--priority-fee-gwei', type=_range_check(float, 0.0, 10_000, '--priority-fee-gwei'), default=0.01) ap.add_argument('--max-gas-reward-fraction', type=_range_check(float, 1e-6, 1.0, '--max-gas-reward-fraction'), default=0.25, help='skip when gas cost exceeds this fraction of the reward value') ap.add_argument('--price-wei-per-gourde', type=_range_check(int, 1, None, '--price-wei-per-gourde'), default=None, help='reward value: wei of native coin per 1e18 token units') ap.add_argument('--price-hook', default=None, help='module.path:function — f(reward_token_wei)->native_wei; overrides --price-wei-per-gourde') ap.add_argument('--no-profit-gate', action='store_true', help='explicitly allow --send with no price source (the min-profit rule is OFF)') ap.add_argument('--forward-to', default=None, help='owner address for reward forwarding (checksummed EOA)') ap.add_argument('--forward-every', type=_range_check(int, 1, None, '--forward-every'), default=10, help='forward after every N accepted solutions (>= 1)') ap.add_argument('--allow-contract-forward', action='store_true', help='allow --forward-to to be an address with code (normally refused)') ap.add_argument('--stop-file', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'STOP')) ap.add_argument('--status-file', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'status.line')) ap.add_argument('--hours', default='always', help="allowed local-time window in --tz, for example 'mon-fri:19:00-08:00,sat-sun:00:00-24:00'; " "default 'always' (no window)") ap.add_argument('--tz', default='America/New_York') ap.add_argument('--batch', type=_range_check(int, 1, 1 << 30, '--batch'), default=1 << 26, help='GPU batch size (power/intensity)') ap.add_argument('--sleep-between', type=_range_check(float, 0.0, 3600, '--sleep-between'), default=0.0, help='seconds to idle between GPU batches') ap.add_argument('--poll-interval', type=_range_check(float, 0.05, 60, '--poll-interval'), default=0.25, help='challenge poll period, seconds (0.05-60)') ap.add_argument('--replace-after', type=_range_check(float, 5.0, 3600, '--replace-after'), default=15.0, help='seconds before a pending tx is fee-bumped (>= 5)') ap.add_argument('--max-solve-seconds', type=_range_check(float, 0.1, None, '--max-solve-seconds'), default=None, help='give up on one search after this long') ap.add_argument('--gpu-uuid', default=None, help="full NVIDIA GPU uuid, or several separated by commas (never an index; never defaults " "to GPU 0). 'keep' inherits CUDA_VISIBLE_DEVICES, refused unless it holds exactly one " "full uuid. At least one of --gpu-uuid / --opencl-device / --cpu-threads is required") ap.add_argument('--opencl-device', action='append', default=[], help="PLATFORM:DEVICE of any OpenCL GPU (AMD, Intel, Apple, NVIDIA), as printed by " "`gminer.py --list`; repeat for several") ap.add_argument('--cpu-threads', type=_range_check(int, 0, 1024, '--cpu-threads'), default=0, help='also mine on this many CPU threads (lowest process priority); works on any computer') ap.add_argument('--require-sandbox', action='store_true', help='exit 2 unless the systemd sandbox is really active (home hidden except the working ' 'dir and keyfile, NoNewPrivileges, seccomp); the service unit passes this') return ap def main(): a = build_parser().parse_args() a.max_fee_wei = int(a.max_fee_gwei * 1e9) a.priority_fee_wei = int(a.priority_fee_gwei * 1e9) # Every local check below runs before the first RPC request. try: parse_hours(a.hours) # fail fast (and closed) on a bad spec except ValueError as e: fatal(f'--hours: {e}') try: ZoneInfo(a.tz) except Exception: fatal(f'--tz {a.tz!r} is not a known time zone') # The GPU is always named by its full uuid; an index ("0"), a list, or an unset variable # would let the driver pick a card the operator did not choose. a.devices = [] if a.gpu_uuid is None and not a.opencl_device and not a.cpu_threads: fatal('name at least one mining device: --gpu-uuid, --opencl-device or --cpu-threads') if a.gpu_uuid == 'keep': inherited = os.environ.get('CUDA_VISIBLE_DEVICES', '') if not GPU_UUID_RE.match(inherited): fatal("--gpu-uuid keep requires CUDA_VISIBLE_DEVICES to hold exactly one full GPU uuid " f"(GPU-xxxxxxxx-...), got {inherited!r}; refusing to default to GPU 0") a.devices.append(('nvidia', inherited)) elif a.gpu_uuid is not None: uuids = [u.strip() for u in a.gpu_uuid.split(',')] for u in uuids: if not GPU_UUID_RE.match(u): fatal(f'--gpu-uuid {u!r} is not a full GPU uuid (GPU-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx); ' 'indexes are refused so the client can never land on GPU 0 by accident') if len(set(uuids)) != len(uuids): fatal('--gpu-uuid names the same card twice') a.devices += [('nvidia', u) for u in uuids] for od in a.opencl_device: m = re.fullmatch(r'(\d{1,3}):(\d{1,3})', od.strip()) if not m: fatal(f'--opencl-device {od!r} must be PLATFORM:DEVICE as printed by gminer.py --list') spec = ('opencl', int(m.group(1)), int(m.group(2))) if spec in a.devices: fatal(f'--opencl-device {od} named twice') a.devices.append(spec) if a.cpu_threads: a.devices.append(('cpu', a.cpu_threads)) # One NVIDIA card and nothing else: the original single-process path, unchanged. a.single_gpu = len(a.devices) == 1 and a.devices[0][0] == 'nvidia' if a.single_gpu: os.environ['CUDA_VISIBLE_DEVICES'] = a.devices[0][1] if a.send and not a.keyfile: fatal('--send requires --keyfile') if a.forward_to and not a.send: fatal('--forward-to only makes sense with --send') if a.send and a.price_hook is None and a.price_wei_per_gourde is None and not a.no_profit_gate: fatal('--send has no price source (--price-wei-per-gourde / --price-hook); the min-profit ' 'gate would be silently off. Pass one, or --no-profit-gate to accept that explicitly.') if a.require_sandbox: check_sandbox([os.getcwd(), os.path.dirname(os.path.abspath(__file__))] + ([a.keyfile] if a.keyfile else [])) cfg = Config(a.config) try: Client(a, cfg).run() except SystemExit: raise except Exception as e: tb = redact(''.join(traceback.format_exception(type(e), e, e.__traceback__))) print(tb, file=sys.stderr, flush=True) log('fatal_error', error=redact(repr(e))[:400]) sys.exit(1) if __name__ == '__main__': main()