From 75232d6f819f3091f5d8def1f186b6545cc5113c Mon Sep 17 00:00:00 2001 From: lin1er Date: Thu, 17 Sep 2026 00:50:02 +0700 Subject: [PATCH 1/2] feat(STE-49): the orchestrator locks escrow before the audit and slashes to a reporter The STE-27 rehearsal had to call onchain.* directly for two things orchestrate() could not express: 1. Lock before audit. orchestrate() ran register, verdict, mint and only then create_audit_request + post_bond, so neither fee nor bond was at stake while the audit ran. open_escrow_job() now locks both first; with escrow_lock="before_audit", orchestrate() closes that same job. 2. Slash to the reporter. _run_escrow always paid the admin. reporter_address now receives the bond; when empty the admin is paid and the step says "explicit fallback". Decisions: - The request_id travels in the journal (CREATE_REQUEST records it) and is never guessed. Before settling or slashing, get_request is read back and must be a Bonded job for this exact skill and version, because a journal is a local file that can be stale or copied. Otherwise nothing moves and the step fails naming what the chain holds. - Default stays "after_verdict" so existing callers do not change. - Resumable: an open job is not re-created, a posted bond not re-posted, a closed job neither re-closed nor silently re-opened. - An invalid reporter (not G...) or unknown mode is refused before any money moves. Tests: pipeline 673 passed (17 new: both orders, journal/chain disagreement x3, crash between create and bond, re-runs, reporter and fallback, invalid config). E2E on testnet (Escrow v1 + Registry/Tokens v2), read back from chain: - SAFE: request #20 Bonded with developer -0.1 / auditor -0.2 / escrow +0.3 USDC while the registry had no record of the bytes; after audit and orchestrate, Settled, net auditor +0.1, developer -0.1, is_verified true. - poisoned: request #21 locked the same way; audit DANGEROUS; Slashed, reporter +0.2, developer fee refunded, auditor -0.2. --- .../ste-49-e2e-escrow-order-2026-09-17.json | 243 ++++++++++++++++++ pipeline/scripts/e2e_escrow_order.py | 192 ++++++++++++++ pipeline/src/sterish_pipeline/onchain.py | 7 + pipeline/src/sterish_pipeline/orchestrator.py | 190 ++++++++++++-- pipeline/tests/test_orchestrator.py | 193 ++++++++++++++ 5 files changed, 808 insertions(+), 17 deletions(-) create mode 100644 docs/evidence/ste-49-e2e-escrow-order-2026-09-17.json create mode 100644 pipeline/scripts/e2e_escrow_order.py diff --git a/docs/evidence/ste-49-e2e-escrow-order-2026-09-17.json b/docs/evidence/ste-49-e2e-escrow-order-2026-09-17.json new file mode 100644 index 0000000..54fe1ff --- /dev/null +++ b/docs/evidence/ste-49-e2e-escrow-order-2026-09-17.json @@ -0,0 +1,243 @@ +{ + "ticket": "STE-49", + "started_at": 1789580908, + "escrow": "CCVCNFXK4YHY3ECPWCXLAMEXT4MI457ZREAZBR57CEJ3GQXONW7HVVDE", + "registry": "CCZJN366SV57JEBZVXGYY3ZBLJNFV4IR5ILCAI3EMX2WDNQPEPQ4BRL2", + "tokens": "CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T", + "fee": 1000000, + "bond": 2000000, + "reporter": "GADNHGAFXH3BE2PY2QYY5NAH3A6PWKQKK2YMF4HAF5BDOVHKI2GC5JFJ", + "runs": [ + { + "skill_id": "com.sterish.e2e-escrow-order-safe-1789580908", + "version": "1.0.0", + "expect": "SAFE", + "open": [ + { + "step": "create_audit_request", + "status": "done", + "tx_hash": "1a2e892ca142e3e31f49315dce4491a838a84d71a9c401b6efe7c04f664a4a6b", + "detail": "", + "request_id": 20 + }, + { + "step": "post_bond", + "status": "done", + "tx_hash": "9198b1ecbbcb3c54457efb401c5ed1c882bcaa82e93aaccf41106d9d0013b62e", + "detail": "" + } + ], + "request_id": 20, + "orchestrate": { + "skill_id": "com.sterish.e2e-escrow-order-safe-1789580908", + "version": "1.0.0", + "content_hash": "ffbc3f0546fb38f2629ca9352318e911896df340e8cc0311bbe12c10c6f99eb4", + "verdict": "SAFE", + "score": 100, + "evidence_hash": "b0ebc62d822235192c670f717bd7a4024dfa659cf9ed3a741b31d2b07d22d3cc", + "report_uri": "file:///reports/com.sterish.e2e-escrow-order-safe-1789580908/1.0.0.json", + "ok": true, + "steps": [ + { + "step": "register_skill", + "status": "done", + "tx_hash": "9bd647d5f0b6d8386ee76577077ea12f42ee040f66e2258441cc38acddc81efc", + "detail": "" + }, + { + "step": "publish_report", + "status": "done", + "tx_hash": null, + "detail": "/reports/com.sterish.e2e-escrow-order-safe-1789580908/1.0.0.json (669 bytes)" + }, + { + "step": "submit_verdict", + "status": "done", + "tx_hash": "9d9961c0329b2edd8ecebb3965e7655930e8e7b656754fc3964fa1b3c4685fd3", + "detail": "" + }, + { + "step": "mint_verified", + "status": "done", + "tx_hash": "d06497c863f5e84b09eacc743278359fd33fff575136705663d51f7bdccaff71", + "detail": "" + }, + { + "step": "settle", + "status": "done", + "tx_hash": "7d2695e0e3fec11feb86fc620bab68a0459696e513a8b677ac6469dd34b88c2e", + "detail": "" + } + ] + }, + "balance_deltas": { + "developer": -1000000, + "auditor": 1000000, + "reporter": 0, + "escrow": 0 + }, + "final_status": "Settled", + "tx": { + "register_skill": "9bd647d5f0b6d8386ee76577077ea12f42ee040f66e2258441cc38acddc81efc", + "submit_verdict": "9d9961c0329b2edd8ecebb3965e7655930e8e7b656754fc3964fa1b3c4685fd3", + "mint_verified": "d06497c863f5e84b09eacc743278359fd33fff575136705663d51f7bdccaff71", + "settle": "7d2695e0e3fec11feb86fc620bab68a0459696e513a8b677ac6469dd34b88c2e", + "create_audit_request": "1a2e892ca142e3e31f49315dce4491a838a84d71a9c401b6efe7c04f664a4a6b", + "post_bond": "9198b1ecbbcb3c54457efb401c5ed1c882bcaa82e93aaccf41106d9d0013b62e" + } + }, + { + "skill_id": "com.sterish.e2e-escrow-order-poisoned-1789580952", + "version": "1.0.0", + "expect": "DANGEROUS", + "open": [ + { + "step": "create_audit_request", + "status": "done", + "tx_hash": "6d718710ab383f3413344d7260a6f996739f842d79f35991cbff37a392170502", + "detail": "", + "request_id": 21 + }, + { + "step": "post_bond", + "status": "done", + "tx_hash": "bafc90e84add28a4123d91e0c5ac7ba85f7f86445a8186e98e4960e7741a26cb", + "detail": "" + } + ], + "request_id": 21, + "orchestrate": { + "skill_id": "com.sterish.e2e-escrow-order-poisoned-1789580952", + "version": "1.0.0", + "content_hash": "749f03669256c97a59d4dd880b3a3cf05457b5b743563a11cd076743e5aaca71", + "verdict": "DANGEROUS", + "score": 10, + "evidence_hash": "35ea5dac50938bda6605fef689dc20e7e90174d4435de19de36e6278c1e7e460", + "report_uri": "file:///reports/com.sterish.e2e-escrow-order-poisoned-1789580952/1.0.0.json", + "ok": true, + "steps": [ + { + "step": "register_skill", + "status": "done", + "tx_hash": "0510931a10a4e9cafb46691a3f8dbd9c99eeef424c8e52d82b163a19e5717d92", + "detail": "" + }, + { + "step": "publish_report", + "status": "done", + "tx_hash": null, + "detail": "/reports/com.sterish.e2e-escrow-order-poisoned-1789580952/1.0.0.json (10049 bytes)" + }, + { + "step": "submit_verdict", + "status": "done", + "tx_hash": "81fe33648491a321b0981207153691fb30ca129b9bb71636f7807e818f097963", + "detail": "" + }, + { + "step": "mint_verified", + "status": "skipped", + "tx_hash": null, + "detail": "verdict is DANGEROUS, not SAFE \u2014 no badge" + }, + { + "step": "slash", + "status": "done", + "tx_hash": "5321aeca3e1ac61b79c5c495f61aa0c2f44a70fb0dee40a71a7bc592547719ba", + "detail": "bond forfeited to reporter GADNHGAFXH3BE2PY2QYY5NAH3A6PWKQKK2YMF4HAF5BDOVHKI2GC5JFJ" + } + ] + }, + "balance_deltas": { + "developer": 0, + "auditor": -2000000, + "reporter": 2000000, + "escrow": 0 + }, + "final_status": "Slashed", + "tx": { + "register_skill": "0510931a10a4e9cafb46691a3f8dbd9c99eeef424c8e52d82b163a19e5717d92", + "submit_verdict": "81fe33648491a321b0981207153691fb30ca129b9bb71636f7807e818f097963", + "slash": "5321aeca3e1ac61b79c5c495f61aa0c2f44a70fb0dee40a71a7bc592547719ba", + "create_audit_request": "6d718710ab383f3413344d7260a6f996739f842d79f35991cbff37a392170502", + "post_bond": "bafc90e84add28a4123d91e0c5ac7ba85f7f86445a8186e98e4960e7741a26cb" + } + } + ], + "result": "pass", + "checks": [ + { + "check": "create_audit_request returned request #20", + "ok": true + }, + { + "check": "request #20 is Bonded for com.sterish.e2e-escrow-order-safe-1789580908 before the audit", + "ok": true + }, + { + "check": "lock moved fee and bond into escrow: {'developer': -1000000, 'auditor': -2000000, 'reporter': 0, 'escrow': 3000000}", + "ok": true + }, + { + "check": "the registry has no record of these bytes while the funds are already locked", + "ok": true + }, + { + "check": "audit verdict SAFE == SAFE", + "ok": true + }, + { + "check": "orchestrate reported every step done or skipped", + "ok": true + }, + { + "check": "request #20 Settled", + "ok": true + }, + { + "check": "settle paid fee+bond to the auditor: net {'developer': -1000000, 'auditor': 1000000, 'reporter': 0, 'escrow': 0}", + "ok": true + }, + { + "check": "registry.is_verified true for the audited version", + "ok": true + }, + { + "check": "create_audit_request returned request #21", + "ok": true + }, + { + "check": "request #21 is Bonded for com.sterish.e2e-escrow-order-poisoned-1789580952 before the audit", + "ok": true + }, + { + "check": "lock moved fee and bond into escrow: {'developer': -1000000, 'auditor': -2000000, 'reporter': 0, 'escrow': 3000000}", + "ok": true + }, + { + "check": "the registry has no record of these bytes while the funds are already locked", + "ok": true + }, + { + "check": "audit verdict DANGEROUS == DANGEROUS", + "ok": true + }, + { + "check": "orchestrate reported every step done or skipped", + "ok": true + }, + { + "check": "request #21 Slashed", + "ok": true + }, + { + "check": "slash sent the bond to the reporter and refunded the fee: net {'developer': 0, 'auditor': -2000000, 'reporter': 2000000, 'escrow': 0}", + "ok": true + }, + { + "check": "the slash step names the reporter it paid", + "ok": true + } + ], + "finished_at": 1789580987 +} diff --git a/pipeline/scripts/e2e_escrow_order.py b/pipeline/scripts/e2e_escrow_order.py new file mode 100644 index 0000000..006fa29 --- /dev/null +++ b/pipeline/scripts/e2e_escrow_order.py @@ -0,0 +1,192 @@ +"""End-to-end proof of the STE-49 escrow order on testnet, through the orchestrator. + +Real USDC moves on the live stack (Escrow v1 + Registry/Tokens v2). Two runs, both with +`escrow_lock="before_audit"`: + +1. SAFE skill: `open_escrow_job` locks fee + bond **before the skill is even registered + or audited** (read back: request Bonded, escrow holds fee+bond, registry has no + record of the hash yet). Then the audit runs, and `orchestrate` registers, submits, + mints and **settles the same request_id**, found through the journal. +2. Poisoned skill: same lock, audit comes back DANGEROUS, and `orchestrate` **slashes + the bond to the configured reporter**: reporter +bond, developer's fee refunded, + auditor -bond. + +Every claim is read back from the chain (escrow `get_request`, SAC balances, registry), +not taken from the orchestrator's own step list. Skill ids come from +`new_test_skill_id("e2e", ...)`, so nothing reaches the dashboard's default listing. + + cd pipeline && set -a && . ../.env && set +a + uv run --project . python scripts/e2e_escrow_order.py --out ../docs/evidence/ste-49-e2e.json + +Only public addresses and transaction hashes are printed or written. +""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import sys +import tempfile +import time +from pathlib import Path + +from stellar_sdk import Address, scval + +from sterish_pipeline import onchain, orchestrator +from sterish_pipeline.audit import run_audit +from sterish_pipeline.config import PipelineConfig +from sterish_pipeline.namespaces import new_test_skill_id +from sterish_pipeline.orchestrator import OrchestratorConfig, Step + +REPO = Path(__file__).resolve().parents[2] +SKILLS = REPO / "docs" / "rehearsal" / "skills" +REGISTRY = "CCZJN366SV57JEBZVXGYY3ZBLJNFV4IR5ILCAI3EMX2WDNQPEPQ4BRL2" +TOKENS = "CB6VK4EXEN7V6MXLOFUI2ECMLSDUXAUV5EZICWBICKJDL3WPPU3CTP3T" +ESCROW = "CCVCNFXK4YHY3ECPWCXLAMEXT4MI457ZREAZBR57CEJ3GQXONW7HVVDE" +USDC_SAC = "CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA" +FEE = 1_000_000 # 0.1 USDC +BOND = 2_000_000 # 0.2 USDC + + +class E2EFailure(Exception): + pass + + +checks: list[dict] = [] + + +def check(condition: bool, message: str) -> None: + checks.append({"check": message, "ok": bool(condition)}) + if not condition: + raise E2EFailure(message) + print(f" ok {message}") + + +def balance(cfg: PipelineConfig, address: str) -> int: + return int(onchain.simulate(cfg, USDC_SAC, "balance", [scval.to_address(Address(address))]) + or 0) + + +def request(cfg: PipelineConfig, request_id: int) -> dict: + return onchain.simulate(cfg, ESCROW, "get_request", [scval.to_uint32(request_id)]) + + +def status(record: dict) -> str: + s = record.get("status") + return str(s[0] if isinstance(s, (list, tuple)) and s else s) + + +def prepare(kind: str, slug: str, workdir: Path) -> tuple[Path, str]: + skill_id = new_test_skill_id("e2e", slug) + target = workdir / kind + shutil.copytree(SKILLS / kind, target) + manifest = json.loads((target / "manifest.json").read_text()) + manifest["skill_id"] = skill_id + (target / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") + return target, skill_id + + +def run(kind: str, slug: str, expect: str, cfg: PipelineConfig, env: dict, workdir: Path, + evidence: dict) -> None: + skill_dir, skill_id = prepare(kind, slug, workdir) + version = json.loads((skill_dir / "manifest.json").read_text()).get("version", "1.0.0") + developer, auditor, reporter = (env["DEVELOPER_ADDRESS"], env["AUDITOR_ADDRESS"], + env["REPORTER_ADDRESS"]) + config = OrchestratorConfig( + registry_id=REGISTRY, tokens_id=TOKENS, escrow_id=ESCROW, + owner_secret=env["DEVELOPER_SECRET"], auditor_secret=env["AUDITOR_SECRET"], + admin_secret=env["DEPLOYER_SECRET"], reports_dir=workdir / "reports", + journal_path=workdir / f"journal-{kind}.json", fee_amount=FEE, bond_amount=BOND, + run_escrow=True, escrow_lock="before_audit", reporter_address=reporter, + ) + record: dict = {"skill_id": skill_id, "version": version, "expect": expect} + evidence["runs"].append(record) + parties = {"developer": developer, "auditor": auditor, "reporter": reporter, + "escrow": ESCROW} + before = {k: balance(cfg, a) for k, a in parties.items()} + + print(f"\n{kind}: {skill_id}@{version}") + # 1. lock, before registration and before the audit exists + opened = orchestrator.open_escrow_job(skill_id, version, config, cfg) + record["open"] = [s.to_dict() for s in opened] + request_id = next(s.value for s in opened if s.step == Step.CREATE_REQUEST) + record["request_id"] = request_id + check(isinstance(request_id, int), f"create_audit_request returned request #{request_id}") + locked = request(cfg, request_id) + time.sleep(2) + after_lock = {k: balance(cfg, a) for k, a in parties.items()} + lock_delta = {k: after_lock[k] - before[k] for k in parties} + check(status(locked) == "Bonded" and locked["skill_id"] == skill_id, + f"request #{request_id} is Bonded for {skill_id} before the audit") + check(lock_delta == {"developer": -FEE, "auditor": -BOND, "reporter": 0, + "escrow": FEE + BOND}, + f"lock moved fee and bond into escrow: {lock_delta}") + + run_result = run_audit(skill_dir, config=cfg, skip_sandbox=True) + run_result.validate(submittable=True) + document = run_result.verdict_json() + check(onchain.lookup_by_hash(cfg, REGISTRY, document["content_hash"]) is None, + "the registry has no record of these bytes while the funds are already locked") + check(document["verdict"] == expect, f"audit verdict {document['verdict']} == {expect}") + + # 2. the audit result closes the same job + result = orchestrator.orchestrate(document, config, cfg) + record["orchestrate"] = result.to_dict() + check(result.ok, "orchestrate reported every step done or skipped") + closed = request(cfg, request_id) + time.sleep(2) + after = {k: balance(cfg, a) for k, a in parties.items()} + net = {k: after[k] - before[k] for k in parties} + record["balance_deltas"] = net + record["final_status"] = status(closed) + if expect == "SAFE": + check(status(closed) == "Settled", f"request #{request_id} Settled") + check(net == {"developer": -FEE, "auditor": FEE, "reporter": 0, "escrow": 0}, + f"settle paid fee+bond to the auditor: net {net}") + check(onchain.is_verified(cfg, REGISTRY, skill_id, version), + "registry.is_verified true for the audited version") + else: + check(status(closed) == "Slashed", f"request #{request_id} Slashed") + check(net == {"developer": 0, "auditor": -BOND, "reporter": BOND, "escrow": 0}, + f"slash sent the bond to the reporter and refunded the fee: net {net}") + slash = next(s for s in result.steps if s.step == Step.SLASH) + check(reporter in slash.detail, "the slash step names the reporter it paid") + record["tx"] = result.tx_hashes() | { + str(s.step): s.tx_hash for s in opened if s.tx_hash + } + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--out", default=None) + args = parser.parse_args() + env = {k: os.environ[k] for k in ( + "DEVELOPER_ADDRESS", "DEVELOPER_SECRET", "AUDITOR_ADDRESS", "AUDITOR_SECRET", + "DEPLOYER_SECRET", "REPORTER_ADDRESS")} + cfg = PipelineConfig(registry_contract_id=REGISTRY, use_llm=False) + evidence = {"ticket": "STE-49", "started_at": int(time.time()), "escrow": ESCROW, + "registry": REGISTRY, "tokens": TOKENS, "fee": FEE, "bond": BOND, + "reporter": env["REPORTER_ADDRESS"], "runs": []} + workdir = Path(tempfile.mkdtemp(prefix="ste49-")) + try: + run("safe", "escrow-order-safe", "SAFE", cfg, env, workdir, evidence) + run("poisoned", "escrow-order-poisoned", "DANGEROUS", cfg, env, workdir, evidence) + evidence["result"] = "pass" + print("\nPASS") + return 0 + except E2EFailure as exc: + evidence["result"] = f"fail: {exc}" + print(f"\nFAIL: {exc}") + return 1 + finally: + evidence["checks"] = checks + evidence["finished_at"] = int(time.time()) + if args.out: + Path(args.out).write_text(json.dumps(evidence, indent=2) + "\n") + print(f"evidence written to {args.out}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pipeline/src/sterish_pipeline/onchain.py b/pipeline/src/sterish_pipeline/onchain.py index 2d090a6..c9957dc 100644 --- a/pipeline/src/sterish_pipeline/onchain.py +++ b/pipeline/src/sterish_pipeline/onchain.py @@ -175,6 +175,13 @@ def _raise_for_error(error: Any, function: str, contract: str | None = None) -> raise OnChainError(f"{function} simulation failed: {error}") +def is_account_address(value: str) -> bool: + """A classic `G...` account (not a contract `C...` or a muxed `M...`).""" + from stellar_sdk.strkey import StrKey + + return isinstance(value, str) and StrKey.is_valid_ed25519_public_key(value) + + # --- encoding --------------------------------------------------------------- diff --git a/pipeline/src/sterish_pipeline/orchestrator.py b/pipeline/src/sterish_pipeline/orchestrator.py index 4e5ad96..20a9235 100644 --- a/pipeline/src/sterish_pipeline/orchestrator.py +++ b/pipeline/src/sterish_pipeline/orchestrator.py @@ -66,6 +66,16 @@ class OrchestratorConfig: fee_amount: int = 50_000_000 bond_amount: int = 100_000_000 run_escrow: bool = False + # When the escrow job is opened (STE-49): + # "after_verdict" — the original order: register, verdict, then create + bond + + # settle/slash in one go. Kept as the default so existing runs + # do not change underneath anyone. + # "before_audit" — the product order: `open_escrow_job` locks fee + bond BEFORE the + # audit runs, and `orchestrate` then closes that same job, found + # by the request_id the journal recorded. Never guessed. + escrow_lock: str = "after_verdict" + # Who a slashed bond goes to. Empty = the admin, and the step says so explicitly. + reporter_address: str = "" @property def owner_address(self) -> str: @@ -95,8 +105,13 @@ def tx_url(self) -> str | None: return None if not self.tx_hash else f"https://stellar.expert/explorer/testnet/tx/{self.tx_hash}" def to_dict(self) -> dict: - return {"step": str(self.step), "status": self.status, - "tx_hash": self.tx_hash, "detail": self.detail} + out = {"step": str(self.step), "status": self.status, + "tx_hash": self.tx_hash, "detail": self.detail} + # The escrow request_id is the one value a later run must read back from the + # journal (STE-49: the job is opened before the audit and closed after it). + if self.step == Step.CREATE_REQUEST and isinstance(self.value, int): + out["request_id"] = self.value + return out @dataclass @@ -274,8 +289,159 @@ def orchestrate( # 4. Economic path, opt-in: it moves real balances and needs a funded escrow. if config.run_escrow and config.escrow_id: - result.steps.extend(_run_escrow(journal, cfg, config, skill_id, version, verdict)) + _check_escrow_config(config) + if config.escrow_lock == "before_audit": + result.steps.extend(_close_escrow_job(journal, cfg, config, skill_id, version, verdict)) + else: + result.steps.extend(_run_escrow(journal, cfg, config, skill_id, version, verdict)) + + return result + + +ESCROW_LOCK_MODES = ("after_verdict", "before_audit") + + +def _check_escrow_config(config: OrchestratorConfig) -> None: + if config.escrow_lock not in ESCROW_LOCK_MODES: + raise ValueError( + f"escrow_lock must be one of {ESCROW_LOCK_MODES}, got {config.escrow_lock!r}" + ) + if config.reporter_address and not onchain.is_account_address(config.reporter_address): + raise ValueError( + f"reporter_address must be a Stellar account (G...), got {config.reporter_address!r}" + ) + + +def open_escrow_job( + skill_id: str, + version: str, + config: OrchestratorConfig, + pipeline_config: PipelineConfig | None = None, +) -> list[StepResult]: + """Lock the developer's fee and the auditor's bond BEFORE the audit runs (STE-49). + + `create_audit_request` then `post_bond`. The request_id the contract returns is + journalled with the step, so the `orchestrate` call that follows the audit closes + exactly this job. Re-running resumes: a job already created is not created again, + a bond already posted is not posted again. + """ + _check_escrow_config(config) + cfg = pipeline_config or PipelineConfig() + journal = Journal(config.journal_path) + stuck = journal.has_unknown(skill_id, version) + if stuck: + raise onchain.OnChainError( + f"previous run left {stuck} in an UNKNOWN state for {skill_id}@{version}. " + "Check the ledger and clear that entry from the journal before re-running." + ) + if not config.escrow_id: + raise ValueError("open_escrow_job needs escrow_id") + + steps: list[StepResult] = [] + created = journal.get(skill_id, version, Step.CREATE_REQUEST) + closed = journal.get(skill_id, version, Step.SETTLE) or journal.get( + skill_id, version, Step.SLASH + ) + if created and created.get("status") == "done" and not ( + closed and closed.get("status") == "done" + ): + request_id = created.get("request_id") + steps.append(StepResult( + Step.CREATE_REQUEST, "skipped", created.get("tx_hash"), + f"escrow job #{request_id} already open for this version (journal)", + value=request_id, + )) + elif created and created.get("status") == "done": + # A finished job exists; opening another is a deliberate act, not a resume. + steps.append(StepResult( + Step.CREATE_REQUEST, "skipped", created.get("tx_hash"), + "escrow job already run to completion for this version (journal); " + "delete the journal entry to open another", + )) + return steps + else: + result = _run_step( + journal, skill_id, version, Step.CREATE_REQUEST, + lambda: onchain.create_audit_request( + cfg, config.escrow_id, config.owner_secret, skill_id, version, + config.fee_amount, config.bond_amount), + ) + steps.append(result) + request_id = _request_id_from(cfg, config, result) + + if not isinstance(request_id, int): + steps.append(StepResult(Step.POST_BOND, "failed", None, "could not resolve request_id")) + return steps + + bonded = journal.get(skill_id, version, Step.POST_BOND) + if bonded and bonded.get("status") == "done": + steps.append(StepResult(Step.POST_BOND, "skipped", bonded.get("tx_hash"), + f"bond already posted on #{request_id} (journal)")) + else: + steps.append(_run_step( + journal, skill_id, version, Step.POST_BOND, + lambda: onchain.post_bond(cfg, config.escrow_id, config.auditor_secret, request_id), + )) + return steps + + +def _close_escrow_job(journal, cfg, config, skill_id, version, verdict) -> list[StepResult]: + """Settle or slash the job `open_escrow_job` locked, found through the journal.""" + _check_escrow_config(config) + for step in (Step.SETTLE, Step.SLASH): + done = journal.get(skill_id, version, step) + if done and done.get("status") == "done": + return [StepResult(step, "skipped", done.get("tx_hash"), + "escrow job already closed for this version (journal)")] + + created = journal.get(skill_id, version, Step.CREATE_REQUEST) + bonded = journal.get(skill_id, version, Step.POST_BOND) + request_id = (created or {}).get("request_id") + if not isinstance(request_id, int) or not (bonded and bonded.get("status") == "done"): + step = Step.SETTLE if verdict == FinalVerdict.SAFE.value else Step.SLASH + return [StepResult( + step, "failed", None, + "escrow_lock=before_audit but the journal holds no bonded job for this version; " + "run open_escrow_job before the audit (nothing was settled or slashed)", + )] + + # The journal is local and could be stale or copied from elsewhere. Before moving + # money, confirm on chain that this request is ours and still Bonded. + record = onchain.simulate(cfg, config.escrow_id, "get_request", + [onchain.scval.to_uint32(request_id)]) + status = record.get("status") if isinstance(record, dict) else None + if isinstance(status, (list, tuple)) and status: + status = status[0] + if not isinstance(record, dict) or record.get("skill_id") != skill_id or record.get( + "version" + ) != version or str(status) != "Bonded": + step = Step.SETTLE if verdict == FinalVerdict.SAFE.value else Step.SLASH + seen = (f"{record.get('skill_id')}@{record.get('version')} {status}" + if isinstance(record, dict) else repr(record)) + return [StepResult( + step, "failed", None, + f"journal says request #{request_id}, but on chain it is {seen}, not a Bonded " + f"job for {skill_id}@{version}; refusing to settle or slash it", + )] + + return [_settle_or_slash(journal, cfg, config, skill_id, version, verdict, request_id)] + +def _settle_or_slash(journal, cfg, config, skill_id, version, verdict, request_id) -> StepResult: + if verdict == FinalVerdict.SAFE.value: + return _run_step( + journal, skill_id, version, Step.SETTLE, + lambda: onchain.settle(cfg, config.escrow_id, config.admin_secret, request_id), + ) + reporter = config.reporter_address or config.admin_address + result = _run_step( + journal, skill_id, version, Step.SLASH, + lambda: onchain.slash(cfg, config.escrow_id, config.admin_secret, request_id, reporter), + ) + result.detail = ( + f"bond forfeited to reporter {reporter}" if config.reporter_address + else f"no reporter given: bond forfeited to the admin {reporter} (explicit fallback)" + ) return result @@ -374,20 +540,10 @@ def _run_escrow(journal, cfg, config, skill_id, version, verdict) -> list[StepRe lambda: onchain.post_bond(cfg, config.escrow_id, config.auditor_secret, request_id), )) - if verdict == FinalVerdict.SAFE.value: - steps.append(_run_step( - journal, skill_id, version, Step.SETTLE, - lambda: onchain.settle(cfg, config.escrow_id, config.admin_secret, request_id), - )) - else: - # A bad audit forfeits the bond. With no external reporter the admin is paid, - # which is the documented fallback in contracts/escrow (claim_forfeited). - steps.append(_run_step( - journal, skill_id, version, Step.SLASH, - lambda: onchain.slash(cfg, config.escrow_id, config.admin_secret, - request_id, config.admin_address), - )) - + # A bad audit forfeits the bond — to the reporter when one is configured (STE-49), + # otherwise to the admin, the documented fallback in contracts/escrow, and the step + # says which. + steps.append(_settle_or_slash(journal, cfg, config, skill_id, version, verdict, request_id)) return steps diff --git a/pipeline/tests/test_orchestrator.py b/pipeline/tests/test_orchestrator.py index 52cd0c2..64cc5e9 100644 --- a/pipeline/tests/test_orchestrator.py +++ b/pipeline/tests/test_orchestrator.py @@ -240,3 +240,196 @@ def test_already_registered_hash_is_skipped(self, cfg, chain, monkeypatch): result = orchestrator.register_only("com.acme.demo", "2.0.0", "b" * 64, cfg) assert chain == [] assert next(s for s in result.steps if s.step == Step.REGISTER).status == "skipped" + + +# --- STE-49: lock before the audit, slash to the reporter ------------------------------ + +REPORTER = Keypair.random().public_key + + +@pytest.fixture +def escrow_chain(chain, monkeypatch): + """The chain fixture, plus an escrow that remembers its requests and records who a + slash paid, so a test can assert the arguments, not only the call order.""" + requests: dict[int, dict] = {} + slashed_to: list[str] = [] + next_id = [7] + + def create(cfg, escrow_id, requestor_secret, skill_id, version, fee, bond): + chain.append("create") + rid = next_id[0] + next_id[0] += 1 + requests[rid] = {"skill_id": skill_id, "version": version, "status": ["Open"]} + return onchain.TxResult(tx_hash=f"create-{rid}", value=rid) + + def bond(cfg, escrow_id, auditor_secret, request_id): + chain.append("bond") + requests[request_id]["status"] = ["Bonded"] + return onchain.TxResult(tx_hash=f"bond-{request_id}") + + def settle(cfg, escrow_id, admin_secret, request_id): + chain.append(f"settle#{request_id}") + requests[request_id]["status"] = ["Settled"] + return onchain.TxResult(tx_hash=f"settle-{request_id}") + + def slash(cfg, escrow_id, admin_secret, request_id, reporter): + chain.append(f"slash#{request_id}") + slashed_to.append(reporter) + requests[request_id]["status"] = ["Slashed"] + return onchain.TxResult(tx_hash=f"slash-{request_id}") + + def simulate(cfg, contract_id, function, args=None): + if function == "get_request": + rid = int(onchain.scval.to_native(args[0])) + return requests.get(rid) + return False + + monkeypatch.setattr(onchain, "create_audit_request", create) + monkeypatch.setattr(onchain, "post_bond", bond) + monkeypatch.setattr(onchain, "settle", settle) + monkeypatch.setattr(onchain, "slash", slash) + monkeypatch.setattr(onchain, "simulate", simulate) + return {"calls": chain, "requests": requests, "slashed_to": slashed_to} + + +@pytest.fixture +def before_audit(cfg): + cfg.run_escrow = True + cfg.escrow_lock = "before_audit" + return cfg + + +class TestLockBeforeAudit: + def test_fee_and_bond_are_locked_before_anything_else_happens(self, before_audit, escrow_chain): + steps = orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + assert escrow_chain["calls"] == ["create", "bond"] + assert [s.status for s in steps] == ["done", "done"] + assert escrow_chain["requests"][7]["status"] == ["Bonded"] + + def test_the_audit_result_closes_the_same_job(self, before_audit, escrow_chain): + orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + result = orchestrator.orchestrate(DOC, before_audit) + assert escrow_chain["calls"] == [ + "create", "bond", "register", "verdict", "mint", "settle#7" + ] + assert result.ok + + def test_the_request_id_is_carried_by_the_journal_not_guessed(self, before_audit, escrow_chain): + orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + # Another job opened by someone else in between must not be the one settled. + escrow_chain["requests"][99] = { + "skill_id": DOC["skill_id"], "version": DOC["version"], "status": ["Bonded"] + } + orchestrator.orchestrate(DOC, before_audit) + assert "settle#7" in escrow_chain["calls"] and "settle#99" not in escrow_chain["calls"] + entry = Journal(before_audit.journal_path).get(DOC["skill_id"], DOC["version"], + Step.CREATE_REQUEST) + assert entry["request_id"] == 7 + + def test_a_dangerous_verdict_slashes_the_locked_bond_to_the_reporter( + self, before_audit, escrow_chain + ): + before_audit.reporter_address = REPORTER + orchestrator.open_escrow_job(POISON["skill_id"], POISON["version"], before_audit) + result = orchestrator.orchestrate(POISON, before_audit) + assert escrow_chain["calls"][-1] == "slash#7" + assert escrow_chain["slashed_to"] == [REPORTER] + slash = next(s for s in result.steps if s.step == Step.SLASH) + assert REPORTER in slash.detail and "reporter" in slash.detail + + def test_closing_without_an_open_job_moves_nothing(self, before_audit, escrow_chain): + result = orchestrator.orchestrate(DOC, before_audit) + settle = next(s for s in result.steps if s.step == Step.SETTLE) + assert settle.status == "failed" + assert "open_escrow_job" in settle.detail + assert not any(c.startswith(("settle#", "slash#")) for c in escrow_chain["calls"]) + assert not result.ok + + @pytest.mark.parametrize( + "tamper, why", + [ + ({"skill_id": "com.someone.else"}, "someone else's request"), + ({"version": "9.9.9"}, "another version"), + ({"status": ["Settled"]}, "already settled"), + ], + ) + def test_a_journal_that_disagrees_with_the_chain_is_refused( + self, before_audit, escrow_chain, tamper, why + ): + orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + escrow_chain["requests"][7].update(tamper) + result = orchestrator.orchestrate(DOC, before_audit) + settle = next(s for s in result.steps if s.step == Step.SETTLE) + assert settle.status == "failed", why + assert "refusing" in settle.detail + assert "settle#7" not in escrow_chain["calls"] + + def test_opening_again_resumes_instead_of_locking_twice(self, before_audit, escrow_chain): + orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + steps = orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + assert escrow_chain["calls"] == ["create", "bond"] + assert [s.status for s in steps] == ["skipped", "skipped"] + + def test_a_crash_between_create_and_bond_resumes_at_the_bond( + self, before_audit, escrow_chain, monkeypatch + ): + def bond_times_out(*a, **k): + raise onchain.OnChainError("rpc refused the connection") + + real_bond = onchain.post_bond + monkeypatch.setattr(onchain, "post_bond", bond_times_out) + with pytest.raises(onchain.OnChainError): + orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + monkeypatch.setattr(onchain, "post_bond", real_bond) + orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + assert escrow_chain["calls"] == ["create", "bond"] # one job, one bond + + def test_a_closed_job_is_not_closed_twice_or_reopened(self, before_audit, escrow_chain): + orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + orchestrator.orchestrate(DOC, before_audit) + orchestrator.orchestrate(DOC, before_audit) + steps = orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + assert escrow_chain["calls"].count("settle#7") == 1 + assert escrow_chain["calls"].count("create") == 1 + assert "completion" in steps[0].detail + + def test_the_request_id_is_never_guessed_when_the_contract_returns_none( + self, before_audit, escrow_chain, monkeypatch + ): + monkeypatch.setattr(onchain, "create_audit_request", + lambda *a, **k: onchain.TxResult(tx_hash="c", value=None)) + steps = orchestrator.open_escrow_job(DOC["skill_id"], DOC["version"], before_audit) + assert steps[-1].step == Step.POST_BOND and steps[-1].status == "failed" + assert "bond" not in escrow_chain["calls"] + + +class TestReporter: + def test_after_verdict_mode_also_pays_the_reporter(self, cfg, escrow_chain): + cfg.run_escrow = True + cfg.reporter_address = REPORTER + orchestrator.orchestrate(POISON, cfg) + assert escrow_chain["slashed_to"] == [REPORTER] + + def test_no_reporter_falls_back_to_the_admin_and_says_so(self, cfg, escrow_chain): + cfg.run_escrow = True + result = orchestrator.orchestrate(POISON, cfg) + assert escrow_chain["slashed_to"] == [cfg.admin_address] + slash = next(s for s in result.steps if s.step == Step.SLASH) + assert "explicit fallback" in slash.detail + + @pytest.mark.parametrize( + "bad", + ["not-an-address", "CCVCNFXK4YHY3ECPWCXLAMEXT4MI457ZREAZBR57CEJ3GQXONW7HVVDE"], + ) + def test_an_invalid_reporter_is_refused_before_any_money_moves(self, cfg, escrow_chain, bad): + cfg.run_escrow = True + cfg.reporter_address = bad + with pytest.raises(ValueError, match="reporter_address"): + orchestrator.orchestrate(POISON, cfg) + assert not any(c.startswith(("create", "slash#")) for c in escrow_chain["calls"]) + + def test_an_unknown_lock_mode_is_refused(self, cfg, escrow_chain): + cfg.run_escrow = True + cfg.escrow_lock = "whenever" + with pytest.raises(ValueError, match="escrow_lock"): + orchestrator.orchestrate(DOC, cfg) From 329a58ca684249c38449d5afb0053a691f9a448d Mon Sep 17 00:00:00 2001 From: lin1er Date: Thu, 17 Sep 2026 14:28:35 +0700 Subject: [PATCH 2/2] docs(STE-49): the admin fallback on slash is an operational convenience, not product behaviour Axel's note on the ACC: in a real report-and-slash flow there is always a reporter; the admin fallback exists for our own seed and rehearsal runs. --- pipeline/src/sterish_pipeline/orchestrator.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pipeline/src/sterish_pipeline/orchestrator.py b/pipeline/src/sterish_pipeline/orchestrator.py index 20a9235..aa54bf4 100644 --- a/pipeline/src/sterish_pipeline/orchestrator.py +++ b/pipeline/src/sterish_pipeline/orchestrator.py @@ -75,6 +75,11 @@ class OrchestratorConfig: # by the request_id the journal recorded. Never guessed. escrow_lock: str = "after_verdict" # Who a slashed bond goes to. Empty = the admin, and the step says so explicitly. + # + # That fallback is an operational convenience for our own runs (seed, rehearsal), NOT + # product behaviour: in a real report-and-slash flow there is always a reporter, and if + # there is none, nobody reported anything and the slash path should not have been + # reached. Callers running the product flow should always set this. reporter_address: str = "" @property