Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions backend/docs/near-provenance.md
Original file line number Diff line number Diff line change
Expand Up @@ -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-<job_id>` 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:
Expand Down
1 change: 1 addition & 0 deletions backend/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
7 changes: 7 additions & 0 deletions backend/src/api/v1/agents.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
92 changes: 92 additions & 0 deletions backend/src/api/v1/near_publish.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading