diff --git a/backend/docs/near-provenance.md b/backend/docs/near-provenance.md index d6d725c3..9faced53 100644 --- a/backend/docs/near-provenance.md +++ b/backend/docs/near-provenance.md @@ -40,6 +40,32 @@ this release trusts that operator and the configured RPC. It is not a light clie Keep the original registry configuration to verify historical records after migration; changing contract/publisher settings can invalidate those checks. +## Publish from the app (agent chat and Lab pages) + +Finished circuit, finance and pharma results show a **Publish to NEAR** button, and the agent's +`publish_near_anchor` tool shows a **Sign with wallet & publish** card. Both use +`/api/v1/near-provenance`: `prepare` writes one `near-` bundle per job and a single-use, +owner-bound request (15 minutes); the browser asks the connected wallet (MetaMask) to sign the +publication statement (`anchor_intent`, EIP-191); `requests/{id}` checks that signature, then +the backend signs the NEAR `anchor` call itself, waits for finality, verifies it and attaches +the inclusion proofs. Nobody runs a CLI. Without a browser wallet it publishes unsigned and +says so. Without `QB2_NEAR_PUBLISHER_PRIVATE_KEY=ed25519:...` it falls back to the manual +command below. + +`anchor` is payable and NEAR function-call keys cannot attach a deposit, so this needs a +**full-access key** for the publisher account. On this registry the publisher is also the +contract account, so that key can also upgrade the contract. Keep it only in the backend +environment, and prefer a dedicated registry whose publisher is a separate low-value account for +anything beyond testnet demos. + +**Wallet in the explorer.** When every bundle commits to the signed-in Ethereum wallet +(`summary.owner_wallet`), the call carries it as an extra `submitter` argument: +`anchor {"merkle_root":…,"leaf_count":…,"hash_profile":…,"submitter":"0x…"}`. NearBlocks shows +call input on the transaction page, together with `submitter_signature` when the wallet signed. +The deployed contract ignores unknown input fields, so the record is unchanged. The verifier +checks the address, that every bundle commits to it, and that the signature recovers to it over +the statement rebuilt from the call itself, so anyone can re-check it from the explorer alone. + ## Publish committed evidence From `backend/`, with project dependencies and `QB2_MONGODB_URI` configured: diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 36a609c2..cf4caf5d 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -56,6 +56,7 @@ dependencies = [ # declare explicitly so resolve/reverse APIs stay stable. "web3>=7.6.0,<8", "cryptography>=43.0.0", + "base58>=2.1.1", "motor>=3.3.0", # Agent chat still imports FastMCP; mcp 2 renamed it. "mcp[cli]>=1.0.0,<2", diff --git a/backend/src/api/v1/agents.py b/backend/src/api/v1/agents.py index ba587e9b..c19b2acc 100644 --- a/backend/src/api/v1/agents.py +++ b/backend/src/api/v1/agents.py @@ -761,6 +761,13 @@ class ApprovalRequest(BaseModel): model_config = ConfigDict(extra="forbid") summary: str = Field(max_length=2000, description="What the agent will do once approved") action: str = Field(max_length=80, description="Approve button label") + kind: Literal["near_publish"] | None = Field( + default=None, + description="near_publish: confirm via wallet signature and the NEAR publish API", + ) + request_id: str | None = Field(default=None, max_length=64) + message: str | None = Field(default=None, max_length=2000, description="Text the wallet signs") + submitter: str | None = Field(default=None, description="Wallet expected to sign") class ChatResponse(BaseModel): diff --git a/backend/src/api/v1/near_publish.py b/backend/src/api/v1/near_publish.py new file mode 100644 index 00000000..dc6d94f8 --- /dev/null +++ b/backend/src/api/v1/near_publish.py @@ -0,0 +1,92 @@ +"""NEAR provenance publishing for Lab pages and the agent chat's wallet-sign card.""" + +from __future__ import annotations + +import logging +from typing import Any + +import httpx +from fastapi import APIRouter +from pydantic import BaseModel, ConfigDict, Field + +from mcp_server.platform_mcp import owner_headers +from quantum_backend_v2.api.deps.auth import CurrentUser +from quantum_backend_v2.api.deps.research import AIAgentServiceDep +from quantum_backend_v2.api.errors.models import ErrorCode, PlatformException +from services.near_publish import complete_publication, prepare_publication, publication_status + +logger = logging.getLogger(__name__) + +router = APIRouter(prefix="/api/v1/near-provenance", tags=["near-provenance"]) + + +class PrepareRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + job_ids: list[str] = Field(min_length=1, max_length=50) + + +class PublishRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + signature: str | None = Field( + default=None, pattern=r"^0x[0-9a-fA-F]{130}$", description="EIP-191 wallet signature" + ) + + +def _fail(exc: Exception) -> PlatformException: + if isinstance(exc, OSError): + # Publisher/adapter OSErrors carry fixed, credential-free messages. + return PlatformException( + status_code=503, + error=ErrorCode.SERVICE_UNAVAILABLE, + message=f"{exc}. Nothing was lost; try again shortly.", + ) + if isinstance(exc, ValueError): + return PlatformException( + status_code=422, error=ErrorCode.VALIDATION_ERROR, message=str(exc) + ) + logger.exception("NEAR publication failed") + return PlatformException( + status_code=500, error=ErrorCode.INTERNAL_ERROR, message="NEAR publication failed" + ) + + +@router.post("/prepare", summary="Bundle completed experiments and open a publish request") +async def prepare( + body: PrepareRequest, current_user: CurrentUser, ai_agent_service: AIAgentServiceDep +) -> dict[str, Any]: + headers = owner_headers(current_user.user_id, current_user.email, current_user.wallet_address) + try: + async with httpx.AsyncClient(headers=headers) as client: + return await prepare_publication( + ai_agent_service.db, + client, + current_user.user_id, + current_user.wallet_address, + body.job_ids, + ) + except Exception as exc: + raise _fail(exc) from None + + +@router.post( + "/requests/{request_id}", summary="Publish a prepared request (optionally wallet-signed)" +) +async def publish( + request_id: str, + body: PublishRequest, + current_user: CurrentUser, + ai_agent_service: AIAgentServiceDep, +) -> dict[str, Any]: + try: + return await complete_publication( + ai_agent_service.db, current_user.user_id, request_id, body.signature + ) + except Exception as exc: + raise _fail(exc) from None + + +@router.get("/jobs/{job_id}", summary="Whether a job is anchored on NEAR testnet") +async def status( + job_id: str, current_user: CurrentUser, ai_agent_service: AIAgentServiceDep +) -> dict[str, Any]: + return await publication_status(ai_agent_service.db, current_user.user_id, job_id) diff --git a/backend/src/mcp_server/platform_mcp.py b/backend/src/mcp_server/platform_mcp.py index ea0eadc5..0aebda03 100644 --- a/backend/src/mcp_server/platform_mcp.py +++ b/backend/src/mcp_server/platform_mcp.py @@ -40,6 +40,15 @@ API = "http://localhost:8081" +def _viewable(kind: str, data: Any) -> Any: + """Add the Lab page path so the agent can link the user to the running experiment.""" + from services.near_publish import VIEW_PATHS + + if isinstance(data, dict) and data.get("job_id"): + data["view_url"] = VIEW_PATHS[kind].format(data["job_id"]) + return data + + def owner_headers(owner_id: str, email: str | None, wallet: str | None) -> dict[str, str]: """Same signed assertion the frontend sends, so agent-made jobs belong to the chat's owner.""" secret = os.getenv("AGENT_AUTH_BRIDGE_SECRET", "") @@ -60,16 +69,6 @@ def owner_headers(owner_id: str, email: str | None, wallet: str | None) -> dict[ return {"Authorization": f"Bearer qn1.{body}.{signature}"} -# (experiment type, owner-scoped result path); probed in order to find a job by ID. -_EXPERIMENT_PATHS = ( - ("quantum-circuit", "/api/v1/jobs/{}"), - ("portfolio-optimization", "/api/v1/finance/{}?result_detail=full"), - ("drug-discovery", "/api/v1/pharma/jobs/{}"), - ("options-pricing", "/api/v1/options/{}"), - ("risk-analysis", "/api/v1/risk/{}"), -) - - def create_platform_mcp( db: AsyncIOMotorDatabase, owner_id: str, @@ -355,7 +354,7 @@ async def submit_quantum_circuit(circuit: str) -> dict: json={"circuit": circuit}, timeout=30.0, ) - return resp.json() + return _viewable("quantum-circuit", resp.json()) except Exception as e: logger.error("submit_quantum_circuit failed: %s", e) return {"error": str(e)} @@ -465,7 +464,7 @@ async def price_option( json=body, timeout=30.0, ) - return resp.json() + return _viewable("options-pricing", resp.json()) except Exception as e: logger.error("price_option failed: %s", e) return {"error": str(e)} @@ -541,7 +540,7 @@ async def analyze_portfolio_risk( json=body, timeout=30.0, ) - return resp.json() + return _viewable("risk-analysis", resp.json()) except Exception as e: logger.error("analyze_portfolio_risk failed: %s", e) return {"error": str(e)} @@ -692,7 +691,7 @@ async def submit_pharma_job( json=body, timeout=30.0, ) - return resp.json() + return _viewable("drug-discovery", resp.json()) except Exception as e: logger.error("submit_pharma_job failed: %s", e) return {"error": str(e)} @@ -900,158 +899,88 @@ async def submit_portfolio_optimization( files={"file": ("agent-portfolio.csv", csv.encode(), "text/csv")}, timeout=30.0, ) - return resp.json() + return _viewable("portfolio-optimization", resp.json()) except Exception as e: logger.error("submit_portfolio_optimization failed: %s", e) return {"error": str(e)} - # ── NEAR testnet provenance (operator-signed) ───────────────────────────── - - async def _experiment_bundle(client: httpx.AsyncClient, job_id: str): - """Commit an owned, completed job's result and the owner's SIWE wallet into one bundle.""" - from quantum_backend_v2.provenance.hashing import hash_json - from quantum_backend_v2.provenance.models import ProvenanceBundle - - for kind, path in _EXPERIMENT_PATHS: # noqa: B007 - kind/path are used after the break - resp = await client.get(API + path.format(job_id), timeout=10.0) - if resp.status_code == 200: - break - else: - raise ValueError(f"No job {job_id} found in your account") - job = resp.json() - if str(job.get("status", "")).lower() != "completed": - raise ValueError( - f"Job {job_id} is {job.get('status')}; only completed experiments can be published" - ) - result = job.get("result") if job.get("result") is not None else job - summary: dict[str, Any] = { - "experiment_type": kind, - "result_hash": hash_json(result), - "result_hash_scope": "job result as returned by result_url at publication", - "result_url": path.format(job_id), - "owner_wallet": owner_wallet, - } - if job.get("provenance_bundle_id"): - summary["source_bundle_id"] = job["provenance_bundle_id"] - embedded = result.get("provenance") if isinstance(result, dict) else None - if isinstance(embedded, dict) and embedded.get("bundle_hash"): - summary["source_bundle_hash"] = embedded["bundle_hash"] - return ProvenanceBundle( - bundle_id=f"near-{job_id}", - workflow_run_id=job_id, - workflow_definition_id=kind, - owner_user_id=owner_id, - summary=summary, - is_publishable=True, - created_at=datetime.now(timezone.utc), - ) - - def _near_settings(): - from quantum_backend_v2.config import load_settings - - settings = load_settings().near_registry - if not settings.configured: - raise ValueError( - "NEAR registry is not configured (QB2_NEAR_REGISTRY_CONTRACT/PUBLISHER)" - ) - return settings - - async def _owned_bundles(collection, bundle_ids: list[str]) -> None: - query = {"bundle_id": {"$in": bundle_ids}} - rows = await collection.find(query).to_list(length=len(bundle_ids)) - if any(row["payload"].get("owner_user_id") != owner_id for row in rows): - raise ValueError("One or more provenance bundles belong to another account") + # ── NEAR testnet provenance ─────────────────────────────────────────────── @mcp.tool() - async def prepare_near_anchor(job_ids: list[str]) -> dict: - """Prepare completed experiments for publication on the NEAR testnet provenance registry. + async def publish_near_anchor(job_ids: list[str]) -> dict: + """Publish completed experiments to the NEAR testnet provenance registry. Works for quantum circuit, portfolio optimisation, drug discovery, options and risk jobs. Each job gets a provenance bundle committing to its result hash and the user's signed-in - Ethereum wallet; the bundles form one SHA-256 Merkle root. Nothing is sent on-chain here: - show the user near_cli_command exactly as returned. After they run it and paste the - transaction hash, call attach_near_anchor with the SAME job_ids in the SAME order. + Ethereum wallet; the bundles form one SHA-256 Merkle root. Calling this does NOT publish + yet: the chat shows the user a "Sign with wallet & publish" card (MetaMask), and the + app publishes and shows the explorer link once they confirm. Do not call + request_approval for this; the card is the approval. Never ask the user to run a command. Args: job_ids: 1-50 completed job IDs owned by the user Returns: - merkle_root, bundle_ids, contract_arguments and near_cli_command for the - publisher to sign. + awaiting_user_confirmation (card shown), published=true with explorer_url if these + experiments are already on-chain, or awaiting_signature with near_cli_command when + the server has no publisher key (then an operator must sign; call + attach_near_anchor with the same job_ids after they paste the hash). """ - from quantum_backend_v2.application.near_provenance import prepare_manifest - from quantum_backend_v2.persistence.mongodb import ProvenanceBundleDocument - from quantum_backend_v2.provenance.hashing import bundle_hash + from services.near_publish import prepare_publication try: - if not 1 <= len(job_ids) <= 50 or len(set(job_ids)) != len(job_ids): - raise ValueError("Provide 1-50 unique job IDs") - settings = _near_settings() - collection = db[ProvenanceBundleDocument.Settings.name] - bundle_ids = [f"near-{job_id}" for job_id in job_ids] - await _owned_bundles(collection, bundle_ids) - rows = await collection.find({"bundle_id": {"$in": bundle_ids}}).to_list(length=50) - existing = {row["bundle_id"] for row in rows} async with _api() as client: - for job_id, bundle_id in zip(job_ids, bundle_ids, strict=True): - if bundle_id in existing: - continue # keep the original commitment so retries reuse the same root - bundle = await _experiment_bundle(client, job_id) - await collection.insert_one({ - "bundle_id": bundle_id, - "workflow_run_id": job_id, - "artifact_refs": [], - "peer_log_refs": [], - "payload": bundle.model_dump(mode="json"), - "content_hash": bundle_hash(bundle), - "created_at": bundle.created_at, - "anchor_batch_id": None, - }) - manifest = await prepare_manifest(collection, bundle_ids, settings) - args = json.dumps(manifest.contract_arguments(), separators=(",", ":")) - return { - "status": "awaiting_signature", - "merkle_root": manifest.merkle_root, - "leaf_count": manifest.leaf_count, - "bundle_ids": bundle_ids, - "owner_wallet": owner_wallet, - "registry": settings.contract_id, - "contract_arguments": manifest.contract_arguments(), - "near_cli_command": ( - f"near contract call-function as-transaction {settings.contract_id} anchor " - f"json-args '{args}' prepaid-gas '30 Tgas' attached-deposit '0.01 NEAR' " - f"sign-as {settings.publisher_id} network-config testnet " - "sign-with-keychain send" - ), - } + result = await prepare_publication(db, client, owner_id, owner_wallet, job_ids) + except OSError as e: + return {"error": f"{e}. Retry shortly."} except Exception as e: - logger.error("prepare_near_anchor failed: %s", type(e).__name__) + logger.error("publish_near_anchor failed: %s", type(e).__name__) return {"error": str(e)} + if result.get("status") == "awaiting_user_confirmation": + signs = bool(result.get("message")) + result["approval"] = { + "kind": "near_publish", + "request_id": result["request_id"], + "message": result.get("message"), + "submitter": result.get("submitter"), + "summary": ( + f"Publish {result['leaf_count']} experiment(s) to the NEAR testnet registry " + f"{result['registry']} (Merkle root {result['merkle_root'][:12]}…)." + ), + "action": "Sign with wallet & publish" if signs else "Publish to NEAR", + } + return result @mcp.tool() async def attach_near_anchor(job_ids: list[str], tx_hash: str) -> dict: - """Verify a signed NEAR testnet anchor transaction and attach inclusion proofs. + """Verify an operator-signed NEAR testnet anchor transaction and attach inclusion proofs. - Call after the user pastes the transaction hash from the near_cli_command returned by - prepare_near_anchor. Use the same job_ids in the same order. Safe to retry. + Only for when publish_near_anchor returned awaiting_signature and an operator pasted + the transaction hash. Use the same job_ids in the same order. Safe to retry. Args: - job_ids: The job IDs passed to prepare_near_anchor, same order + job_ids: The job IDs passed to publish_near_anchor, same order tx_hash: NEAR testnet transaction hash (base58) Returns: verified flag, explorer_url (testnet.nearblocks.io) and merkle_root. """ - from quantum_backend_v2.application.near_provenance import attach_manifest, prepare_manifest + from quantum_backend_v2.application.near_provenance import ( + attach_manifest, + common_wallet, + prepare_manifest, + ) from quantum_backend_v2.persistence.mongodb import ProvenanceBundleDocument from quantum_backend_v2.provenance.near_registry import NearRegistryAdapter + from services.near_publish import bundle_ids_for, near_settings, owned_rows try: - settings = _near_settings() + settings = near_settings() collection = db[ProvenanceBundleDocument.Settings.name] - bundle_ids = [f"near-{job_id}" for job_id in job_ids] - await _owned_bundles(collection, bundle_ids) - manifest = await prepare_manifest(collection, bundle_ids, settings) + bundle_ids = bundle_ids_for(job_ids) + await owned_rows(collection, bundle_ids, owner_id) + submitter = await common_wallet(collection, bundle_ids) + manifest = await prepare_manifest(collection, bundle_ids, settings, submitter) adapter = NearRegistryAdapter(settings) await attach_manifest(collection, manifest, tx_hash.strip(), adapter) return { @@ -1060,7 +989,7 @@ async def attach_near_anchor(job_ids: list[str], tx_hash: str) -> dict: "registry": settings.contract_id, "merkle_root": manifest.merkle_root, "bundle_ids": bundle_ids, - "owner_wallet": owner_wallet, + "submitter": submitter, } except OSError as e: # Adapter OSErrors carry fixed, credential-free messages. diff --git a/backend/src/quantum_backend_v2/api/app.py b/backend/src/quantum_backend_v2/api/app.py index f82a0c35..5f85d069 100644 --- a/backend/src/quantum_backend_v2/api/app.py +++ b/backend/src/quantum_backend_v2/api/app.py @@ -17,6 +17,7 @@ from api.v1.agents import router as agents_router from api.v1.starknet_sessions import router as starknet_sessions_router from api.v1.chat_sessions import router as chat_sessions_router +from api.v1.near_publish import router as near_publish_router from api.v1.ens import router as ens_router from api.v1.ens_workers import router as ens_workers_router from api.v1.marketplace import router as marketplace_router @@ -325,6 +326,7 @@ async def favicon() -> Response: app.include_router(notifications_router) app.include_router(marketplace_router) app.include_router(chat_sessions_router) + app.include_router(near_publish_router) app.include_router(ens_router) app.include_router(ens_workers_router) diff --git a/backend/src/quantum_backend_v2/application/near_provenance.py b/backend/src/quantum_backend_v2/application/near_provenance.py index 0e2bd9a8..9f4744fc 100644 --- a/backend/src/quantum_backend_v2/application/near_provenance.py +++ b/backend/src/quantum_backend_v2/application/near_provenance.py @@ -29,6 +29,10 @@ class NearManifest(BaseModel): contract_id: NearTestnetAccount publisher_id: NearTestnetAccount hash_profile: Literal["qmesh-provenance-sha256-v1"] = HASH_PROFILE + # Ethereum wallet shown beside the anchor call in the explorer; every bundle commits to it. + submitter: Annotated[str, Field(pattern=r"^0x[0-9a-fA-F]{40}$")] | None = None + # EIP-191 signature by ``submitter`` over ``anchor_intent``; proves the wallet approved it. + submitter_signature: Annotated[str, Field(pattern=r"^0x[0-9a-fA-F]{130}$")] | None = None bundles: Annotated[tuple[BundleCommitment, ...], Field(min_length=1, max_length=20_000)] merkle_root: Sha256Digest leaf_count: int = Field(ge=1, le=20_000, strict=True) @@ -36,6 +40,8 @@ class NearManifest(BaseModel): @model_validator(mode="after") def validate_commitments(self) -> NearManifest: ids = [item.bundle_id for item in self.bundles] + if self.submitter_signature is not None and self.submitter is None: + raise ValueError("A wallet signature needs its submitter") if ( len(set(ids)) != len(ids) or self.leaf_count != len(ids) @@ -45,7 +51,12 @@ def validate_commitments(self) -> NearManifest: return self def contract_arguments(self) -> dict[str, Any]: - return self.model_dump(include={"merkle_root", "leaf_count", "hash_profile"}) + arguments = self.model_dump(include={"merkle_root", "leaf_count", "hash_profile"}) + if self.submitter is not None: + arguments["submitter"] = self.submitter + if self.submitter_signature is not None: + arguments["submitter_signature"] = self.submitter_signature + return arguments async def _load(collection: Any, ids: list[str]) -> dict[str, dict[str, Any]]: @@ -66,20 +77,42 @@ async def _load(collection: Any, ids: list[str]) -> dict[str, dict[str, Any]]: return found +def _wallet(row: dict[str, Any]) -> str: + return str((row["payload"].get("summary") or {}).get("owner_wallet") or "") + + +def _require_wallet(rows: dict[str, dict[str, Any]], submitter: str | None) -> None: + mismatch = submitter is not None and any( + _wallet(row).lower() != submitter.lower() for row in rows.values() + ) + if mismatch: + raise ValueError("Every bundle must commit to the submitting wallet") + + +async def common_wallet(collection: Any, bundle_ids: list[str]) -> str | None: + """The one wallet every bundle commits to, else None (nothing to show in the explorer).""" + rows = await _load(collection, bundle_ids) + wallets = {_wallet(row).lower() for row in rows.values()} + return _wallet(rows[bundle_ids[0]]) if len(wallets) == 1 and "" not in wallets else None + + async def prepare_manifest( collection: Any, bundle_ids: list[str], settings: NearRegistrySettings, + submitter: str | None = None, ) -> NearManifest: if not settings.configured: raise ValueError("NEAR registry is not configured") rows = await _load(collection, bundle_ids) + _require_wallet(rows, submitter) entries = tuple( BundleCommitment(bundle_id=key, digest=rows[key]["content_hash"]) for key in bundle_ids ) return NearManifest( contract_id=settings.contract_id, publisher_id=settings.publisher_id, + submitter=submitter, bundles=entries, merkle_root=MerkleTree([e.digest for e in entries]).root, leaf_count=len(entries), @@ -102,6 +135,7 @@ async def attach_manifest( rows = await _load(collection, [entry.bundle_id for entry in manifest.bundles]) if any(rows[e.bundle_id]["content_hash"] != e.digest for e in manifest.bundles): raise ValueError("Manifest differs from the current provenance commitments") + _require_wallet(rows, manifest.submitter) tree = MerkleTree([entry.digest for entry in manifest.bundles]) first = ChainAnchor( chain=CHAIN_ID, @@ -111,7 +145,9 @@ async def attach_manifest( leaf_count=manifest.leaf_count, proof=tree.proof(0).siblings, ) - if not await adapter.contains_root(first): + if not await adapter.contains_root( + first, submitter=manifest.submitter, signature=manifest.submitter_signature + ): raise ValueError("NEAR registry transaction does not match this manifest") for index, entry in enumerate(manifest.bundles): row = rows[entry.bundle_id] diff --git a/backend/src/quantum_backend_v2/config/models.py b/backend/src/quantum_backend_v2/config/models.py index 6ae3fef9..cdbfbb89 100644 --- a/backend/src/quantum_backend_v2/config/models.py +++ b/backend/src/quantum_backend_v2/config/models.py @@ -4,6 +4,7 @@ from collections.abc import Mapping from decimal import Decimal +import re from enum import Enum from pathlib import Path from typing import Annotated @@ -125,13 +126,27 @@ class WorkerPayoutSettings(BaseModel): class NearRegistrySettings(BaseModel): - """Opt-in, read-only verification of one trusted NEAR testnet registry.""" + """Opt-in verification of one trusted NEAR testnet registry. + + ``private_key`` is optional: set, the backend signs ``anchor`` calls as the publisher so + users never touch a CLI; unset, publication stays an operator-signed manual step. + """ model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) contract_id: NearTestnetAccount | None = None publisher_id: NearTestnetAccount | None = None rpc_url: str = Field(default="https://rpc.testnet.near.org", repr=False) + private_key: SecretStr | None = Field(default=None, repr=False) + + @field_validator("private_key") + @classmethod + def ed25519_key(cls, value: SecretStr | None) -> SecretStr | None: + if value is not None and not re.fullmatch( + r"ed25519:[1-9A-HJ-NP-Za-km-z]{43,90}", value.get_secret_value() + ): + raise ValueError("NEAR publisher key must look like ed25519:") + return value @field_validator("rpc_url") @classmethod @@ -147,6 +162,8 @@ def https_rpc(cls, value: str) -> str: def complete_identity(self) -> NearRegistrySettings: if (self.contract_id is None) != (self.publisher_id is None): raise ValueError("NEAR registry contract and publisher must be configured together") + if self.private_key is not None and self.publisher_id is None: + raise ValueError("A NEAR publisher key needs the registry contract and publisher") return self @property @@ -305,6 +322,7 @@ def from_env(cls, env: Mapping[str, str]) -> AppSettings: "contract_id": _optional(env.get("QB2_NEAR_REGISTRY_CONTRACT")), "publisher_id": _optional(env.get("QB2_NEAR_REGISTRY_PUBLISHER")), "rpc_url": env.get("QB2_NEAR_RPC_URL", "https://rpc.testnet.near.org"), + "private_key": _optional(env.get("QB2_NEAR_PUBLISHER_PRIVATE_KEY")), } ), anchor=AnchorSettings.model_validate( diff --git a/backend/src/quantum_backend_v2/provenance/near_publisher.py b/backend/src/quantum_backend_v2/provenance/near_publisher.py new file mode 100644 index 00000000..8d1a2afc --- /dev/null +++ b/backend/src/quantum_backend_v2/provenance/near_publisher.py @@ -0,0 +1,165 @@ +"""Sign and broadcast the registry's ``anchor`` call with the publisher's testnet key. + +Why a full-access key: ``anchor`` is payable (it pays record storage), and NEAR +function-call keys cannot attach a deposit. Keep this key in the environment only; it never +reaches a prompt, tool result, log or response. Verification stays in ``NearRegistryAdapter``. +""" + +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json +import struct +from typing import Any + +import base58 +import httpx +from nacl.signing import SigningKey + +from quantum_backend_v2.config.models import NearRegistrySettings + +_GAS = 30 * 10**12 # 30 Tgas, as in docs/near-provenance.md +_DEPOSIT = 10**22 # 0.01 NEAR; the contract refunds whatever storage does not use +_MAX_RPC_BYTES = 1024 * 1024 +# shortcut: one lock per process serializes nonces; use a shared lock if the API runs multi-worker. +_NONCE_LOCK = asyncio.Lock() + + +def _string(text: str) -> bytes: + raw = text.encode() + return struct.pack(" SigningKey: + """Parse ``ed25519:`` (32-byte seed or the 64-byte seed+public form near-cli stores).""" + raw = base58.b58decode(secret.removeprefix("ed25519:")) + if len(raw) not in (32, 64): + raise ValueError("NEAR publisher key has the wrong length") + key = SigningKey(raw[:32]) + if len(raw) == 64 and bytes(key.verify_key) != raw[32:]: + raise ValueError("NEAR publisher key halves do not match") + return key + + +def encode_transaction( + signer_id: str, + public_key: bytes, + nonce: int, + receiver_id: str, + block_hash: bytes, + method: str, + args: bytes, +) -> bytes: + """Borsh-encode a one-action FunctionCall transaction.""" + action = ( + b"\x02" + + _string(method) + + struct.pack(" str: + return "ed25519:" + base58.b58encode(bytes(self._key.verify_key)).decode() + + async def _rpc(self, client: httpx.AsyncClient, method: str, params: Any) -> dict[str, Any]: + try: + response = await client.post( + self._settings.rpc_url, + json={"jsonrpc": "2.0", "id": 1, "method": method, "params": params}, + timeout=45.0, + follow_redirects=False, + ) + response.raise_for_status() + if len(response.content) > _MAX_RPC_BYTES: + raise ValueError("Oversized RPC response") + body = response.json() + except (httpx.HTTPError, ValueError): + # Endpoint URLs and RPC payloads can carry credentials. + raise OSError("NEAR RPC unavailable") from None + if not isinstance(body, dict) or not isinstance(body.get("result"), dict): + error = body.get("error") if isinstance(body, dict) else None + reason = error.get("cause", {}).get("name") if isinstance(error, dict) else None + raise OSError(f"NEAR RPC rejected {method}" + (f" ({reason})" if reason else "")) + if "error" in body["result"]: + # `query` reports failures (e.g. an unknown access key) inside the result. + raise OSError(f"NEAR RPC rejected {method}") + return body["result"] + + async def anchor(self, arguments: dict[str, Any]) -> str: + """Publish one root and return the finalized transaction hash. + + Re-publishing an identical root is idempotent on-chain (the original record is returned + and the deposit refunded), so retrying after a timeout cannot double-register. + """ + async with _NONCE_LOCK: + if self._client is None: + async with httpx.AsyncClient() as client: + return await self._anchor(client, arguments) + return await self._anchor(self._client, arguments) + + async def _anchor(self, client: httpx.AsyncClient, arguments: dict[str, Any]) -> str: + settings = self._settings + status = await self._rpc(client, "status", []) + if status.get("chain_id") != "testnet": + raise OSError("NEAR RPC is not on testnet") + try: + access_key = await self._rpc( + client, + "query", + { + "request_type": "view_access_key", + "finality": "final", + "account_id": settings.publisher_id, + "public_key": self.public_key, + }, + ) + except OSError: + raise OSError( + f"The configured NEAR key is not an access key of {settings.publisher_id}" + ) from None + transaction = encode_transaction( + settings.publisher_id, + bytes(self._key.verify_key), + int(access_key["nonce"]) + 1, + settings.contract_id, + base58.b58decode(access_key["block_hash"]), + "anchor", + json.dumps(arguments, separators=(",", ":")).encode(), + ) + digest = hashlib.sha256(transaction).digest() + signed = transaction + b"\x00" + self._key.sign(digest).signature + result = await self._rpc( + client, + "send_tx", + {"signed_tx_base64": base64.b64encode(signed).decode(), "wait_until": "FINAL"}, + ) + tx_hash = base58.b58encode(digest).decode() + if result.get("transaction", {}).get("hash") != tx_hash: + raise OSError("NEAR RPC returned a different transaction") + if "SuccessValue" not in result.get("status", {}): + raise OSError("NEAR registry rejected the anchor call") + return tx_hash diff --git a/backend/src/quantum_backend_v2/provenance/near_registry.py b/backend/src/quantum_backend_v2/provenance/near_registry.py index e955ab4c..13b700ee 100644 --- a/backend/src/quantum_backend_v2/provenance/near_registry.py +++ b/backend/src/quantum_backend_v2/provenance/near_registry.py @@ -17,6 +17,35 @@ CHAIN_ID = "near:testnet" HASH_PROFILE = "qmesh-provenance-sha256-v1" _TX_HASH = re.compile(r"[1-9A-HJ-NP-Za-km-z]{32,44}") +_EVM_ADDRESS = re.compile(r"0x[0-9a-fA-F]{40}") +_EVM_SIGNATURE = re.compile(r"0x[0-9a-fA-F]{130}") + + +def anchor_intent(contract_id: str, merkle_root: str, leaf_count: int, submitter: str) -> str: + """The text a submitter's Ethereum wallet signs (EIP-191) to approve one publication. + + Everything in it is also in the anchor call, so anyone can re-check the signature + from the explorer alone. + """ + return ( + "QMesh provenance anchor\n" + f"Registry: {contract_id} (NEAR testnet)\n" + f"Merkle root: {merkle_root}\n" + f"Experiments: {leaf_count}\n" + f"Hash profile: {HASH_PROFILE}\n" + f"Submitter: {submitter}" + ) + + +def signed_by(message: str, signature: str, address: str) -> bool: + from eth_account import Account + from eth_account.messages import encode_defunct + + try: + signer = Account.recover_message(encode_defunct(text=message), signature=signature) + except Exception: + return False + return signer.lower() == address.lower() _MAX_RPC_BYTES = 1024 * 1024 @@ -29,10 +58,13 @@ def __init__(self, settings: NearRegistrySettings, *, client: httpx.Client | Non self.settings = settings self._client = client - async def contains_root(self, anchor: ChainAnchor) -> bool: + async def contains_root( + self, anchor: ChainAnchor, submitter: str | None = None, signature: str | None = None + ) -> bool: + """``submitter``/``signature``: when given, the call must carry exactly these too.""" if anchor.chain != CHAIN_ID or _TX_HASH.fullmatch(anchor.tx_hash) is None: return False - return await asyncio.to_thread(self._check, anchor) + return await asyncio.to_thread(self._check, anchor, submitter, signature) @staticmethod def explorer_url(tx_hash: str) -> str: @@ -72,13 +104,21 @@ def _rpc(self, client: httpx.Client, method: str, params: Any) -> dict[str, Any] # RPC error payloads and endpoint URLs can contain credentials. raise OSError("NEAR registry lookup unavailable") from None - def _check(self, anchor: ChainAnchor) -> bool: + def _check( + self, anchor: ChainAnchor, submitter: str | None = None, signature: str | None = None + ) -> bool: if self._client is None: with httpx.Client() as client: - return self._check_with(client, anchor) - return self._check_with(self._client, anchor) + return self._check_with(client, anchor, submitter, signature) + return self._check_with(self._client, anchor, submitter, signature) - def _check_with(self, client: httpx.Client, anchor: ChainAnchor) -> bool: + def _check_with( + self, + client: httpx.Client, + anchor: ChainAnchor, + submitter: str | None = None, + signature: str | None = None, + ) -> bool: try: # Independent reads run together within the verifier's ten-second I/O budget. with ThreadPoolExecutor(max_workers=3) as pool: @@ -137,6 +177,36 @@ def _check_with(self, client: httpx.Client, anchor: ChainAnchor) -> bool: if call.get("method_name") != "anchor": return False arguments = json.loads(base64.b64decode(call["args"], validate=True)) + # The contract ignores unknown input fields, so the call may name the user's wallet + # for explorer readers. It is never stored in the record; only its format is checked. + if not isinstance(arguments, dict): + return False + claimed = arguments.pop("submitter", None) + claimed_signature = arguments.pop("submitter_signature", None) + if claimed is not None and ( + not isinstance(claimed, str) or _EVM_ADDRESS.fullmatch(claimed) is None + ): + return False + if submitter is not None and (claimed or "").lower() != submitter.lower(): + return False + if claimed_signature is not None and not ( + isinstance(claimed_signature, str) + and _EVM_SIGNATURE.fullmatch(claimed_signature) + and claimed is not None + and signed_by( + anchor_intent( + self.settings.contract_id, + anchor.merkle_root, + anchor.leaf_count, + claimed, + ), + claimed_signature, + claimed, + ) + ): + return False + if signature is not None and (claimed_signature or "").lower() != signature.lower(): + return False if arguments != expected or type(arguments.get("leaf_count")) is not int: return False if not _successful_status(result["status"]): diff --git a/backend/src/services/ai_agent_service.py b/backend/src/services/ai_agent_service.py index 194d2465..9418828d 100644 --- a/backend/src/services/ai_agent_service.py +++ b/backend/src/services/ai_agent_service.py @@ -937,6 +937,15 @@ async def invoke(name, arguments): except ValueError as exc: return {"error": str(exc)} result = await mcp_server.call_tool(name, arguments) + blocks = result[0] if isinstance(result, tuple) else result + single = isinstance(blocks, list) and len(blocks) == 1 + if single and getattr(blocks[0], "type", "") == "text": + # FastMCP wraps the tool's dict as one JSON text block; unwrap so the chat loop can + # see structured fields such as `approval`. + try: + return json.loads(blocks[0].text) + except ValueError: + return blocks[0].text return result.model_dump(mode="json") if hasattr(result, "model_dump") else result system = ( @@ -951,13 +960,15 @@ async def invoke(name, arguments): "Do not repeatedly call a failed tool or duplicate a creation request. " "Whenever you need the user's go-ahead, call request_approval instead of asking in " "text. A user message starting with 'Approved' is that go-ahead: proceed. " + "When you submit a job, always give the user its view_url as a markdown link, e.g. " + "[Open the run](/runs/job-123), so they can watch it in the Lab. " "After an experiment completes, offer to publish it to NEAR testnet with " - "prepare_near_anchor. Show the returned near_cli_command verbatim on one line; " - "the registry publisher account signs it with the NEAR CLI. The Ethereum " - "owner_wallet is attribution inside the bundles, not the NEAR signer. When the user " - "pastes the transaction hash, call attach_near_anchor with the same job_ids in the " - "same order. Never claim an experiment is on-chain until attach_near_anchor " - "returns verified." + "publish_near_anchor (no request_approval needed: it shows a card where the user " + "signs with their wallet and the app publishes and shows the explorer link). " + "Never ask the user to run a command or open a terminal. Only if it returns " + "awaiting_signature (server has no publisher key) say an operator must sign it. " + "If it returns published=true, share explorer_url. Never claim an experiment is " + "on-chain without an explorer_url." ) messages = [{"role": "system", "content": system}] messages.extend({"role": h["role"], "content": h["content"]} diff --git a/backend/src/services/groq_agent.py b/backend/src/services/groq_agent.py index b7119f3f..84abdf0f 100644 --- a/backend/src/services/groq_agent.py +++ b/backend/src/services/groq_agent.py @@ -217,12 +217,20 @@ async def complete( raise ValueError("Tool arguments must be an object") logging.getLogger(__name__).info("Agent tool: %s", function["name"]) result = await invoke(function["name"], arguments) - if function["name"] == "request_approval" and isinstance(result, dict): + approval = None + if isinstance(result, dict): + approval = ( + {"summary": result["summary"], "action": result["action"]} + if function["name"] == "request_approval" + else result.get("approval") + ) + if isinstance(approval, dict): + # The turn ends here; the chat shows the approval card (or wallet-sign card). if meta is not None: - meta["approval"] = {"summary": result["summary"], "action": result["action"]} + meta["approval"] = approval if provider == "near": _populate_near_meta(meta, model, round_statuses, round_signatures, last_request_id, round_index) - return message.get("content") or result["summary"] + return message.get("content") or approval["summary"] if function["name"] == "prepare_storage_export" and isinstance(result, dict) and result.get("status") == "pending": if provider == "near" and meta is not None: _populate_near_meta(meta, model, round_statuses, round_signatures, last_request_id, round_index) diff --git a/backend/src/services/near_publish.py b/backend/src/services/near_publish.py new file mode 100644 index 00000000..0e7bd6b5 --- /dev/null +++ b/backend/src/services/near_publish.py @@ -0,0 +1,280 @@ +"""Publish completed experiments to the NEAR testnet registry (agent chat and Lab pages). + +Flow: ``prepare_publication`` writes one ``near-`` bundle per job and a single-use +request; the user optionally signs ``message`` with their Ethereum wallet (MetaMask); then +``complete_publication`` has the backend sign the NEAR ``anchor`` call, verifies it on-chain +and attaches inclusion proofs. Wallet keys never leave the browser and the NEAR key never +leaves the backend. +""" + +from __future__ import annotations + +import json +import uuid +from datetime import datetime, timedelta, timezone +from typing import Any + +import httpx +from eth_account import Account +from eth_account.messages import encode_defunct + +from quantum_backend_v2.application.near_provenance import ( + NearManifest, + attach_manifest, + common_wallet, + prepare_manifest, +) +from quantum_backend_v2.config import load_settings +from quantum_backend_v2.config.models import NearRegistrySettings +from quantum_backend_v2.persistence.mongodb import ProvenanceBundleDocument +from quantum_backend_v2.provenance.hashing import bundle_hash, hash_json +from quantum_backend_v2.provenance.models import ProvenanceBundle +from quantum_backend_v2.provenance.near_publisher import NearPublisher +from quantum_backend_v2.provenance.near_registry import ( + CHAIN_ID, + NearRegistryAdapter, + anchor_intent, +) + +API = "http://localhost:8081" +REQUESTS = "near_publish_requests" +REQUEST_TTL = timedelta(minutes=15) + +# (experiment type, owner-scoped result path, Lab page); probed in order to find a job by ID. +EXPERIMENTS = ( + ("quantum-circuit", "/api/v1/jobs/{}", "/runs/{}"), + ("portfolio-optimization", "/api/v1/finance/{}?result_detail=full", "/finance/{}"), + ("drug-discovery", "/api/v1/pharma/jobs/{}", "/pharma/jobs/{}"), + ("options-pricing", "/api/v1/options/{}", "/options/{}"), + ("risk-analysis", "/api/v1/risk/{}", "/risk/{}"), +) +VIEW_PATHS = {kind: view for kind, _, view in EXPERIMENTS} + + +def near_settings() -> NearRegistrySettings: + settings = load_settings().near_registry + if not settings.configured: + raise ValueError("NEAR registry is not configured (QB2_NEAR_REGISTRY_CONTRACT/PUBLISHER)") + return settings + + +def bundle_ids_for(job_ids: list[str]) -> list[str]: + if not 1 <= len(job_ids) <= 50 or len(set(job_ids)) != len(job_ids): + raise ValueError("Provide 1-50 unique job IDs") + return [f"near-{job_id}" for job_id in job_ids] + + +async def owned_rows(collection: Any, bundle_ids: list[str], owner_id: str) -> list[dict]: + rows = await collection.find({"bundle_id": {"$in": bundle_ids}}).to_list(length=len(bundle_ids)) + if any(row["payload"].get("owner_user_id") != owner_id for row in rows): + raise ValueError("One or more provenance bundles belong to another account") + return rows + + +async def experiment_bundle( + client: httpx.AsyncClient, job_id: str, owner_id: str, owner_wallet: str | None +) -> ProvenanceBundle: + """Commit an owned, completed job's result and the owner's SIWE wallet into one bundle. + + ``client`` must call the API as the owner, so foreign jobs are simply not found. + """ + for kind, path, view in EXPERIMENTS: # noqa: B007 - used after the break + resp = await client.get(API + path.format(job_id), timeout=10.0) + if resp.status_code == 200: + break + else: + raise ValueError(f"No job {job_id} found in your account") + job = resp.json() + if str(job.get("status", "")).lower() != "completed": + raise ValueError( + f"Job {job_id} is {job.get('status')}; only completed experiments can be published" + ) + result = job.get("result") if job.get("result") is not None else job + summary: dict[str, Any] = { + "experiment_type": kind, + "result_hash": hash_json(result), + "result_hash_scope": "job result as returned by result_url at publication", + "result_url": path.format(job_id), + "view_url": view.format(job_id), + "owner_wallet": owner_wallet, + } + if job.get("provenance_bundle_id"): + summary["source_bundle_id"] = job["provenance_bundle_id"] + embedded = result.get("provenance") if isinstance(result, dict) else None + if isinstance(embedded, dict) and embedded.get("bundle_hash"): + summary["source_bundle_hash"] = embedded["bundle_hash"] + return ProvenanceBundle( + bundle_id=f"near-{job_id}", + workflow_run_id=job_id, + workflow_definition_id=kind, + owner_user_id=owner_id, + summary=summary, + is_publishable=True, + created_at=datetime.now(timezone.utc), + ) + + +def _near_anchor(row: dict, merkle_root: str | None = None) -> dict | None: + for anchor in row["payload"].get("anchors", []): + if anchor.get("chain") == CHAIN_ID and merkle_root in (None, anchor.get("merkle_root")): + return anchor + return None + + +async def prepare_publication( + db: Any, + client: httpx.AsyncClient, + owner_id: str, + owner_wallet: str | None, + job_ids: list[str], +) -> dict[str, Any]: + settings = near_settings() + collection = db[ProvenanceBundleDocument.Settings.name] + bundle_ids = bundle_ids_for(job_ids) + existing = {row["bundle_id"] for row in await owned_rows(collection, bundle_ids, owner_id)} + for job_id, bundle_id in zip(job_ids, bundle_ids, strict=True): + if bundle_id in existing: + continue # keep the original commitment so retries reuse the same root + bundle = await experiment_bundle(client, job_id, owner_id, owner_wallet) + await collection.insert_one( + { + "bundle_id": bundle_id, + "workflow_run_id": job_id, + "artifact_refs": [], + "peer_log_refs": [], + "payload": bundle.model_dump(mode="json"), + "content_hash": bundle_hash(bundle), + "created_at": bundle.created_at, + "anchor_batch_id": None, + } + ) + submitter = await common_wallet(collection, bundle_ids) + manifest = await prepare_manifest(collection, bundle_ids, settings, submitter) + rows = await owned_rows(collection, bundle_ids, owner_id) + anchors = [_near_anchor(row, manifest.merkle_root) for row in rows] + if anchors and all(anchors): + return { + "published": True, + "explorer_url": anchors[0].get("url"), + "tx_hash": anchors[0].get("tx_hash"), + "merkle_root": manifest.merkle_root, + "bundle_ids": bundle_ids, + "submitter": submitter, + } + base = { + "merkle_root": manifest.merkle_root, + "leaf_count": manifest.leaf_count, + "bundle_ids": bundle_ids, + "submitter": submitter, + "registry": settings.contract_id, + } + if settings.private_key is None: + args = json.dumps(manifest.contract_arguments(), separators=(",", ":")) + return base | { + "status": "awaiting_signature", + "near_cli_command": ( + f"near contract call-function as-transaction {settings.contract_id} anchor " + f"json-args '{args}' prepaid-gas '30 Tgas' attached-deposit '0.01 NEAR' " + f"sign-as {settings.publisher_id} network-config testnet " + "sign-with-keychain send" + ), + } + message = ( + anchor_intent(settings.contract_id, manifest.merkle_root, manifest.leaf_count, submitter) + if submitter + else None + ) + now = datetime.now(timezone.utc) + request_id = uuid.uuid4().hex + await db[REQUESTS].insert_one( + { + "_id": request_id, + "owner_id": owner_id, + "bundle_ids": bundle_ids, + "merkle_root": manifest.merkle_root, + "submitter": submitter, + "message": message, + "status": "pending", + "created_at": now, + "expires_at": now + REQUEST_TTL, + } + ) + return base | { + "status": "awaiting_user_confirmation", + "request_id": request_id, + "message": message, + } + + +async def complete_publication( + db: Any, owner_id: str, request_id: str, signature: str | None +) -> dict[str, Any]: + """Single-use: claim the request, publish, verify, attach. Failures release the claim.""" + settings = near_settings() + if settings.private_key is None: + raise ValueError("Automatic NEAR publishing is not configured on this server") + requests = db[REQUESTS] + now = datetime.now(timezone.utc) + request = await requests.find_one_and_update( + {"_id": request_id, "owner_id": owner_id, "status": "pending", "expires_at": {"$gt": now}}, + {"$set": {"status": "publishing", "claimed_at": now}}, + ) + if request is None: + raise ValueError("This publish request is unknown, expired or already used") + try: + submitter = request.get("submitter") + if signature is not None: + if not submitter or not request.get("message"): + raise ValueError("This publication has no wallet to sign with") + try: + signer = Account.recover_message( + encode_defunct(text=request["message"]), signature=signature + ) + except Exception: + raise ValueError("The wallet signature is malformed") from None + if signer.lower() != submitter.lower(): + raise ValueError(f"Sign with {submitter}; the signature came from {signer}") + collection = db[ProvenanceBundleDocument.Settings.name] + await owned_rows(collection, request["bundle_ids"], owner_id) + manifest = await prepare_manifest(collection, request["bundle_ids"], settings, submitter) + if manifest.merkle_root != request["merkle_root"]: + raise ValueError("The experiments changed since this request; prepare it again") + if signature is not None: + manifest = NearManifest.model_validate( + manifest.model_dump() | {"submitter_signature": signature} + ) + tx_hash = await NearPublisher(settings).anchor(manifest.contract_arguments()) + adapter = NearRegistryAdapter(settings) + await attach_manifest(collection, manifest, tx_hash, adapter) + except BaseException: + await requests.update_one({"_id": request_id}, {"$set": {"status": "pending"}}) + raise + await requests.update_one( + {"_id": request_id}, {"$set": {"status": "published", "tx_hash": tx_hash}} + ) + return { + "published": True, + "explorer_url": adapter.explorer_url(tx_hash), + "tx_hash": tx_hash, + "registry": settings.contract_id, + "merkle_root": manifest.merkle_root, + "bundle_ids": request["bundle_ids"], + "submitter": submitter, + "wallet_signed": signature is not None, + } + + +async def publication_status(db: Any, owner_id: str, job_id: str) -> dict[str, Any]: + row = await db[ProvenanceBundleDocument.Settings.name].find_one({"bundle_id": f"near-{job_id}"}) + if row is None or row["payload"].get("owner_user_id") != owner_id: + return {"published": False} + anchor = _near_anchor(row) + if anchor is None: + return {"published": False} + return { + "published": True, + "explorer_url": anchor.get("url"), + "tx_hash": anchor.get("tx_hash"), + "merkle_root": anchor.get("merkle_root"), + "submitter": (row["payload"].get("summary") or {}).get("owner_wallet"), + } diff --git a/backend/tests/unit/test_near_provenance.py b/backend/tests/unit/test_near_provenance.py index ef43d4f7..33c83f64 100644 --- a/backend/tests/unit/test_near_provenance.py +++ b/backend/tests/unit/test_near_provenance.py @@ -16,6 +16,7 @@ from quantum_backend_v2.application.near_provenance import ( NearManifest, attach_manifest, + common_wallet, prepare_manifest, ) from quantum_backend_v2.config.models import AppSettings, NearRegistrySettings @@ -41,8 +42,11 @@ def anchor(root=ROOT, count=1): ) +WALLET = "0x9E61709c27d1214eb01A72e778d5FAd20D0B4e26" + + class Node: - def __init__(self, root=ROOT, count=1): + def __init__(self, root=ROOT, count=1, submitter=None): self.network = "testnet" self.record = dict( merkle_root=root, @@ -63,6 +67,7 @@ def __init__(self, root=ROOT, count=1): "args": base64.b64encode( json.dumps( dict(merkle_root=root, leaf_count=count, hash_profile=PROFILE) + | ({"submitter": submitter} if submitter is not None else {}) ).encode() ).decode(), "gas": 30_000_000_000_000, @@ -259,7 +264,7 @@ async def to_list(self, length): class Collection: - def __init__(self): + def __init__(self, wallet=None): self.rows = {} self.writes = 0 self.conflict = False @@ -274,6 +279,9 @@ def __init__(self): bundle = build_result_bundle( self.run, created_at=datetime(2026, 11, 10, tzinfo=timezone.utc) ) + if wallet is not None: # a wallet-committing bundle, as the agent's publish tool writes + summary = {**bundle.summary, "owner_wallet": wallet} + bundle = bundle.model_copy(update={"summary": summary}) self.rows[bundle.bundle_id] = dict( bundle_id=bundle.bundle_id, workflow_run_id=bundle.workflow_run_id, @@ -424,3 +432,93 @@ async def interrupted(query, update): assert current["payload"]["anchors"][0] == before[key]["payload"]["anchors"][0] assert len(current["payload"]["anchors"]) == 2 assert current["anchor_batch_id"] == before[key]["anchor_batch_id"] + + +def test_submitter_is_optional_checked_and_never_required_by_default(): + assert check(Node(submitter=WALLET)) # explorer-visible wallet does not break verification + assert check(Node()) # older anchors without one still verify + for bad in ("0xnothex", "x" * 42, 7): + assert not check(Node(submitter=bad)) + + +def test_expected_submitter_must_match_the_call(): + def verify(node, submitter): + with httpx.Client(transport=httpx.MockTransport(node.respond)) as client: + adapter = NearRegistryAdapter(SETTINGS, client=client) + return asyncio.run(adapter.contains_root(anchor(), submitter=submitter)) + + assert verify(Node(submitter=WALLET), WALLET.lower()) + assert not verify(Node(submitter=WALLET), "0x" + "1" * 40) + assert not verify(Node(), WALLET) # a wallet was promised but the call never named it + + +def test_manifest_names_the_wallet_every_bundle_commits_to(): + collection = Collection(wallet=WALLET) + ids = list(collection.rows) + assert asyncio.run(common_wallet(collection, ids)) == WALLET + manifest = asyncio.run(prepare_manifest(collection, ids, SETTINGS, WALLET)) + assert manifest.contract_arguments()["submitter"] == WALLET + assert NearManifest.model_validate_json(manifest.model_dump_json()) == manifest + # the wallet is explorer-only: it does not change the committed Merkle root + plain = asyncio.run(prepare_manifest(Collection(), list(Collection().rows), SETTINGS)) + assert "submitter" not in plain.contract_arguments() + with pytest.raises(ValueError, match="commit to the submitting wallet"): + asyncio.run(prepare_manifest(collection, ids, SETTINGS, "0x" + "2" * 40)) + assert asyncio.run(common_wallet(Collection(), list(Collection().rows))) is None + node = Node(manifest.merkle_root, submitter=WALLET) + with httpx.Client(transport=httpx.MockTransport(node.respond)) as client: + adapter = NearRegistryAdapter(SETTINGS, client=client) + asyncio.run(attach_manifest(collection, manifest, TX, adapter)) + wrong = Node(manifest.merkle_root, submitter="0x" + "3" * 40) + with httpx.Client(transport=httpx.MockTransport(wrong.respond)) as client: + with pytest.raises(ValueError, match="does not match"): + asyncio.run( + attach_manifest( + Collection(wallet=WALLET), + manifest, + TX, + NearRegistryAdapter(SETTINGS, client=client), + ) + ) + + +def _signed_node(sign_with=None, submitter=None): + from eth_account import Account + from eth_account.messages import encode_defunct + + from quantum_backend_v2.provenance.near_registry import anchor_intent + + wallet = Account.create() + signer = sign_with or wallet + claimed = submitter or wallet.address + message = anchor_intent("registry.testnet", ROOT, 1, claimed) + signature = signer.sign_message(encode_defunct(text=message)).signature.to_0x_hex() + node = Node(submitter=claimed) + call = node.transaction["actions"][0]["FunctionCall"] + arguments = json.loads(base64.b64decode(call["args"])) | {"submitter_signature": signature} + call["args"] = base64.b64encode(json.dumps(arguments).encode()).decode() + return node, claimed, signature + + +def test_wallet_signature_in_the_call_must_come_from_the_named_submitter(): + from eth_account import Account + + node, wallet, signature = _signed_node() + assert check(node) + with httpx.Client(transport=httpx.MockTransport(node.respond)) as client: + adapter = NearRegistryAdapter(SETTINGS, client=client) + assert asyncio.run(adapter.contains_root(anchor(), submitter=wallet, signature=signature)) + assert not asyncio.run( + adapter.contains_root(anchor(), submitter=wallet, signature="0x" + "1" * 130) + ) + forged, _, _ = _signed_node(sign_with=Account.create()) # signed by someone else + assert not check(forged) + unnamed, _, _ = _signed_node() + call = unnamed.transaction["actions"][0]["FunctionCall"] + arguments = json.loads(base64.b64decode(call["args"])) + del arguments["submitter"] + call["args"] = base64.b64encode(json.dumps(arguments).encode()).decode() + assert not check(unnamed) # a signature without the address it proves + plain = asyncio.run(prepare_manifest(Collection(), list(Collection().rows), SETTINGS)) + with pytest.raises(ValueError): + NearManifest.model_validate(plain.model_dump() | {"submitter_signature": signature}) diff --git a/backend/tests/unit/test_near_publish_service.py b/backend/tests/unit/test_near_publish_service.py new file mode 100644 index 00000000..7dff000a --- /dev/null +++ b/backend/tests/unit/test_near_publish_service.py @@ -0,0 +1,128 @@ +"""Publish requests are owner-bound, single-use, and only accept the expected wallet's signature.""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace + +import pytest +from eth_account import Account +from eth_account.messages import encode_defunct + +from services import near_publish + +WALLET = Account.create() +MESSAGE = "QMesh provenance anchor\nSubmitter: " + WALLET.address + + +class Requests: + def __init__(self, **overrides): + self.doc = { + "_id": "req-1", + "owner_id": "owner-1", + "bundle_ids": ["near-job-1"], + "merkle_root": "ab" * 32, + "submitter": WALLET.address, + "message": MESSAGE, + "status": "pending", + "expires_at": datetime.now(timezone.utc) + timedelta(minutes=5), + } | overrides + + async def find_one_and_update(self, query, update): + doc = self.doc + if ( + doc["_id"] != query["_id"] + or doc["owner_id"] != query["owner_id"] + or doc["status"] != query["status"] + or doc["expires_at"] <= query["expires_at"]["$gt"] + ): + return None + snapshot = dict(doc) + doc.update(update["$set"]) + return snapshot + + async def update_one(self, query, update): + self.doc.update(update["$set"]) + + +@pytest.fixture +def published(monkeypatch): + calls = [] + settings = SimpleNamespace(private_key="set", contract_id="registry.testnet", publisher_id="p") + + async def manifest(collection, ids, settings_, submitter): + return SimpleNamespace( + merkle_root="ab" * 32, + model_dump=lambda: {}, + contract_arguments=lambda: {"submitter": submitter}, + ) + + class Publisher: + def __init__(self, settings_): + pass + + async def anchor(self, arguments): + calls.append(arguments) + return "T" * 44 + + async def attach(*args): + calls.append("attached") + + async def owned(*args): + return [] + + monkeypatch.setattr(near_publish, "near_settings", lambda: settings) + monkeypatch.setattr(near_publish, "prepare_manifest", manifest) + monkeypatch.setattr(near_publish, "owned_rows", owned) + monkeypatch.setattr(near_publish, "NearPublisher", Publisher) + monkeypatch.setattr(near_publish, "attach_manifest", attach) + monkeypatch.setattr( + near_publish.NearManifest, + "model_validate", + lambda data: SimpleNamespace(merkle_root="ab" * 32, contract_arguments=lambda: data), + ) + monkeypatch.setattr( + near_publish, + "NearRegistryAdapter", + lambda s: SimpleNamespace( + explorer_url=lambda tx: "https://testnet.nearblocks.io/txns/" + tx + ), + ) + return calls + + +def _db(requests): + return {near_publish.REQUESTS: requests, "provenance_bundles": object()} + + +def _sign(account=WALLET): + return account.sign_message(encode_defunct(text=MESSAGE)).signature.to_0x_hex() + + +def test_signed_publication_runs_once_and_links_the_explorer(published): + requests = Requests() + result = asyncio.run( + near_publish.complete_publication(_db(requests), "owner-1", "req-1", _sign()) + ) + assert result["wallet_signed"] and result["explorer_url"].endswith("T" * 44) + assert published[0]["submitter_signature"] == _sign() and published[-1] == "attached" + assert requests.doc["status"] == "published" + with pytest.raises(ValueError, match="already used"): + asyncio.run(near_publish.complete_publication(_db(requests), "owner-1", "req-1", _sign())) + + +def test_wrong_wallet_or_owner_never_publishes_and_releases_the_claim(published): + requests = Requests() + with pytest.raises(ValueError, match="Sign with"): + asyncio.run( + near_publish.complete_publication( + _db(requests), "owner-1", "req-1", _sign(Account.create()) + ) + ) + assert published == [] and requests.doc["status"] == "pending" + with pytest.raises(ValueError, match="unknown"): + asyncio.run(near_publish.complete_publication(_db(requests), "intruder", "req-1", _sign())) + expired = Requests(expires_at=datetime.now(timezone.utc) - timedelta(seconds=1)) + with pytest.raises(ValueError, match="expired"): + asyncio.run(near_publish.complete_publication(_db(expired), "owner-1", "req-1", None)) diff --git a/backend/tests/unit/test_near_publisher.py b/backend/tests/unit/test_near_publisher.py new file mode 100644 index 00000000..2894aab7 --- /dev/null +++ b/backend/tests/unit/test_near_publisher.py @@ -0,0 +1,112 @@ +"""NearPublisher signs the registry anchor call correctly and fails closed.""" + +from __future__ import annotations + +import asyncio +import base64 +import hashlib +import json + +import base58 +import httpx +import pytest +from nacl.signing import SigningKey + +from quantum_backend_v2.config.models import NearRegistrySettings +from quantum_backend_v2.provenance.near_publisher import NearPublisher, signing_key + +ACCOUNT = "qmesh-provenance-20261110.testnet" +SEED = bytes(range(32)) +KEY = "ed25519:" + base58.b58encode(SEED + bytes(SigningKey(SEED).verify_key)).decode() +ARGS = {"merkle_root": "ab" * 32, "leaf_count": 2, "hash_profile": "qmesh-provenance-sha256-v1"} +BLOCK_HASH = bytes(range(32, 64)) + + +def _settings(key: str | None = KEY) -> NearRegistrySettings: + return NearRegistrySettings(contract_id=ACCOUNT, publisher_id=ACCOUNT, private_key=key) + + +def _rpc(sent: list[dict], *, chain: str = "testnet", status: dict | None = None): + def handler(request: httpx.Request) -> httpx.Response: + body = json.loads(request.content) + sent.append(body) + method, params = body["method"], body["params"] + if method == "status": + result = {"chain_id": chain} + elif method == "query": + result = {"nonce": 41, "block_hash": base58.b58encode(BLOCK_HASH).decode()} + else: + raw = base64.b64decode(params["signed_tx_base64"]) + digest = hashlib.sha256(raw[:-65]).digest() + result = { + "transaction": {"hash": base58.b58encode(digest).decode()}, + "status": status or {"SuccessValue": ""}, + } + return httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": result}) + + return httpx.AsyncClient(transport=httpx.MockTransport(handler)) + + +def test_signs_the_exact_transaction_it_sends() -> None: + sent: list[dict] = [] + tx_hash = asyncio.run(NearPublisher(_settings(), client=_rpc(sent)).anchor(ARGS)) + + assert [call["method"] for call in sent] == ["status", "query", "send_tx"] + assert sent[1]["params"]["public_key"] == NearPublisher(_settings()).public_key + assert sent[2]["params"]["wait_until"] == "FINAL" + raw = base64.b64decode(sent[2]["params"]["signed_tx_base64"]) + transaction, signature = raw[:-65], raw[-64:] + assert raw[-65] == 0 # ed25519 signature tag + SigningKey(SEED).verify_key.verify(hashlib.sha256(transaction).digest(), signature) + assert base58.b58encode(hashlib.sha256(transaction).digest()).decode() == tx_hash + # nonce is the key's current nonce + 1, bound to the block hash and the anchor arguments + assert (42).to_bytes(8, "little") in transaction + assert BLOCK_HASH in transaction + assert json.dumps(ARGS, separators=(",", ":")).encode() in transaction + + +def test_refuses_to_sign_for_a_non_testnet_rpc() -> None: + sent: list[dict] = [] + with pytest.raises(OSError, match="not on testnet"): + asyncio.run(NearPublisher(_settings(), client=_rpc(sent, chain="mainnet")).anchor(ARGS)) + assert [call["method"] for call in sent] == ["status"] + + +def test_failed_registry_call_is_not_reported_as_published() -> None: + with pytest.raises(OSError, match="rejected the anchor call"): + asyncio.run( + NearPublisher( + _settings(), client=_rpc([], status={"Failure": {"ActionError": {}}}) + ).anchor(ARGS) + ) + + +def test_key_parsing_and_secrecy() -> None: + assert bytes(signing_key(KEY).verify_key) == bytes(SigningKey(SEED).verify_key) + seed_only = "ed25519:" + base58.b58encode(SEED).decode() + assert bytes(signing_key(seed_only).verify_key) == bytes(SigningKey(SEED).verify_key) + mismatched = "ed25519:" + base58.b58encode(SEED + bytes(32)).decode() + with pytest.raises(ValueError, match="do not match"): + signing_key(mismatched) + assert KEY not in repr(_settings()) + with pytest.raises(ValueError): + _settings("not-a-key") + with pytest.raises(ValueError): + NearRegistrySettings(private_key=KEY) # a key without a configured registry + with pytest.raises(ValueError, match="not configured"): + NearPublisher(_settings(None)) + + +def test_a_key_the_publisher_account_does_not_hold_is_reported_clearly() -> None: + def handler(request: httpx.Request) -> httpx.Response: + method = json.loads(request.content)["method"] + result = ( + {"chain_id": "testnet"} + if method == "status" + else {"error": "access key ed25519:... does not exist while viewing", "logs": []} + ) + return httpx.Response(200, json={"jsonrpc": "2.0", "id": 1, "result": result}) + + client = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + with pytest.raises(OSError, match="not an access key of"): + asyncio.run(NearPublisher(_settings(), client=client).anchor(ARGS)) diff --git a/backend/uv.lock b/backend/uv.lock index 56c789f1..763820cd 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -4120,6 +4120,7 @@ version = "0.1.0" source = { editable = "." } dependencies = [ { name = "anthropic" }, + { name = "base58" }, { name = "beanie" }, { name = "biopython" }, { name = "boto3" }, @@ -4184,6 +4185,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "anthropic", specifier = ">=0.18.0" }, + { name = "base58", specifier = ">=2.1.1" }, { name = "beanie", specifier = ">=1.27.0" }, { name = "biopython", specifier = ">=1.84" }, { name = "boto3", specifier = ">=1.34.0" }, diff --git a/frontend/src/app/(main)/agents/chat/page.tsx b/frontend/src/app/(main)/agents/chat/page.tsx index 49272d4a..82226146 100644 --- a/frontend/src/app/(main)/agents/chat/page.tsx +++ b/frontend/src/app/(main)/agents/chat/page.tsx @@ -28,6 +28,7 @@ import { } from "@/features/agentkit/hooks/use-chat-sessions"; import { AttestationBadge } from "@/features/agent/components/conversation-panel"; import { ApprovalActions } from "@/features/agentkit/components/approval-actions"; +import { publicationMessage, signAndPublish } from "@/features/agentkit"; import { useStorageExports, type StorageExport } from "@/features/agentkit/hooks/use-storage-exports"; import { StorageExports } from "@/features/agentkit/components/storage-exports"; @@ -203,6 +204,28 @@ function AgentsChatInner() { } catch { /* The approval card shows the mutation error. */ } }; + // The agent's NEAR card: sign with the connected wallet, publish, then post the explorer link. + const publishFromChat = async (approval: NonNullable) => { + if (!activeSessionId || !approval.request_id || loading) return; + pushMessage({ role: "user", content: approval.action }, activeSessionId); + setLoading(true); + try { + const result = await signAndPublish({ + request_id: approval.request_id, + message: approval.message, + submitter: approval.submitter, + }); + pushMessage({ role: "agent", content: publicationMessage(result) }, activeSessionId); + } catch (err) { + pushMessage( + { role: "agent", content: `NEAR publishing did not complete: ${(err instanceof Error ? err.message : "unknown error").replace(/\.+$/, "")}. Nothing was published; you can ask me to try again.` }, + activeSessionId, + ); + } finally { + setLoading(false); + } + }; + const send = async (text: string) => { if (!text.trim() || loading) return; // Wait for session restore (effect below) before first send when this agent already has sessions. @@ -430,7 +453,9 @@ function AgentsChatInner() { showSummary={msg.content.trim() !== msg.approval.summary.trim()} disabled={loading} onDecide={(approved) => - send(approved ? `Approved. Go ahead: ${msg.approval!.action}` : "Declined. Do not do that.") + approved && msg.approval!.kind === "near_publish" + ? publishFromChat(msg.approval!) + : send(approved ? `Approved. Go ahead: ${msg.approval!.action}` : "Declined. Do not do that.") } /> )} diff --git a/frontend/src/app/(main)/finance/[jobId]/page.tsx b/frontend/src/app/(main)/finance/[jobId]/page.tsx index ab5807c7..b2000afc 100644 --- a/frontend/src/app/(main)/finance/[jobId]/page.tsx +++ b/frontend/src/app/(main)/finance/[jobId]/page.tsx @@ -6,6 +6,7 @@ import { Skeleton } from "@/components/ui/skeleton"; import { PageHeader } from "@/shared/components/layout/page-header"; import { useFinanceJob } from "@/features/finance/hooks/use-finance-job"; import { ShareToVaultButton } from "@/features/ipfs/components/share-to-vault-button"; +import { PublishToNearButton } from "@/features/agentkit"; import { FinanceResultSummary } from "@/features/finance/components/finance-result-summary"; export default function FinanceDetailPage() { @@ -22,11 +23,14 @@ export default function FinanceDetailPage() { glow="emerald" > {data && data.status.toLowerCase() === "completed" && ( - } - name={data.jobId} - type="run" - /> +
+ + } + name={data.jobId} + type="run" + /> +
)}
diff --git a/frontend/src/app/api/agentkit/near/jobs/[jobId]/route.ts b/frontend/src/app/api/agentkit/near/jobs/[jobId]/route.ts new file mode 100644 index 00000000..fb4eb91b --- /dev/null +++ b/frontend/src/app/api/agentkit/near/jobs/[jobId]/route.ts @@ -0,0 +1,15 @@ +import { NextResponse } from "next/server"; +import { BACKEND_AGENTKIT } from "@/constants/backend"; +import { agentBackendFetch } from "@/features/agentkit/server/backend-fetch"; + +type Params = { params: Promise<{ jobId: string }> }; + +export async function GET(_request: Request, { params }: Params) { + try { + const { jobId } = await params; + const res = await agentBackendFetch(BACKEND_AGENTKIT.NEAR_STATUS(jobId)); + return NextResponse.json(await res.json(), { status: res.status }); + } catch { + return NextResponse.json({ error: "Backend unreachable" }, { status: 502 }); + } +} diff --git a/frontend/src/app/api/agentkit/near/prepare/route.ts b/frontend/src/app/api/agentkit/near/prepare/route.ts new file mode 100644 index 00000000..fcc40f13 --- /dev/null +++ b/frontend/src/app/api/agentkit/near/prepare/route.ts @@ -0,0 +1,16 @@ +import { NextResponse } from "next/server"; +import { BACKEND_AGENTKIT } from "@/constants/backend"; +import { agentBackendFetch } from "@/features/agentkit/server/backend-fetch"; + +export async function POST(request: Request) { + try { + const res = await agentBackendFetch(BACKEND_AGENTKIT.NEAR_PREPARE, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(await request.json()), + }); + return NextResponse.json(await res.json(), { status: res.status }); + } catch { + return NextResponse.json({ error: "Backend unreachable" }, { status: 502 }); + } +} diff --git a/frontend/src/app/api/agentkit/near/requests/[id]/route.ts b/frontend/src/app/api/agentkit/near/requests/[id]/route.ts new file mode 100644 index 00000000..d1a858d7 --- /dev/null +++ b/frontend/src/app/api/agentkit/near/requests/[id]/route.ts @@ -0,0 +1,19 @@ +import { NextResponse } from "next/server"; +import { BACKEND_AGENTKIT } from "@/constants/backend"; +import { agentBackendFetch } from "@/features/agentkit/server/backend-fetch"; + +type Params = { params: Promise<{ id: string }> }; + +export async function POST(request: Request, { params }: Params) { + try { + const { id } = await params; + const res = await agentBackendFetch(BACKEND_AGENTKIT.NEAR_PUBLISH(id), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(await request.json()), + }); + return NextResponse.json(await res.json(), { status: res.status }); + } catch { + return NextResponse.json({ error: "Backend unreachable" }, { status: 502 }); + } +} diff --git a/frontend/src/constants/api.ts b/frontend/src/constants/api.ts index 6729b854..8622583a 100644 --- a/frontend/src/constants/api.ts +++ b/frontend/src/constants/api.ts @@ -104,4 +104,9 @@ export const API_AGENTKIT = { AGENTS: "/api/agentkit/agents", AGENT_ANALYZE: (id: string) => `/api/agentkit/agents/${id}/analyze` as const, NOTIFICATIONS: "/api/agentkit/notifications", + NEAR_PREPARE: "/api/agentkit/near/prepare", + NEAR_PUBLISH: (requestId: string) => + `/api/agentkit/near/requests/${encodeURIComponent(requestId)}` as const, + NEAR_STATUS: (jobId: string) => + `/api/agentkit/near/jobs/${encodeURIComponent(jobId)}` as const, } as const; diff --git a/frontend/src/constants/backend.ts b/frontend/src/constants/backend.ts index 8d9ad897..cf93ced3 100644 --- a/frontend/src/constants/backend.ts +++ b/frontend/src/constants/backend.ts @@ -81,6 +81,11 @@ export const BACKEND = { } as const; export const BACKEND_AGENTKIT = { + NEAR_PREPARE: `${BASE_URL}/api/v1/near-provenance/prepare`, + NEAR_PUBLISH: (requestId: string) => + `${BASE_URL}/api/v1/near-provenance/requests/${encodeURIComponent(requestId)}` as const, + NEAR_STATUS: (jobId: string) => + `${BASE_URL}/api/v1/near-provenance/jobs/${encodeURIComponent(jobId)}` as const, WALLET: `${BASE_URL}/api/v1/wallet`, WALLET_CREATE: `${BASE_URL}/api/v1/wallet/create`, WALLET_BALANCE: `${BASE_URL}/api/v1/wallet/balance`, diff --git a/frontend/src/constants/query-keys.ts b/frontend/src/constants/query-keys.ts index 85e3c522..e122a30e 100644 --- a/frontend/src/constants/query-keys.ts +++ b/frontend/src/constants/query-keys.ts @@ -76,6 +76,7 @@ export const QUERY_KEYS = { export const QUERY_KEYS_AGENTKIT = { + nearPublication: (jobId: string) => ["agentkit", "near-publication", jobId] as const, wallet: () => ["agentkit", "wallet"] as const, ensResolve: (name: string, fresh: boolean) => ["agentkit", "ens", "resolve", name, fresh] as const, diff --git a/frontend/src/features/agentkit/components/publish-to-near-button.tsx b/frontend/src/features/agentkit/components/publish-to-near-button.tsx new file mode 100644 index 00000000..9e5db6d7 --- /dev/null +++ b/frontend/src/features/agentkit/components/publish-to-near-button.tsx @@ -0,0 +1,58 @@ +"use client"; + +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { ExternalLink, Loader2, ShieldCheck } from "lucide-react"; +import { toast } from "sonner"; +import { Button } from "@/components/ui/button"; +import { QUERY_KEYS_AGENTKIT } from "@/constants/query-keys"; +import { fetchNearPublication, publishExperiments } from "@/features/agentkit/lib/near-publish"; + +/** Header action on a finished experiment: anchor its result on NEAR testnet, then link it. */ +export function PublishToNearButton({ jobId }: { jobId: string }) { + const queryClient = useQueryClient(); + const key = QUERY_KEYS_AGENTKIT.nearPublication(jobId); + const status = useQuery({ queryKey: key, queryFn: () => fetchNearPublication(jobId) }); + const publish = useMutation({ + mutationFn: () => publishExperiments([jobId]), + onSuccess: (result) => { + queryClient.setQueryData(key, result); + toast.success("Published to NEAR testnet", { + action: { label: "View", onClick: () => window.open(result.explorer_url, "_blank", "noopener") }, + }); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : "NEAR publishing failed"), + }); + + if (status.isPending) return null; + if (status.data?.published && status.data.explorer_url) { + return ( + + + On NEAR testnet + + + ); + } + return ( + + ); +} diff --git a/frontend/src/features/agentkit/hooks/use-chat-sessions.ts b/frontend/src/features/agentkit/hooks/use-chat-sessions.ts index 4d21d1b7..71dc377f 100644 --- a/frontend/src/features/agentkit/hooks/use-chat-sessions.ts +++ b/frontend/src/features/agentkit/hooks/use-chat-sessions.ts @@ -16,7 +16,15 @@ export type AttestationSummary = { }; /** The agent paused for the user's go-ahead (backend `request_approval` tool). */ -export type ApprovalRequest = { summary: string; action: string }; +export type ApprovalRequest = { + summary: string; + action: string; + /** near_publish: confirm by wallet signature; the app publishes, not the agent. */ + kind?: "near_publish" | null; + request_id?: string | null; + message?: string | null; + submitter?: string | null; +}; export type ChatMessage = { role: "user" | "agent"; diff --git a/frontend/src/features/agentkit/index.ts b/frontend/src/features/agentkit/index.ts index 0777af20..054267dc 100644 --- a/frontend/src/features/agentkit/index.ts +++ b/frontend/src/features/agentkit/index.ts @@ -23,3 +23,6 @@ export { truncateAddress, } from "./lib/ens"; export { useAgentLlmProvider } from "./llm-provider/use-agent-llm-provider"; +export { PublishToNearButton } from "./components/publish-to-near-button"; +export { signAndPublish, publicationMessage } from "./lib/near-publish"; +export type { NearPublication, NearPublishRequest } from "./lib/near-publish"; diff --git a/frontend/src/features/agentkit/lib/near-publish.ts b/frontend/src/features/agentkit/lib/near-publish.ts new file mode 100644 index 00000000..337c67d2 --- /dev/null +++ b/frontend/src/features/agentkit/lib/near-publish.ts @@ -0,0 +1,100 @@ +import { API_AGENTKIT } from "@/constants/api"; + +/** What the backend needs confirmed before it signs the NEAR `anchor` call. */ +export type NearPublishRequest = { + request_id: string; + /** Text the user's Ethereum wallet signs; null when the account has no linked wallet. */ + message?: string | null; + submitter?: string | null; +}; + +export type NearPublication = { + published: true; + explorer_url: string; + tx_hash: string; + merkle_root: string; + submitter?: string | null; + wallet_signed?: boolean; +}; + +type Prepared = + | NearPublication + | (NearPublishRequest & { status: "awaiting_user_confirmation" }) + | { status: "awaiting_signature" }; + +async function call(url: string, init?: RequestInit): Promise { + const res = await fetch(url, init); + const body = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(body.message ?? body.detail ?? body.error ?? "NEAR publishing failed"); + return body as T; +} + +function utf8Hex(text: string): string { + return "0x" + Array.from(new TextEncoder().encode(text), (b) => b.toString(16).padStart(2, "0")).join(""); +} + +/** + * Ask the connected wallet (MetaMask etc.) to sign the publication statement, then let the + * backend publish. Without a browser wallet it publishes unsigned: the address is still shown + * as the submitter, but not proven by a signature. + */ +export async function signAndPublish(request: NearPublishRequest): Promise { + let signature: string | null = null; + const wallet = typeof window === "undefined" ? undefined : window.ethereum; + if (request.message && request.submitter && wallet) { + const accounts = (await wallet.request({ method: "eth_requestAccounts" })) as string[]; + const account = accounts.find((a) => a.toLowerCase() === request.submitter!.toLowerCase()); + if (!account) { + throw new Error( + `Switch your wallet to ${request.submitter}; these experiments are attributed to that address.`, + ); + } + signature = (await wallet.request({ + method: "personal_sign", + params: [utf8Hex(request.message), account], + })) as string; + } + return call(API_AGENTKIT.NEAR_PUBLISH(request.request_id), { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ signature }), + }); +} + +/** Prepare, sign and publish experiments in one go (Lab page buttons). */ +export async function publishExperiments(jobIds: string[]): Promise { + const prepared = await call(API_AGENTKIT.NEAR_PREPARE, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ job_ids: jobIds }), + }); + if ("published" in prepared) return prepared; + if (prepared.status === "awaiting_signature") { + throw new Error("Automatic NEAR publishing is not configured on this server yet."); + } + return signAndPublish(prepared); +} + +export async function fetchNearPublication( + jobId: string, +): Promise { + return call(API_AGENTKIT.NEAR_STATUS(jobId)); +} + +/** Chat message shown after a successful publication. */ +export function publicationMessage(result: NearPublication): string { + const by = result.submitter + ? result.wallet_signed + ? `Signed by your wallet \`${result.submitter}\`.` + : `Attributed to \`${result.submitter}\` (not wallet-signed).` + : "No wallet linked, so no submitter address is attached."; + return [ + "**Published to NEAR testnet.**", + "", + `- Transaction: [${result.tx_hash.slice(0, 10)}…](${result.explorer_url})`, + `- Merkle root: \`${result.merkle_root}\``, + `- ${by}`, + "", + `[View on NearBlocks](${result.explorer_url})`, + ].join("\n"); +} diff --git a/frontend/src/features/pharma/components/pharma-live-canvas.tsx b/frontend/src/features/pharma/components/pharma-live-canvas.tsx index 8bc6cb4a..5cee9220 100644 --- a/frontend/src/features/pharma/components/pharma-live-canvas.tsx +++ b/frontend/src/features/pharma/components/pharma-live-canvas.tsx @@ -1,5 +1,6 @@ "use client"; +import { PublishToNearButton } from "@/features/agentkit"; import dynamic from "next/dynamic"; import { useEffect, useRef, useState } from "react"; import { @@ -326,6 +327,7 @@ export function PharmaLiveCanvas({ job, onCancel, isCancelling }: Props) {
+ {isCompleted && } {isRunning && (
diff --git a/frontend/src/features/runs/components/run-detail-page-client.tsx b/frontend/src/features/runs/components/run-detail-page-client.tsx index 60d7d7c4..3cb98779 100644 --- a/frontend/src/features/runs/components/run-detail-page-client.tsx +++ b/frontend/src/features/runs/components/run-detail-page-client.tsx @@ -1,4 +1,5 @@ "use client"; +import { PublishToNearButton } from "@/features/agentkit"; import { useParams } from "next/navigation"; import { Cpu, Zap, BarChart3, Database, CheckCircle2, XCircle, Clock, @@ -292,6 +293,8 @@ export function RunDetailPageClient() { glow="violet" > {run && run.status.toLowerCase() === "completed" && ( +
+ +
)}