#!/usr/bin/env python3 # 天財運算節點(compute node)——任何機上盒或會員自備 AI 伺服器皆可跑 # 用法:python3 compute_node.py <中心URL> <會員編號> <驗證碼> [--once|--exit-when-idle] # 例:python3 compute_node.py https://xxx.trycloudflare.com TCD088815A 4463 --once # 会员中心「🖥 運算互助」按「拿執行檔」存檔後在盒子終端機跑同一條指令即可 # 只吃 CPU、零依賴、純 stdlib;領單→本地算→交件;中心會重算驗證,灌單無效。 import sys, os, json, time, math, urllib.request, urllib.error def log(m): print(time.strftime('%H:%M:%S'), m, flush=True) def main(): if len(sys.argv) < 4: print(__doc__); sys.exit(1) B, MID, SEC = sys.argv[1].rstrip('/'), sys.argv[2], sys.argv[3] FLAGS = sys.argv[4:] ONCE = '--once' in FLAGS EXIT_IDLE = '--exit-when-idle' in FLAGS POLL = 15 def api(path, body=None, tok=None): req = urllib.request.Request(B + path, data=json.dumps(body).encode() if body is not None else None, headers={'Content-Type': 'application/json', **({'X-Session': tok} if tok else {})}) try: with urllib.request.urlopen(req, timeout=60) as r: return json.loads(r.read()) except urllib.error.HTTPError as e: try: return json.loads(e.read() or b'{}') except Exception: return {'ok': False, 'error': 'HTTP %s' % e.code} except Exception as e: return {'ok': False, 'error': str(e)[:80]} r = api('/api/video/login', {'id': MID, 'secret': SEC}) if not r.get('ok'): log('登入失敗:' + str(r.get('error'))); sys.exit(1) TOK = r['token'] log('已登入(%s)—開始輪詢工作單…' % MID) idle_rounds = 0 while True: u = api('/api/compute/claim', {}, TOK) unit = u.get('unit') if u.get('ok') else None if not unit: idle_rounds += 1 if ONCE or (EXIT_IDLE and idle_rounds >= 3): log('目前無可領工作單,離開。'); break time.sleep(POLL); continue idle_rounds = 0 # 本地重算沙盒(與中心同規則:白名單、禁 **) import ast FUNCS = {'sqrt': math.sqrt, 'sin': math.sin, 'cos': math.cos, 'tan': math.tan, 'exp': math.exp, 'log': math.log, 'log10': math.log10, 'abs': abs, 'floor': math.floor, 'ceil': math.ceil, 'pow': math.pow, 'atan': math.atan, 'asin': math.asin, 'sinh': math.sinh, 'cosh': math.cosh, 'tanh': math.tanh} CONSTS = {'pi': math.pi, 'e': math.e, 'tau': math.tau, 'inf': math.inf} try: tree = ast.parse(unit['expr'], mode='eval') pvar = unit.get('pvar') or 'x' env = {} def ev(nd): t = type(nd) if t is ast.Constant: return nd.value if t is ast.Name: return FUNCS[nd.id] if nd.id in FUNCS else CONSTS.get(nd.id, env[nd.id]) if t is ast.BinOp: a, b = ev(nd.left), ev(nd.right) op = type(nd.op) if op is ast.Add: return a + b if op is ast.Sub: return a - b if op is ast.Mult: return a * b if op is ast.Div: return a / b if op is ast.FloorDiv: return a // b if op is ast.Mod: return a % b raise ValueError('op') if t is ast.UnaryOp: a = ev(nd.operand) return -a if isinstance(nd.op, ast.USub) else +a if t is ast.Call: return FUNCS[nd.func.id](*[ev(a) for a in nd.args]) raise ValueError('node') vals = [] k = 0 lo, hi, step = unit['lo'], unit['hi'], unit['step'] while lo + k * step < hi - step * 1e-9: env[pvar] = lo + k * step try: v = ev(tree.body) except ZeroDivisionError: v = float('inf') except (ValueError, OverflowError): v = float('nan') if not (-1e18 < v < 1e18): v = math.copysign(1e18, v) if v else 0.0 vals.append(round(float(v), 10)) k += 1 digest = __import__('hashlib').sha256(','.join(repr(v) for v in vals).encode()).hexdigest() res = api('/api/compute/result', {'uid': unit['uid'], 'n': len(vals), 'agg': sum(vals), 'digest': digest}, TOK) if res.get('ok'): extra = (';中心已記您應付 NT$%s' % res['owed_to_node']) if res.get('obligation') else '' log('✓ %s(%d 點)完成%s' % (unit['uid'], len(vals), extra)) else: log('✗ 交件被拒:' + str(res.get('error'))) except Exception as e: log('算這單出錯:' + str(e)[:80]) if ONCE: break if __name__ == '__main__': main()