zkproofport-ai
proofport-ai
Инфраструктура ZK-доказательств для ZKProofport, ориентированная на агентов. Автономный сервис, который генерирует и проверяет доказательства с нулевым разглашением внутри AWS Nitro Enclave со сквозным шифрованием — сервер выступает в роли слепого ретранслятора (blind relay) и никогда не видит входные данные доказательств.
Архитектура
Client (AI Agent / SDK)
│
│ 1. POST /api/v1/prove → 402 { nonce, price, teePublicKey }
│ 2. Sign EIP-3009 USDC payment
│ 3. Encrypt inputs with TEE X25519 public key (ECIES)
│ 4. POST /api/v1/prove + X-Payment-TX + X-Payment-Nonce + encrypted_payload
│
▼
┌─────────────────────────────────────┐
│ Node.js Server (port 4002) │
│ ─ Verify USDC payment on-chain │
│ ─ Blind relay: pass encrypted │
│ payload to enclave via vsock │
│ ─ Return proof + TEE attestation │
└────────────┬────────────────────────┘
│ vsock
▼
┌─────────────────────────────────────┐
│ AWS Nitro Enclave │
│ ─ X25519 key pair (bound to NSM) │
│ ─ Decrypt inputs (AES-256-GCM) │
│ ─ bb prove (Barretenberg CLI) │
│ ─ NSM attestation of proof hash │
└─────────────────────────────────────┘Ключевые свойства:
Сквозное шифрование (E2E) — X25519 ECDH + AES-256-GCM. В режиме
nitroвходные данные в открытом виде отклоняются.Слепой ретранслятор — Хост Node.js не может прочитать входные данные доказательства. Расшифровка происходит только внутри анклава.
Оплата x402 — Одношаговый процесс: вызов 402 → оплата в USDC → генерация доказательства. Без промежуточного ПО.
Аппаратная аттестация — Документ аттестации NSM привязывает открытый ключ TEE к измерению анклава (PCRs).
Related MCP server: AgentStamp
Структура каталогов
proofport-ai/
├── src/
│ ├── index.ts # Express server entry (port 4002)
│ ├── logger.ts # Pino logger
│ ├── swagger.ts # OpenAPI spec
│ ├── tracing.ts # OpenTelemetry tracing
│ ├── a2a/
│ │ ├── agentCard.ts # /.well-known/agent.json, agent-card.json
│ │ ├── proofportExecutor.ts # A2A task executor
│ │ └── redisTaskStore.ts # Redis-backed task persistence
│ ├── chat/
│ │ ├── geminiClient.ts # Gemini API client
│ │ ├── llmProvider.ts # LLM provider interface
│ │ ├── multiProvider.ts # Multi-provider routing
│ │ └── openaiClient.ts # OpenAI API client
│ ├── circuit/
│ │ └── artifactManager.ts # Circuit artifact download/cache
│ ├── config/
│ │ ├── index.ts # Environment config
│ │ ├── circuits.ts # Circuit metadata
│ │ └── contracts.ts # Deployed contract addresses
│ ├── identity/
│ │ ├── agentAuth.ts # Agent JWT authentication
│ │ ├── autoRegister.ts # ERC-8004 auto-registration
│ │ ├── register.ts # Identity registration
│ │ └── reputation.ts # Reputation management
│ ├── input/
│ │ ├── attestationFetcher.ts # EAS GraphQL attestation fetch
│ │ ├── inputBuilder.ts # Circuit input construction
│ │ └── merkleTree.ts # Merkle tree builder
│ ├── mcp/
│ │ ├── server.ts # StreamableHTTP MCP server
│ │ └── stdio.ts # stdio MCP server (local use)
│ ├── payment/
│ │ └── freeTier.ts # Payment mode config
│ ├── proof/
│ │ ├── proofRoutes.ts # x402 single-step proof API
│ │ ├── guideBuilder.ts # Dynamic proof generation guide
│ │ ├── paymentVerifier.ts # On-chain USDC payment verification
│ │ ├── sessionManager.ts # Proof session/nonce management
│ │ └── types.ts
│ ├── prover/
│ │ ├── bbProver.ts # bb CLI direct prover
│ │ ├── tomlBuilder.ts # Prover.toml builder
│ │ └── verifier.ts # On-chain verification (ethers v6)
│ ├── redis/
│ │ ├── client.ts # Redis client
│ │ ├── cleanupWorker.ts # Expired data cleanup
│ │ ├── constants.ts # Redis key prefixes
│ │ ├── proofCache.ts # Proof result caching
│ │ ├── proofResultStore.ts # Proof result persistence
│ │ └── rateLimiter.ts # Rate limiting
│ ├── skills/
│ │ ├── skillHandler.ts # Skill routing
│ │ └── flowGuidance.ts # Step-by-step flow guidance
│ ├── tee/
│ │ ├── index.ts # TEE mode config
│ │ ├── attestation.ts # NSM attestation validation (COSE Sign1)
│ │ ├── detect.ts # TEE environment detection
│ │ ├── enclaveBuilder.ts # Enclave image builder
│ │ ├── enclaveClient.ts # Nitro Enclave vsock client
│ │ ├── encryption.ts # AES-256-GCM encryption utilities
│ │ ├── teeKeyExchange.ts # X25519 ECDH key exchange
│ │ └── validationSubmitter.ts # TEE validation on-chain
│ └── types/
│ └── index.ts
├── packages/
│ ├── sdk/ # @zkproofport-ai/sdk (npm)
│ └── mcp/ # @zkproofport-ai/mcp (npm)
├── aws/
│ ├── enclave-server.ts # TypeScript TEE prover (Nitro Enclave)
│ ├── Dockerfile.enclave # Enclave image
│ ├── deploy-blue-green.sh # Zero-downtime deployment
│ ├── boot-active-slot.sh # Systemd boot script
│ ├── stop-active-slot.sh # Systemd stop script
│ ├── build-enclave.sh # Enclave build helper
│ ├── ec2-setup.sh # EC2 instance setup
│ ├── Caddyfile # Reverse proxy config
│ ├── docker-compose.aws.yml # AWS Docker Compose
│ ├── vsock-bridge.py # vsock-to-TCP bridge
│ └── systemd/ # Systemd service files
├── sign-page/ # Next.js signing page (WalletConnect)
├── tests/
│ ├── e2e/ # Full E2E tests (REST, MCP, A2A, proof, verify)
│ ├── a2a/ # A2A unit tests
│ ├── identity/ # ERC-8004 identity tests
│ ├── integration/ # Integration tests
│ ├── payment/ # Payment tests
│ ├── tee/ # TEE tests
│ └── *.test.ts # Unit tests
├── docker-compose.yml # Local dev: server + redis
├── docker-compose.test.yml # Test stack: + a2a-ui + Phoenix
├── Dockerfile # Node.js server image
└── README.mdБыстрый старт
npm (Разработка)
npm install
npm run dev # Hot reload with tsx
npm run build # Build TypeScript
npm start # Production
npm test # Run tests
npm run test:e2e # E2E tests against Docker stackDocker Compose (Локально)
docker compose up --build # Start redis + server
docker compose down # Stop
docker compose down -v # Reset dataПорт 4002: Сервер Node.js
Порт 6380 (хост) → 6379 (контейнер): Redis
Сквозное шифрование (Слепой ретранслятор)
Входные данные доказательств зашифрованы сквозным шифрованием между клиентом и Nitro Enclave. Сервер Node.js передает зашифрованный блоб, не читая его.
Протокол: X25519 ECDH + AES-256-GCM (паттерн ECIES)
TEE генерирует пару ключей X25519 при запуске, привязывает открытый ключ к аттестации NSM
Клиент получает открытый ключ TEE из ответа 402, проверяет аттестацию
Клиент генерирует эфемерную пару ключей X25519, вычисляет общий секрет ECDH, выводит ключ AES через SHA-256
Клиент шифрует входные данные с помощью AES-256-GCM, отправляет
{ ephemeralPublicKey, iv, ciphertext, authTag, keyId }Сервер передает зашифрованный конверт в анклав через vsock (слепой ретранслятор)
Анклав расшифровывает, генерирует доказательство, возвращает доказательство + аттестацию NSM
Принудительное применение: В режиме nitro входные данные в открытом виде отклоняются с ошибкой PLAINTEXT_REJECTED.
Процесс оплаты x402
Одношаговый атомарный процесс — без промежуточного ПО, без сессий:
POST /api/v1/prove { circuit, inputs }
↓
402 { nonce, price, payTo, teePublicKey }
↓
Client signs EIP-3009 TransferWithAuthorization (USDC)
↓
POST /api/v1/prove { circuit, encrypted_payload }
+ X-Payment-TX: <txHash>
+ X-Payment-Nonce: <nonce>
↓
200 { proof, publicInputs, proofWithInputs, attestation, timing, verification }Режимы оплаты:
Режим | Сеть | Эффект |
| Нет | Все запросы бесплатны |
| Base Sepolia | Требуется оплата в USDC (тестовая сеть) |
| Base Mainnet | Требуется оплата в USDC (основная сеть) |
REST-эндпоинты
Эндпоинт | Метод | Назначение |
| GET | Проверка работоспособности + статус TEE + режим оплаты |
| POST | Одношаговая генерация доказательства x402 |
| GET | Динамическое руководство по генерации (JSON) |
| POST | Эндпоинт StreamableHTTP MCP |
| POST | Эндпоинт A2A JSON-RPC |
| GET | Карточка агента OASF |
| GET | Карточка агента A2A |
| GET | Обнаружение MCP |
| GET | Swagger UI |
| GET | Спецификация OpenAPI |
Инструменты MCP
Доступны через /mcp (StreamableHTTP) или локальный пакет @zkproofport-ai/mcp (stdio):
Инструмент | Назначение |
| Генерация доказательства «все в одном» (оплата x402 + автоопределение E2E шифрования) |
| Проверка доказательства в сети |
| Список доступных схем (circuits) |
| Запрос вызова 402 (пошаговый процесс) |
| Оплата USDC x402 (пошаговый процесс) |
| Отправка входных данных доказательства (пошаговый процесс) |
| Подготовка входных данных схемы (пошаговый процесс) |
Пакеты npm
@zkproofport-ai/sdk — TypeScript SDK for proof generation (ethers v6)
@zkproofport-ai/mcp — Local MCP server for AI agents (stdio transport)Установите MCP-сервер для использования локальным AI-агентом:
npm install @zkproofport-ai/mcp
npx zkproofport-mcp # Starts stdio MCP serverСистема руководств
GET /api/v1/guide/:circuit возвращает подробное JSON-руководство для клиентских AI-агентов по подготовке всех входных данных доказательства. Включает:
Пошаговые инструкции с примерами кода
Константы (ключи аттестатора, адреса контрактов, UID схемы EAS)
Формулы (вычисление nullifier, хеш сигнала, построение дерева Меркла)
Схему входных данных с типами и описаниями
Шаблоны GraphQL-запросов EAS
Схемы используют псевдонимы: coinbase_kyc → coinbase_attestation, coinbase_country → coinbase_country_attestation, oidc_domain → oidc_domain_attestation.
Протокол A2A
Эндпоинт A2A v0.3 JSON-RPC по адресу POST /a2a:
Метод | Назначение |
| Отправка задачи доказательства (блокирующая) |
| Отправка задачи доказательства (SSE стриминг) |
| Запрос статуса задачи |
| Отмена запущенной задачи |
| Повторная подписка на события задачи |
Карточка агента по адресу /.well-known/agent.json предоставляет ончейн-идентификацию ERC-8004 и обнаружение возможностей.
Интеграция TEE (AWS Nitro Enclave)
Режим | Поведение |
| Стандартный Linux, без TEE, разрешен открытый текст |
| AWS Nitro Enclave, аппаратная аттестация, принудительное E2E шифрование |
Анклав запускает aws/enclave-server.ts (скомпилированный в dist/aws/enclave-server.js), который выполняет bb prove с параметром --oracle_hash keccak (необходимо для совместимости с верификатором Solidity). Аттестация NSM привязывает хеш доказательства и открытый ключ TEE к измерению анклава (PCR0/PCR1/PCR2).
Цепочка проверки аттестации: AWS Nitro Root CA → Regional → Zonal → Instance → Leaf-сертификат, проверяется подписью COSE ES384.
Поддерживаемые схемы (Circuits)
Coinbase KYC (coinbase_attestation)
Доказывает, что владелец прошел верификацию KYC в Coinbase.
Псевдонимы:
coinbase_kyc,coinbase_attestationПубличные входные данные: address, scope
Nullifier: Да (конфиденциальность, защита от повторов)
Coinbase Country (coinbase_country_attestation)
Доказывает, что страна KYC владельца совпадает с аттестацией.
Псевдонимы:
coinbase_country,coinbase_country_attestationПубличные входные данные: address, country, scope
Nullifier: Да (конфиденциальность, защита от повторов)
OIDC Domain (oidc_domain_attestation)
Доказывает, что владелец владеет адресом электронной почты в определенном домене через проверку OIDC JWT.
Псевдонимы:
oidc_domain,oidc_domain_attestationТип входных данных: OIDC JWT (
id_tokenот Google и т.д.)Публичные входные данные: domain hash, scope
Nullifier: Да (конфиденциальность, защита от повторов)
Адреса контрактов
Base Sepolia (Тестовая сеть)
Контракт | Адрес |
KYC Verifier |
|
Country Verifier |
|
ERC-8004 Identity |
|
ERC-8004 Reputation |
|
Base Mainnet (Основная сеть)
Контракт | Адрес |
ERC-8004 Identity |
|
ERC-8004 Reputation |
|
Идентификация агента ERC-8004
Агент автоматически регистрируется в сети при запуске через контракт ERC-8004 Identity. Рейтинг репутации увеличивается после каждой успешной генерации доказательства.
Переменные окружения
Обязательные
Переменная | Описание |
| Строка подключения к Redis |
| RPC-эндпоинт сети Base |
| RPC для проверки доказательств |
| GraphQL-эндпоинт EAS для запросов аттестаций |
| Приватный ключ кошелька агента (64 шестнадцатеричных символа, без 0x) |
|
|
| Публичный URL сервиса (для карточки агента) |
Опциональные
Переменная | По умолчанию | Описание |
|
| Порт сервера Express |
|
| Среда Node |
|
| Путь к CLI Barretenberg |
|
| Путь к CLI Nargo |
|
| Директория артефактов схем |
| (GitHub raw URL) | URL для загрузки артефактов схем |
|
|
|
| — | CID анклава Nitro (требуется при |
|
| Порт анклава Nitro |
|
| Включить проверку аттестации |
| — | Кошелек оператора (требуется при включенной оплате) |
|
| Цена за одно доказательство (USD) |
| — | Контракт ERC-8004 Identity |
| — | Контракт ERC-8004 Reputation |
| — | API-ключ Gemini для чата |
| — | API-ключ OpenAI для чата |
| — | Эндпоинт Phoenix OTLP для трассировки |
|
| Версия агента |
Развертывание (AWS Nitro Enclave)
proofport-ai развертывается на AWS EC2 с поддержкой Nitro Enclave. Развертывание использует blue-green переключение слотов для обеспечения нулевого времени простоя.
Blue-Green развертывание
aws/deploy-blue-green.shДва слота: blue (порты 4002/3200) и green (порты 4003/3201)
Активный слот отслеживается в
/opt/proofport-ai/active-slotПерезагрузка Caddy (не перезапуск) переключает трафик
Ожидание завершения текущих запросов перед переключением (до 660 секунд для генерации доказательства)
Автоматический откат, если проверка работоспособности нового контейнера не проходит
Инфраструктура
Caddy — Обратный прокси с HTTPS (Cloudflare Full SSL)
systemd — Сервисы:
proofport-ai,proofport-ai-redis,proofport-ai-enclave,vsock-bridgeCloudWatch — Драйвер логов
awslogs, хранение 30 днейGitHub Actions — Воркфлоу
deploy-ai-aws.yml(НЕdeploy.yml, который предназначен для GCP)
Запуск / Остановка
aws/boot-active-slot.sh # Start active slot containers
aws/stop-active-slot.sh # Stop active slot containersТестирование
npm test # Unit tests
npm run test:e2e # E2E against Docker stack
npm run test:watch # Watch modeТестирование A2A (a2a-ui + Phoenix)
docker compose -f docker-compose.yml -f docker-compose.test.yml up --build -dСервис | URL | Назначение |
proofport-ai |
| Сервер агента |
a2a-ui |
| Веб-интерфейс для тестирования A2A |
Phoenix |
| Визуализация трассировки |
Фиксация версий
Инструмент | Версия |
bb (Barretenberg) |
|
nargo |
|
ethers |
|
@modelcontextprotocol/sdk |
|
Node.js | 20 LTS |
Лицензия
Apache 2.0
Available Tools
7 toolsgenerate_proofA
All-in-one ZK proof generation. Handles: prepare inputs, request challenge, and submit proof in a single call. Use this when you want the simplest path to a proof. For fine-grained control over each step, use prepare_inputs, request_challenge, and submit_proof individually.
CIRCUITS:
"coinbase_kyc": Proves the user passed Coinbase KYC verification, optionally binding the wallet's signature to ONE EIP-712 action (as giwa_attestation). Without action it signs the request signal hash.
"coinbase_country": Proves the user's country of residence is (or is not) in a given list, optionally binding the wallet's signature to ONE EIP-712 action (as coinbase_kyc). Requires country_list and is_included.
"oidc_domain": Proves the user authenticated via OIDC and their email belongs to a specific domain. Requires jwt and scope.
"human_passport": Proves the wallet holds an unexpired Human Passport score at or above min_score, without revealing the wallet or the exact score; optionally binds ONE EIP-712 action (as coinbase_kyc). Requires min_score and chain (the chain id the person recorded the score on).
"giwa_attestation": GIWA attestation, optionally binding the wallet's signature to ONE EIP-712 action. Without action it signs the request signal hash. With one, the proof carries that action's hash, so a contract can check WHICH instruction was authorised -- not merely that somebody eligible signed something. Uses a GIWA-attested wallet; verified on GIWA Sepolia (chain 91342).
WITH ACTION: Returns awaiting_approval with an approval URL for the HUMAN to review and sign in their wallet. Keep the request parameters unchanged, query get_action_approval, then repeat with approval_id when approved. ATTESTATION_KEY cannot authorize an action on the human's behalf. Ordinary proofs without action retain automatic signing.
SIGNAL HASH: without an action the wallet signs signal_hash = keccak256(scope ++ circuitId ++ request_id). It contains no wallet address. Pass request_id when the verifier issued one; otherwise a fresh one is minted and returned as requestId.
NULLIFIER: wallet circuits require oprf_domain (the service the proof is for). The nullifier is one per wallet per (oprf_domain, scope), computed with the OPRF network before the wallet signs; a service whose environment has no OPRF network refuses before anything is signed or paid.
RETURNS: awaiting_approval or the full ProofResult with proof bytes, public inputs, timing information, and the requestId, scope and oprfDomain the proof answers. Use verify_proof separately to verify on-chain.
Inputs: scope (required), circuit (required), jwt, chain, +12 more.
get_action_approvalA
Read the status of a human wallet approval created by this MCP client. This operation never starts a proof or payment.
Inputs: approval_id (required).
get_supported_circuitsA
List all ZK circuits supported by ZKProofport, including verifier addresses and authorized signers. No parameters required. Call this first to discover available circuits before starting proof generation.
Inputs: no named parameters.
prepare_inputsA
Step 1 of the step-by-step flow. WITH ACTION: human wallet approval is required; returns awaiting_approval until resumed with approval_id. Approved action witnesses stay in private local storage; pass the returned prepared_inputs_id to submit_proof. The action hash is public: an action whose proof is shown off-chain should not contain the wallet's address. WITHOUT ACTION: the credential key signs signal_hash = keccak256(scope ++ circuitId ++ request_id), no wallet address; the first result block is the inputs for submit_proof, the second names request_id and scope for the verifier. Handle private witness inputs only in trusted local code, never expose them to the dApp, model or logs. Call this BEFORE request_challenge. For oidc_domain provide jwt and scope.
Inputs: scope (required), circuit (required), jwt, chain, +8 more.
request_challengeA
Step 2 of the step-by-step flow: Request a challenge from the server. Pass inputs: {} to discover the live payment offers, nonce and optional TEE key without transmitting private witness inputs. You MUST pass the returned "nonce" to submit_proof — without it the server just issues another challenge. MCP submit_proof does not sign payments or encrypt inputs; use generate_proof or the SDK for paid/encrypted orchestration.
Inputs: inputs (required), circuit (required).
submit_proofA
Step 3 of the step-by-step flow: Submit prepared inputs to generate the ZK proof. The TEE server runs the Noir circuit and returns the UltraHonk proof. This step may take 30-90 seconds. The TEE server builds Prover.toml from these inputs.
You MUST pass the nonce returned by request_challenge. POST /api/v1/prove answers every request that arrives without that nonce with a fresh 402 challenge, so a submission that omits it can never produce a proof.
Inputs: nonce (required), circuit (required), inputs, prepared_inputs_id.
verify_proofA
Step 4 (optional): Verify a ZK proof on-chain against ZKProofport's own pinned verifier contract for the circuit and chain. Pass the full generate_proof result object directly. The result's verifierAddress is only compared with the pinned one: a different address is refused, never called. Issuer anchors are checked too (OIDC provider key against Google/Microsoft's published keys; Coinbase/GIWA signer-list root). Returns { valid: true } if the proof is valid, otherwise { valid: false, error }.
Inputs: result (required), min_score.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
generate_proof deliberately overlaps with the prepare_inputs → request_challenge → submit_proof trio, but the description explicitly frames it as the convenience path versus fine-grained control, and each step tool has a distinct stated role and ordering. get_action_approval, verify_proof, and get_supported_circuits are clearly separate concerns, leaving only the intentional all-in-one/stepwise duality as potential confusion.
All seven tools follow a clean snake_case verb_noun pattern: generate_proof, prepare_inputs, request_challenge, submit_proof, verify_proof, get_action_approval, get_supported_circuits. Verbs (generate/prepare/request/submit/verify/get) match the actual operations with no mixed conventions.
Seven tools is well-scoped for a ZK proof server: discovery, an all-in-one path, a three-step manual flow, verification, and approval polling. Each tool maps to a real, non-redundant operation within that workflow.
The surface covers the full proof lifecycle from circuit discovery through generation and on-chain verification, including human-in-the-loop approval status. Minor gaps: no way to cancel or revoke a pending approval, no proof/status listing, and payment/encryption orchestration is explicitly deferred to the SDK, leaving MCP users unable to complete paid flows unaided.
Maintenance
Related MCP Connectors
A paid remote MCP for ZeroID, built to return verdicts, receipts, usage logs, and audit-ready JSON.
MCP server for the Z1N Protocol - on-chain identity for AI agents on Polygon
MCP server for verifying EUDI/Talao wallet data via OIDC4VP (pull) for AI agents.
Remote MCP server exposing 330 production AI-agent services for web/data processing, validation, AI utilities, blockchain/crypto utilities, and x402 pay-per-use access.
Related MCP Servers
- AlicenseAqualityBmaintenanceMCP server for wallet auth: read wallet state on-chain, evaluate against conditions, return an ECDSA-signed boolean with a post-quantum companion signature. Condition-based access across 37 chains (EVM, Solana, XRPL, Bitcoin, Tron, Stellar, Sui). No balances, no identity, no shared secrets; verifiable offline via JWKS. 27 tools: wallet attestation, trust profiles, payment verification.27552 npm2MIT
- AlicenseAqualityDmaintenanceTrust intelligence MCP server for AI agents. 19 tools for identity stamps, reputation scoring (0-100), agent registry, forensic audit trails, ERC-8004 bridge, and A2A passports via x402 USDC micropayments.192Apache 2.0
- AlicenseNot gradedqualityDmaintenanceMCP Server for AI agent identity and authorization. Create, verify, and manage agent identities with trust scores and scoped authorization tokens.25 PyPIMIT
- AlicenseNot gradedqualityCmaintenanceAn MCP server for agentic commerce, enabling AI agents to discover services, make x402 payments with USDC across multiple chains, and manage crypto wallets and token swaps.598 npm1MIT