#!/usr/bin/env python3 """GPU solver for GourdesMiner: finds nonce with keccak256(challenge || sender || nonce) <= target. Prints solutions; never sends a transaction. Pick the card with CUDA_VISIBLE_DEVICES=.""" import argparse, os, struct, sys, time import numpy as np, pyopencl as cl from Crypto.Hash import keccak MAX_HITS = 16 # kernel records up to this many candidates per batch (fixes the first-hit-per-batch tie) def k256(b): return keccak.new(digest_bits=256, data=b).digest() def parse_hex(s: str, length: int | None = None) -> bytes: """Hex string with or without 0x/0X prefix.""" s = s.strip() if s[:2] in ('0x', '0X'): s = s[2:] b = bytes.fromhex(s) if length is not None and len(b) != length: raise ValueError(f'expected {length} bytes, got {len(b)}') return b def list_opencl_devices(): """[(platform_index, device_index, platform_name, device_name, device_type)] for every OpenCL device.""" out = [] for pi, p in enumerate(cl.get_platforms()): try: devs = p.get_devices() except Exception: continue for di, d in enumerate(devs): kind = 'GPU' if d.type & cl.device_type.GPU else 'CPU' if d.type & cl.device_type.CPU else 'OTHER' out.append((pi, di, p.name.strip(), d.name.strip(), kind)) return out class Solver: def __init__(self, batch=1 << 26, opencl_device=None): """opencl_device=None: exactly one visible NVIDIA device (pinned by CUDA_VISIBLE_DEVICES). opencl_device=(platform_index, device_index): that exact OpenCL device, any vendor.""" if opencl_device is not None: pi, di = opencl_device plats = cl.get_platforms() if not 0 <= pi < len(plats): raise RuntimeError(f'no OpenCL platform {pi} (found {len(plats)})') devs = plats[pi].get_devices() if not 0 <= di < len(devs): raise RuntimeError(f'OpenCL platform {pi} has no device {di} (found {len(devs)})') devs = [devs[di]] else: devs = [d for p in cl.get_platforms() if 'NVIDIA' in p.name for d in p.get_devices()] if len(devs) != 1: # never pick "the first one": with CUDA_VISIBLE_DEVICES unset that is GPU 0 raise RuntimeError(f'expected exactly 1 visible NVIDIA OpenCL device, found {len(devs)}; ' 'set CUDA_VISIBLE_DEVICES to one GPU uuid') self.dev = devs[0] self.ctx = cl.Context([self.dev]); self.q = cl.CommandQueue(self.ctx) src = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keccak.cl')).read() self.k = cl.Program(self.ctx, src).build().search self.batch = batch mf = cl.mem_flags self.found = cl.Buffer(self.ctx, mf.READ_WRITE, 4) self.out = cl.Buffer(self.ctx, mf.READ_WRITE, 8 * MAX_HITS) def verify_uuid(self, uuid): """Proves the opened OpenCL device is the GPU named by uuid: its PCI bus/slot (NVIDIA OpenCL extension cl_nv_device_attribute_query) must equal what nvidia-smi reports for that uuid. Returns a dict for the log; raises on mismatch or when it cannot be proven.""" import subprocess bus = self.dev.get_info(0x4008) # CL_DEVICE_PCI_BUS_ID_NV slot = self.dev.get_info(0x4009) # CL_DEVICE_PCI_SLOT_ID_NV out = subprocess.run(['nvidia-smi', '--query-gpu=uuid,pci.bus_id', '--format=csv,noheader', '-i', uuid], capture_output=True, text=True, timeout=20) if out.returncode != 0: raise RuntimeError(f'nvidia-smi does not know {uuid}: {out.stderr.strip()[:200]}') u, busid = [x.strip() for x in out.stdout.strip().splitlines()[0].split(',')] _dom, b, ds = busid.split(':') want_bus, want_slot = int(b, 16), int(ds.split('.')[0], 16) if u != uuid or (bus, slot) != (want_bus, want_slot): raise RuntimeError(f'OpenCL device is PCI {bus:02x}:{slot:02x}, but {uuid} is {busid}') return {'uuid': uuid, 'pci_bus_id': busid} def solve(self, challenge: bytes, sender: bytes, target: int, max_seconds=None, stats=None, should_abort=None, sleep_between=0.0): """Returns (nonce_int, digest), or None on timeout / abort. should_abort: 0-arg callable checked between batches (challenge changed, stop file, ...). sleep_between: seconds to sleep after each batch (power/intensity throttle).""" assert len(challenge) == 32 and len(sender) == 20 prefix = os.urandom(12); suffix = os.urandom(12) # nonce = prefix | 8 searched bytes | suffix msg = bytearray(challenge + sender + prefix + b'\0' * 8 + suffix + b'\x01' + b'\0' * 3) fixed = np.frombuffer(bytes(msg), dtype='> 192 base = 0; t0 = time.time() zero = np.zeros(1, dtype=np.uint32); res = np.zeros(MAX_HITS, dtype=np.uint64); cnt = np.zeros(1, dtype=np.uint32) while True: cl.enqueue_copy(self.q, self.found, zero) self.k(self.q, (self.batch,), None, fbuf, np.uint64(base), np.uint64(thi), self.found, self.out) cl.enqueue_copy(self.q, cnt, self.found).wait() if stats is not None: stats['hashes'] = stats.get('hashes', 0) + self.batch if cnt[0]: cl.enqueue_copy(self.q, res, self.out).wait() for i in range(min(int(cnt[0]), MAX_HITS)): # check every hit, not only the first nonce = prefix + struct.pack(' max_seconds: return None if should_abort and should_abort(): return None if sleep_between: # sliced, so a stop/abort is seen within 0.5 s of the throttle sleep t_end = time.time() + sleep_between while time.time() < t_end: time.sleep(min(0.5, max(0.0, t_end - time.time()))) if should_abort and should_abort(): return None if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument('--bench', type=float, help='seconds to benchmark') ap.add_argument('--challenge'); ap.add_argument('--sender'); ap.add_argument('--target') ap.add_argument('--max-seconds', type=float, help='give up after this long (default: run until solved)') ap.add_argument('--list', action='store_true', help='list every OpenCL device (platform:device) and exit') ap.add_argument('--opencl-device', help='PLATFORM:DEVICE from --list (any vendor); default: one NVIDIA card ' 'pinned by CUDA_VISIBLE_DEVICES') a = ap.parse_args() if a.list: for pi, di, pn, dn, dt in list_opencl_devices(): print(f'{pi}:{di} {dt:<6} {dn} [{pn}]') sys.exit(0) s = Solver(opencl_device=tuple(int(x) for x in a.opencl_device.split(':')) if a.opencl_device else None) print('device', s.dev.name, file=sys.stderr) if a.bench: st = {}; t0 = time.time() s.solve(os.urandom(32), os.urandom(20), 0, max_seconds=a.bench, stats=st) dt = time.time() - t0 print(f"{st['hashes']/dt/1e6:.0f} MH/s over {dt:.1f}s") else: ch = parse_hex(a.challenge, 32); sd = parse_hex(a.sender, 20) t0 = time.time() r = s.solve(ch, sd, int(a.target, 0), max_seconds=a.max_seconds) if r is None: print('timeout', file=sys.stderr); sys.exit(2) n, d = r print(f"nonce {n}\ndigest 0x{d.hex()}\nseconds {time.time()-t0:.2f}")