"""Multi-device solver for GourdesMiner: every named GPU and any number of CPU threads search the same puzzle at once; the first valid nonce wins and the others drop the job. Same interface as gminer.Solver (solve(challenge, sender, target, max_seconds, stats, should_abort, sleep_between) -> (nonce_int, digest) | None), so run.py's control logic does not change. Devices (each runs in its own process, started with the 'spawn' method so a GPU process only ever sees the one card it was given): ('nvidia', uuid) one NVIDIA card, pinned by full uuid and proven by PCI bus id ('opencl', platform, device) any OpenCL device (AMD, Intel, Apple, NVIDIA) from `gminer.py --list` ('cpu', threads) CPU threads using keccak from pycryptodome; runs at the lowest priority A worker exits on its own within about a second when the process that started it dies, so a killed client never leaves miners running. Every worker draws its own random nonce prefix, so two workers never search the same nonces. A result is re-checked here against the target before it is returned. """ import multiprocessing as mp import os import queue import struct import time from Crypto.Hash import keccak def k256(b): return keccak.new(digest_bits=256, data=b).digest() class _Counter(dict): """dict that also adds every growth of 'hashes' to a shared counter (gminer.Solver writes stats['hashes'] = stats.get('hashes', 0) + batch after each batch).""" def __init__(self, shared): super().__init__() self.shared = shared def __setitem__(self, k, v): if k == 'hashes': delta = v - self.get('hashes', 0) if delta > 0: with self.shared.get_lock(): self.shared.value += delta super().__setitem__(k, v) def _orphaned(parent): """True once the process that started this worker is gone (killed, crashed, OOM): a worker must never keep mining on its own. Checked between batches and while waiting for work.""" return os.getppid() != parent def _next_job(jobs, parent): """Blocks for the next job, but returns None as soon as the parent process is gone.""" while True: try: return jobs.get(timeout=1.0) except queue.Empty: if _orphaned(parent): return None def _gpu_worker(spec, batch, jobs, results, current, hashes, ready, parent): kind = spec[0] if kind == 'nvidia': os.environ['CUDA_VISIBLE_DEVICES'] = spec[1] import gminer # imported after CUDA_VISIBLE_DEVICES is final for this process try: if kind == 'nvidia': s = gminer.Solver(batch=batch) info = s.verify_uuid(spec[1]) else: s = gminer.Solver(batch=batch, opencl_device=(spec[1], spec[2])) info = {'opencl_device': f'{spec[1]}:{spec[2]}'} ready.put(('ok', spec, s.dev.name.strip(), info)) except Exception as e: # reported to the parent, which refuses to start ready.put(('err', spec, f'{type(e).__name__}: {e}'[:400], None)) return stats = _Counter(hashes) while True: job = _next_job(jobs, parent) if job is None: return jid, challenge, sender, target, sleep_between = job r = s.solve(challenge, sender, target, stats=stats, should_abort=lambda: current.value != jid or _orphaned(parent), sleep_between=sleep_between) if _orphaned(parent): return if r is not None: results.put((jid, r[0], r[1])) def _cpu_worker(index, jobs, results, current, hashes, ready, parent): try: os.nice(19) # CPU mining never competes with anything else on the machine except Exception: pass ready.put(('ok', ('cpu', index), 'CPU thread', {'cpu_thread': index})) while True: job = _next_job(jobs, parent) if job is None: return jid, challenge, sender, target, sleep_between = job prefix = os.urandom(24) head = challenge + sender + prefix i = 0 found = None while current.value == jid: if _orphaned(parent): return for _ in range(4096): nonce = head[52:] + struct.pack('>Q', i) i += 1 d = keccak.new(digest_bits=256, data=head + nonce[24:]).digest() if int.from_bytes(d, 'big') <= target: found = (int.from_bytes(nonce, 'big'), d) break with hashes.get_lock(): hashes.value += 4096 if found: results.put((jid, found[0], found[1])) break if sleep_between: time.sleep(sleep_between) class MultiSolver: def __init__(self, devices, batch=1 << 26, start_timeout=120): if not devices: raise RuntimeError('no mining device named') ctx = mp.get_context('spawn') self.current = ctx.Value('q', 0) self.hashes = ctx.Value('q', 0) self.results = ctx.Queue() ready = ctx.Queue() self.workers = [] # (process, job queue) expected = 0 for spec in devices: if spec[0] == 'cpu': for t in range(int(spec[1])): q = ctx.Queue() p = ctx.Process(target=_cpu_worker, args=(t, q, self.results, self.current, self.hashes, ready, os.getpid()), daemon=True) p.start(); self.workers.append((p, q)); expected += 1 elif spec[0] in ('nvidia', 'opencl'): q = ctx.Queue() p = ctx.Process(target=_gpu_worker, args=(spec, batch, q, self.results, self.current, self.hashes, ready, os.getpid()), daemon=True) p.start(); self.workers.append((p, q)); expected += 1 else: raise RuntimeError(f'unknown device kind {spec[0]!r}') self.devices = [] errors = [] t_end = time.time() + start_timeout while len(self.devices) + len(errors) < expected: try: st, spec, name, info = ready.get(timeout=max(0.1, t_end - time.time())) except queue.Empty: errors.append('a device did not report within the start timeout') break if st == 'ok': self.devices.append({'device': ':'.join(str(x) for x in spec), 'name': name, **(info or {})}) else: errors.append(f"{':'.join(str(x) for x in spec)}: {name}") if errors: self.close() raise RuntimeError('; '.join(errors)) self.jid = 0 class _Dev: pass self.dev = _Dev() gpus = sum(1 for d in devices if d[0] != 'cpu') cpus = sum(int(d[1]) for d in devices if d[0] == 'cpu') self.dev.name = f'{gpus} GPU(s) + {cpus} CPU thread(s)' def solve(self, challenge, sender, target, max_seconds=None, stats=None, should_abort=None, sleep_between=0.0): assert len(challenge) == 32 and len(sender) == 20 self.jid += 1 jid = self.jid with self.current.get_lock(): self.current.value = jid for p, q in self.workers: q.put((jid, challenge, sender, target, sleep_between)) t0 = time.time() last = self.hashes.value try: while True: try: rjid, nonce, digest = self.results.get(timeout=0.2) except queue.Empty: rjid = None now = self.hashes.value if stats is not None: stats['hashes'] = stats.get('hashes', 0) + (now - last) last = now if rjid == jid: nb = nonce.to_bytes(32, 'big') d = k256(challenge + sender + nb) if d == digest and int.from_bytes(d, 'big') <= target: return nonce, d if not all(p.is_alive() for p, _ in self.workers): raise RuntimeError('a mining worker process died') if max_seconds and time.time() - t0 > max_seconds: return None if should_abort and should_abort(): return None finally: with self.current.get_lock(): # every worker drops this job self.current.value = -jid def close(self): for p, q in self.workers: try: q.put(None) except Exception: pass with self.current.get_lock(): self.current.value = -1 for p, _ in self.workers: p.join(timeout=5) if p.is_alive(): p.terminate()