"""Bound chain QWork to committed thinking tokens. Does not send anything. The runtime is responsible for checking the source node, creating the complete block template, and supplying an authentic committed-token event. Neither prompt text nor a model-produced receipt grants permission. Submit/relay and independent verification are deliberately outside the forward pass. """ from dataclasses import dataclass from threading import Lock from typing import Callable MAX_NONCE = (1 << 32) - 1 MAX_WORK_PER_LEASE = 4096 def compact_target(bits: int) -> int: """Bitcoin compact positive target, before checking the network's PoW limit.""" size = bits >> 24 mantissa = bits & 0x007fffff if bits & 0x00800000 or not mantissa: raise ValueError("Negative or zero target") target = (mantissa >> (8 * (3 - size)) if size <= 3 else mantissa << (8 * (size - 3))) if not 0 < target < (1 << 256): raise ValueError("Zero or overflowing target") return target @dataclass(frozen=True) class WorkJob: job_id: str prefix: bytes tip: bytes pow_limit: int def __post_init__(self): if not isinstance(self.job_id, str) or not self.job_id or len(self.job_id) > 128: raise ValueError("Invalid job id") if type(self.prefix) is not bytes or len(self.prefix) != 76: raise ValueError("Need exact unsigned header prefix, 76 bytes") if type(self.tip) is not bytes or len(self.tip) != 32 or self.prefix[4:36] != self.tip: raise ValueError("Job and parent's serialized block ID disagree") if type(self.pow_limit) is not int or not 0 < self.pow_limit < (1 << 256): raise ValueError("Need the validated network PoW limit") if self.target > self.pow_limit: raise ValueError("Block target exceeds the network limit") @property def target(self) -> int: return compact_target(int.from_bytes(self.prefix[72:76], "little")) @dataclass(frozen=True) class WorkResult: job_id: str tip: bytes nonce: int header: bytes digest: bytes meets_target: bool class CommittedMining: """One lease per sequence; a single circuit call per eligible token. Host grants a bounded nonce range, and may renew with a fresh range while the long-running session remains authorized. The lease never owns keys or submits blocks. A tip change, stop or replacement during a circuit call discards the pending result. An exhausted or winning lease disarms. """ def __init__(self): self._lock = Lock() self._epoch = 0 self._job = None self._next = self._end = 0 self._last_token = -1 self._inflight = False self._ranges: dict[bytes, list[tuple[int,int]]] = {} def begin(self, job: WorkJob, *, start_nonce: int, attempts: int) -> None: if not isinstance(job, WorkJob): raise TypeError("Host must supply a validated job") if (type(start_nonce) is not int or type(attempts) is not int or not 0 <= start_nonce <= MAX_NONCE or not 1 <= attempts <= MAX_WORK_PER_LEASE or start_nonce + attempts > MAX_NONCE + 1): raise ValueError("Invalid bounded nonce range") end = start_nonce + attempts with self._lock: old = self._ranges.setdefault(job.prefix, []) if any(start_nonce < b and a < end for a,b in old): raise ValueError("Repeated work range for this header") old.append((start_nonce,end)) self._epoch += 1 self._job, self._next, self._end = job, start_nonce, end def stop(self): with self._lock: self._epoch += 1 self._job = None @property def active(self): with self._lock: return self._job is not None def token(self, sequence: int, *, thinking: bool, live_tip: bytes, digest_header: Callable[[bytes], bytes]) -> WorkResult | None: if type(sequence) is not int or sequence < 0: raise ValueError("Invalid committed-token sequence") with self._lock: if sequence <= self._last_token: return None self._last_token = sequence job = self._job if job is None: return None if live_tip != job.tip: self._epoch += 1 self._job = None return None if not thinking or self._inflight: return None nonce, epoch = self._next, self._epoch self._next += 1 self._inflight = True if self._next >= self._end: self._job = None header = job.prefix + nonce.to_bytes(4, "little") digest = None try: digest = digest_header(header) if type(digest) is not bytes or len(digest) != 32: raise ValueError("Circuit digest must be exactly 32 bytes") finally: with self._lock: self._inflight = False current = self._epoch == epoch meets = current and type(digest) is bytes and len(digest) == 32 and int.from_bytes(digest, "little") <= job.target if meets: self._job = None if not current: return None return WorkResult(job.job_id, job.tip, nonce, header, digest, meets) def mlx_digest_adapter(circuit): """Call current Inkling's exact 80-byte MLX circuit; expose raw digest bytes.""" import mlx.core as mx import numpy as np def evaluate(header: bytes) -> bytes: if type(header) is not bytes or len(header) != 80: raise ValueError("Need a serialized block header") return bytes.fromhex(circuit.digest_hex(mx.array(np.frombuffer(header, dtype=np.uint8)))) return evaluate