Inkling-2-Mini-QWork-IQ4 / v1 /mac_hf_node.py
staccs's picture
Add Apple Developer ID signed & notarized Apple Silicon macOS full release (ASSEMBLY e36c45486600, Apple Notary d98cc31f)
707fc65 verified
Raw History Blame Contribute Delete
8.71 kB
"""Explicit offline smoke for the notarized Qwencoin child inside an HF snapshot."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import platform
import socket
import stat
import struct
import subprocess
import tempfile
import time
from mac_official_release_pins import QWENCOIN, QWENCOIN_MEMBERS
from node_rpc import QwencoinNode, NodeError
GENESIS = "51ebb1f392844e411a0c52ba535773b0cb4a04cac6aede0d822249d5c6ce3cf5"
_MACH_ARM = 0x100000c
_LOAD_DYLIBS = {0xc, 0x18, 0x80000018, 0x8000001f, 0x20, 0x80000023}
_SYSTEM_PREFIX = ("/usr/lib/", "/System/Library/Frameworks/")
def macho_policy(f, expected_type, allowed_min=(0x000d0000,)):
header = f.read(32)
if len(header) != 32:
raise ValueError("Truncated Mach-O header")
magic, cpu, _, f_type, n, sz, _, _ = struct.unpack("<8I", header)
if (magic, cpu, f_type) != (0xfeedfacf, _MACH_ARM, expected_type) or not 0 < n <= 256 or not n * 8 <= sz <= 65536:
raise ValueError("Unexpected native arm64 Mach-O header")
entries = f.read(sz)
if len(entries) != sz:
raise ValueError("Truncated Mach-O load table")
pos = 0
minimum = None
deps = []
for _ in range(n):
if pos + 8 > sz:
raise ValueError("Truncated Mach-O command")
cmd, count = struct.unpack_from("<II", entries, pos)
if count < 8 or count % 8 or pos + count > sz:
raise ValueError("Invalid Mach-O command")
if cmd in _LOAD_DYLIBS or cmd in (0xe, 0x8000001c, 0x27):
if count < 16:
raise ValueError("Invalid Mach-O path")
offset = struct.unpack_from("<I", entries, pos + 8)[0]
raw = entries[pos + offset:pos + count] if 12 <= offset < count else b""
if b"\0" not in raw:
raise ValueError("Invalid Mach-O path")
p = raw.split(b"\0", 1)[0].decode("ascii")
if (cmd == 0xe and p != "/usr/lib/dyld") or cmd in (0x8000001c, 0x27):
raise ValueError("Unexpected dynamic loader path, rpath or environment")
if cmd in _LOAD_DYLIBS:
parts = p.split("/")
if not p.startswith(_SYSTEM_PREFIX) or any(x in ("", ".", "..") for x in parts[1:]):
raise ValueError("Non-system Mach-O dependency")
deps.append(p)
if cmd == 0x32:
if count < 24 or minimum is not None:
raise ValueError("Invalid Mach-O deployment command")
target, minimum, _ = struct.unpack_from("<III", entries, pos + 8)
if target != 1:
raise ValueError("Non-macOS Mach-O platform")
pos += count
if pos != sz or minimum not in allowed_min:
raise ValueError("Unexpected load table or release deployment target")
major, minor = minimum >> 16, (minimum >> 8) & 0xff
return {"minimum_macos": f"{major}.{minor}", "system_dependencies": deps, "rpath": "none"}
def inspect_native(native_root):
root = Path(native_root).resolve(strict=True)
reports = {}
for rel, (size, digest) in QWENCOIN_MEMBERS.items():
member = root / "native/qwencoin" / rel
if member.resolve(strict=True) != member or not member.is_file():
raise ValueError("Native member must be materialized, not a link: " + rel)
with member.open("rb") as f:
info = os.fstat(f.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_size != size:
raise ValueError("Incorrect native file shape: " + rel)
if hashlib.file_digest(f, "sha256").hexdigest() != digest:
raise ValueError("Incorrect official native SHA-256: " + rel)
f.seek(0)
exe = rel.startswith("libexec/")
reports[rel] = {
"sha256": digest,
"executable_bit": bool(info.st_mode & stat.S_IXUSR),
**macho_policy(f, 2 if exe else 6),
}
return {
"release": QWENCOIN["release"],
"download_sha_verified_members": reports,
"executed": False,
"notarized": True,
}
def command(exe, scratch, port, table=None):
argv = [
str(exe), "-noconf", "-nosettings", "-chain=main", "-disablewallet=1",
"-server=1", "-networkactive=0", "-connect=0", "-listen=0", "-listenonion=0",
"-discover=0", "-dns=0", "-dnsseed=0", "-fixedseeds=0", "-natpmp=0",
"-i2pacceptincoming=0", "-blocksonly=1", "-persistmempool=0",
"-rpcbind=127.0.0.1", "-rpcallowip=127.0.0.1", f"-rpcport={port}",
f"-datadir={scratch}", f"-rpccookiefile={scratch / 'cookie'}", "-rpccookieperms=owner",
]
if table is not None:
argv.append(f"-qwork={table}")
return argv
def _stop(proc):
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=8)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=3)
def _wait_ready(proc, cookie, port, timeout):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if proc.poll() is not None:
raise RuntimeError(f"Native child exited before readiness (status {proc.returncode})")
try:
fd = os.open(cookie, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
with os.fdopen(fd, "rb") as f:
info = os.fstat(f.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_mode & 0o077:
raise ValueError("Unsafe RPC cookie ownership or mode")
value = f.read(1025).decode("ascii").rstrip("\r\n")
rpc = QwencoinNode(port, value, timeout=2.0)
s = rpc.sync_status()
except (FileNotFoundError, NodeError):
time.sleep(0.12)
continue
if s.chain != "main" or s.peers or s.height != 0 or s.headers != 0 or s.tip != GENESIS:
raise ValueError("Expected fresh main chain genesis and no peers")
return {
"chain": s.chain, "height": s.height, "genesis": s.tip, "peers": s.peers,
"mainnet_connected": False, "mining": False, "wallet": False,
}
raise TimeoutError("Owned node did not become ready")
def node_smoke(native_root, *, table=None, spawn=subprocess.Popen, ready=_wait_ready):
if (platform.system(), platform.machine()) != ("Darwin", "arm64"):
raise ValueError("Requires native Apple Silicon macOS")
receipt = inspect_native(native_root)
if not receipt["download_sha_verified_members"]["libexec/qwencoind"]["executable_bit"]:
raise PermissionError("Native binary is not executable; refusing to modify permissions")
root = Path(native_root).resolve(strict=True)
source = root / "native/qwencoin/libexec/qwencoind"
cli = root / "native/qwencoin/libexec/qwencoin-cli"
with tempfile.TemporaryDirectory(prefix="inkling-qwen-offline-") as d:
scratch = Path(d)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as reserved:
reserved.bind(("127.0.0.1", 0))
port = reserved.getsockname()[1]
env = {"HOME": str(scratch), "TMPDIR": str(scratch), "PATH": "/usr/bin:/bin", "LANG": "C"}
with (scratch / "process.log").open("xb") as log:
proc = spawn(
command(source, scratch, port, table=table),
stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT,
env=env, cwd=scratch,
)
try:
res = ready(proc, scratch / "cookie", port, 30)
# Also verify qwencoin-cli against this exact offline daemon
cli_out = subprocess.check_output(
[
str(cli), "-noconf", "-rpcconnect=127.0.0.1", f"-rpcport={port}",
f"-rpccookiefile={scratch / 'cookie'}", "getblockhash", "0",
],
env=env, cwd=scratch, text=True, timeout=10,
).strip()
if cli_out != GENESIS:
raise RuntimeError(f"qwencoin-cli genesis mismatch: {cli_out}")
res["cli_verified_genesis"] = cli_out
return res
finally:
_stop(proc)
if __name__ == "__main__":
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--native-root", type=Path, required=True)
p.add_argument("--table", type=Path)
p.add_argument("--node-smoke", action="store_true")
args = p.parse_args()
print(json.dumps(node_smoke(args.native_root, table=args.table) if args.node_smoke else inspect_native(args.native_root), indent=2))