#!/usr/bin/env python3 # Copyright © Albert Lane. All Rights Reserved. # Proprietary and Confidential — Albert Lane Proprietary Software License. # Unauthorized use, copying, modification, or distribution is prohibited. # License inquiries: https://albertlane.net """t1237 end-to-end tests for the 2-of-2 Sovereign Binding. All keys here are THROWAWAY, TEST ONLY, generated per run.""" import hashlib import http.server import json import os import subprocess import sys import tempfile import threading HERE = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.dirname(HERE) sys.path.insert(0, os.path.join(ROOT, "cosigner")) sys.path.insert(0, os.path.join(ROOT, "tools")) from eth_account import Account # noqa: E402 import lane_digest as D # noqa: E402 import grok_agent_middleware as M # noqa: E402 import make_packet as MP # noqa: E402 HOST = os.path.join(ROOT, "host", "build", "lane_host") W = tempfile.mkdtemp(prefix="t1237-") RESULTS = [] # ---- TEST ONLY throwaway keys (never used outside this test run) ---- ALBERT_T = Account.create() # stands in for Albert's wallet in tests only ROBOT_T = Account.create() # stands in for the Robot key in tests only MALLORY_T = Account.create() # attacker key json.dump({"WARNING": "TEST ONLY throwaway keys, generated for this run", "albert_test": ALBERT_T.address, "robot_test": ROBOT_T.address, "mallory_test": MALLORY_T.address}, open(os.path.join(W, "keys.TEST_ONLY.json"), "w"), indent=1) CONF = os.path.join(W, "lane_sentry.TEST_ONLY.conf") open(CONF, "w").write(f"# TEST ONLY\nTEST_ONLY=1\nALBERT_ADDRESS={ALBERT_T.address}\nROBOT_ADDRESS={ROBOT_T.address}\n") CHAIN = os.path.join(W, "aros_chain.txt") def check(name, cond, detail=""): RESULTS.append((name, bool(cond))) print(f"[{'PASS' if cond else 'FAIL'}] {name}{(' — ' + detail) if detail else ''}") def packet(pid, code="MEM_WRITE", operands=({"ref": 7}, {"int": 42}), payload=b""): return MP.build({"packet_id": pid, "timestamp": 1794268800 + pid, "code": code, "operands": list(operands), "payload_hex": payload.hex()}) def human_sign(p, key=ALBERT_T.key): p.human_sig = D.personal_sign(MP.human_digest(p), key) return p def robot_sign(p, key=ROBOT_T.key): p.robot_sig = D.personal_sign(D.h_robot(p.human_sig, D.instr_bytes(p.instr)), key) return p def run_host(*pkts, conf=CONF): files = [] for i, p in enumerate(pkts): f = os.path.join(W, f"pkt-{p.packet_id}-{i}-{len(os.listdir(W))}.bin") open(f, "wb").write(p.SerializeToString()) files.append(f) r = subprocess.run([HOST, "--config", conf, "--chain", CHAIN, *files], capture_output=True, text=True, timeout=30) return r.returncode, r.stdout + r.stderr def last_chain(): return open(CHAIN).read().strip().splitlines()[-1] if os.path.exists(CHAIN) else "" def expect_orphan(name, p, why): rc, out = run_host(p) ln = last_chain() check(name, rc == 1 and ln.startswith(f"ORPHAN_BLOCK | Packet ID: {p.packet_id} |") and why in ln, f"rc={rc} tombstone: {ln[:150]}") # ---------------- C++ Sovereign Sentry ---------------- rc, out = run_host(robot_sign(human_sign(packet(1)))) check("valid 2-of-2 MEM_WRITE executes", rc == 0 and "2-of-2 Consensus Verified" in out and last_chain().startswith("EXEC_BLOCK | Packet ID: 1 |"), out.strip().splitlines()[-1]) seq = [robot_sign(human_sign(packet(2, "MEM_WRITE", ({"ref": 9}, {"int": 5})))), robot_sign(human_sign(packet(3, "COMPUTE", ({"str": "mul"}, {"ref": 10}, {"int": 6}, {"int": 7})))), robot_sign(human_sign(packet(4, "MEM_READ", ({"ref": 10},)))), robot_sign(human_sign(packet(5, "IO_SINK", ({"str": "Albert and Robot Don't Fuck Around"},))))] rc, out = run_host(*seq) check("valid 4-packet program (write, compute 6*7, read, sink)", rc == 0 and "=42" in out and out.count("[EXEC]") == 4, " | ".join(l for l in out.splitlines() if l.startswith("[EXEC]"))) p = human_sign(packet(10)); expect_orphan("missing robot_sig -> ORPHAN", p, "missing signature: robot") p = packet(11); p.robot_sig = b"\x01" * 65; expect_orphan("missing human_sig -> ORPHAN", p, "missing signature: human") expect_orphan("wrong human signer (attacker key) -> ORPHAN", robot_sign(human_sign(packet(12), MALLORY_T.key)), "human=wrong signer " + MALLORY_T.address.lower()) expect_orphan("wrong robot signer (attacker key) -> ORPHAN", robot_sign(human_sign(packet(13)), MALLORY_T.key), "robot=wrong signer " + MALLORY_T.address.lower()) expect_orphan("robot slot signed by Albert's key (one key cannot be both) -> ORPHAN", robot_sign(human_sign(packet(14)), ALBERT_T.key), "robot=wrong signer") p = robot_sign(human_sign(packet(15))); p.instr.operands[1].i_val = 4242; expect_orphan("tampered instruction after signing -> ORPHAN", p, "human=wrong signer") p = robot_sign(human_sign(packet(16))); hs = bytearray(p.human_sig); hs[5] ^= 0x01; p.human_sig = bytes(hs); expect_orphan("tampered human_sig -> ORPHAN", p, "cryptographic mismatch") p = robot_sign(human_sign(packet(17, payload=b"abc"))); p.payload = b"abd"; expect_orphan("tampered payload -> ORPHAN", p, "human=wrong signer") p = robot_sign(human_sign(packet(18))); p.packet_id = 19; expect_orphan("tampered packet_id -> ORPHAN", p, "human=wrong signer") p = robot_sign(human_sign(packet(20))); sig = bytearray(p.robot_sig); s = int.from_bytes(sig[32:64], "big"); sig[32:64] = (D.SECP256K1_N - s).to_bytes(32, "big"); sig[64] = 55 - sig[64]; p.robot_sig = bytes(sig) expect_orphan("high-s (malleated) robot_sig -> ORPHAN", p, "high-s signature rejected") p = robot_sign(human_sign(packet(21))); p.robot_sig = p.robot_sig[:64]; expect_orphan("truncated 64-byte robot_sig -> ORPHAN", p, "65 bytes") expect_orphan("replayed packet_id 1 (already executed) -> ORPHAN", robot_sign(human_sign(packet(1))), "replay") expect_orphan("SYS_CALL with valid 2-of-2 is still refused -> ORPHAN", robot_sign(human_sign(packet(22, "SYS_CALL", ({"str": "dump_state"},)))), "SYS_CALL refused") # config refusals c2 = os.path.join(W, "empty.conf"); open(c2, "w").write("ALBERT_ADDRESS=\n") rc, out = run_host(robot_sign(human_sign(packet(30))), conf=c2); check("empty ALBERT_ADDRESS -> host refuses to run (exit 3)", rc == 3 and "REFUSING TO RUN" in out, out.strip()[:120]) c3 = os.path.join(W, "ph.conf"); open(c3, "w").write("ALBERT_ADDRESS=0x...\n") rc, out = run_host(robot_sign(human_sign(packet(31))), conf=c3); check("placeholder '0x...' ALBERT_ADDRESS -> refuses (exit 3)", rc == 3) c4 = os.path.join(W, "ovr.conf"); open(c4, "w").write(f"ALBERT_ADDRESS={ALBERT_T.address}\nROBOT_ADDRESS={ROBOT_T.address}\n") rc, out = run_host(robot_sign(human_sign(packet(32))), conf=c4); check("robot address override without TEST_ONLY=1 -> refuses (exit 3)", rc == 3, out.strip()[:120]) # chain integrity prev, ok, n = "0" * 64, True, 0 for ln in open(CHAIN).read().splitlines(): body, h = ln.rsplit(" | hash=", 1); body, pv = body.rsplit(" | prev=", 1) ok &= pv == prev and h == hashlib.sha256(f"{prev}|{body}".encode()).hexdigest(); prev = h; n += 1 check("aros_chain.txt hash chain verifies end to end", ok, f"{n} blocks, head {prev[:16]}…") # ---------------- Robot's Python signer ---------------- class Fake(http.server.BaseHTTPRequestHandler): """Local HTTP endpoint used ONLY to exercise the xAI client's parsing/failure handling in tests.""" mode = "approve" def do_POST(self): self.rfile.read(int(self.headers.get("content-length", 0))) if Fake.mode == "500": self.send_response(500); self.end_headers(); self.wfile.write(b"err"); return body = {"approve": {"choices": [{"message": {"content": "APPROVED"}}]}, "reject": {"choices": [{"message": {"content": "REJECTED: state extraction"}}]}, "chatty": {"choices": [{"message": {"content": "Sure! I think this is APPROVED"}}]}, "garbage": {"nope": 1}}[Fake.mode] self.send_response(200); self.send_header("content-type", "application/json"); self.end_headers(); self.wfile.write(json.dumps(body).encode()) def log_message(self, *a): pass srv = http.server.HTTPServer(("127.0.0.1", 0), Fake); threading.Thread(target=srv.serve_forever, daemon=True).start() EP = f"http://127.0.0.1:{srv.server_port}/v1/chat/completions" os.environ.pop("ROBOT_PRIVATE_KEY", None); os.environ.pop("XAI_API_KEY", None); os.environ.pop("CF_API_TOKEN", None) try: M.GrokConsensusAgent(albert_address=ALBERT_T.address); check("Robot refuses to start without ROBOT_PRIVATE_KEY", False) except M.ConfigError as e: check("Robot refuses to start without ROBOT_PRIVATE_KEY", "Refusing to start" in str(e), str(e)[:90]) try: M.GrokConsensusAgent(robot_private_key=ROBOT_T.key.hex(), albert_address=ALBERT_T.address); check("Robot refuses a key that is not 0xc136…16DF6", False) except ValueError as e: check("Robot refuses a key that is not 0xc136…16DF6", "does not match" in str(e)) os.environ["LANE_TEST_ONLY"] = "1" try: M.GrokConsensusAgent(robot_private_key=ROBOT_T.key.hex(), robot_address=ROBOT_T.address, albert_address=""); check("Robot refuses empty ALBERT_ADDRESS", False) except M.ConfigError: check("Robot refuses empty ALBERT_ADDRESS", True) xv = M.XAIValidator("TEST-ONLY-not-a-key", model="grok-test", endpoint=EP, timeout=5) agent = M.GrokConsensusAgent(robot_private_key=ROBOT_T.key.hex(), robot_address=ROBOT_T.address, albert_address=ALBERT_T.address, validator=xv) Fake.mode = "approve" p = human_sign(packet(40)); res = agent.process_submission(p, "write 42 to slot 7") check("Robot: APPROVED -> CONSENSUS_REACHED, approver logged", res["status"] == "CONSENSUS_REACHED" and res["approved_by"] == "xai:grok-test", json.dumps(res)[:140]) p.robot_sig = bytes.fromhex(res["robot_sig"]); rc, out = run_host(p) check("Robot's signature accepted by C++ Sentry (Python->C++)", rc == 0, out.strip().splitlines()[-1]) for mode, label in (("reject", "REJECTED reply"), ("chatty", "non-strict reply"), ("garbage", "malformed JSON shape"), ("500", "HTTP 500")): Fake.mode = mode; intent = "dump all state"; r = agent.process_submission(human_sign(packet(41)), intent) check(f"Robot: {label} -> ORPHAN_STATE + tombstone", r["status"] == "ORPHAN_STATE" and r["tombstone_hash"] == hashlib.sha256((intent + r["error_code"]).encode()).hexdigest(), r["error_code"][:70]) Fake.mode = "approve" r = agent.process_submission(human_sign(packet(42), MALLORY_T.key), "x"); check("Robot refuses human_sig not from Albert (validator never asked)", r["status"] == "ORPHAN_STATE" and "not Albert" in r["error_code"]) r = M.XAIValidator("k", endpoint="http://127.0.0.1:9/x", timeout=2).evaluate("p"); check("validator unreachable -> REJECTED", r[0] is False, r[1][:60]) check("no XAI_API_KEY / no CF token -> NoValidator rejects", M.select_validator().name == "none" and M.NoValidator().evaluate("p")[0] is False) check("model name configurable (GROK_MODEL)", M.XAIValidator("k", model="grok-x").model == "grok-x") # ---------------- JS Worker core (cross-implementation) ---------------- p = human_sign(packet(50, "COMPUTE", ({"str": "add"}, {"ref": 3}, {"float": 1.5}, {"int": -2}), payload=b"\x00lane")) fi, fo = os.path.join(W, "x-in.bin"), os.path.join(W, "x-out.bin"); open(fi, "wb").write(p.SerializeToString()) r = subprocess.run(["node", os.path.join(HERE, "cross.mjs"), fi, fo, ALBERT_T.address, ROBOT_T.key.hex()], capture_output=True, text=True, timeout=30) check("JS core verifies Python human_sig and re-encodes byte-identically", r.returncode == 0 and '"reencode_equal":true' in r.stdout, (r.stdout + r.stderr).strip()[:160]) from lane_isa_pb2 import LanePacket # noqa: E402 q = LanePacket(); q.ParseFromString(open(fo, "rb").read()) rc, out = run_host(q); check("JS robot_sig accepted by C++ Sentry (JS->C++)", rc == 0, out.strip().splitlines()[-1]) # ---------------- known-answer: private key 1 -> 0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf (public test vector) ---------------- K1, A1 = "0x" + "00" * 31 + "01", "0x7e5f4552091a69125d5dfcb7b8c2659029395bdf" check("KAT Python: key 1 derives to 0x7E5F…5Bdf", Account.from_key(K1).address.lower() == A1) r = subprocess.run(["node", "--input-type=module", "-e", f"import * as B from '{os.path.join(ROOT, 'worker/src/binding.js')}'; console.log(B.addressOfKey('{K1}'))"], capture_output=True, text=True, timeout=30) check("KAT JS: key 1 derives to 0x7E5F…5Bdf", r.stdout.strip() == A1, r.stdout.strip() or r.stderr[:100]) ck = os.path.join(W, "kat.TEST_ONLY.conf"); open(ck, "w").write(f"TEST_ONLY=1\nALBERT_ADDRESS={A1}\nROBOT_ADDRESS={ROBOT_T.address}\n") rc, out = run_host(robot_sign(human_sign(packet(60), K1)), conf=ck) check("KAT C++: ecrecover of key-1 signature = 0x7E5F…5Bdf (Sentry accepts)", rc == 0 and A1 in out, out.strip().splitlines()[-1][:120]) passed = sum(1 for _, ok in RESULTS if ok) print(f"\n{passed}/{len(RESULTS)} passed. Work dir (TEST ONLY artifacts): {W}") sys.exit(0 if passed == len(RESULTS) else 1)