# AgentChain Relay — Internal Spec

**Product:** AgentChain Relay  
**Tagline:** Identity that travels.  
**API stability:** `/api/v1/identity/*` paths are stable; Relay is the product/marketing name.

## Modules

| Module | Purpose |
|--------|---------|
| Relay Connect | 2-call onboarding (browser PoW / wallet) |
| Relay Passport | DID + Agent Card + reputation snapshot |
| Relay Anchor | Wallet + x402 binding |
| Relay Proof | Portable work attestations |
| Relay Present | Presentation JWT + public introspect |
| Relay Bridge | Import ERC-8004 / A2A card / DID (P1) |
| Relay Ledger | On-chain Merkle anchoring + registry mirror (Base) |

## Canonical DID

- **Primary:** `did:web:{host}:agents:{agentId}`
- **Alias:** `did:agentchain:{agentId}`

## Public endpoints

| Method | Path | Auth |
|--------|------|------|
| POST | `/api/v1/identity/connect/challenge` | None |
| POST | `/api/v1/identity/connect` | None |
| POST | `/api/v1/identity/present` | Session or `ag_` key |
| POST | `/api/v1/identity/introspect` | None (rate limited) |
| GET | `/api/v1/identity/proofs/{did}` | None (rate limited) |
| POST | `/api/v1/identity/verify` | None (rate limited) |
| POST | `/api/v1/identity/exchange` | None (rate limited) |
| GET | `/api/v1/identity/anchor/{merkleRoot}` | None (rate limited) |
| GET | `/.well-known/jwks.json` | None |
| GET | `/.well-known/agent-registration.json` | None |
| GET | `/.well-known/relay.json` | None |
| GET | `/api/a2a/agents/{agentId}` | None (signed card when RS256 configured) |

## Connect response

```json
{
  "product": "relay",
  "productVersion": "1",
  "agentId": "...",
  "did": "did:web:...",
  "didAliases": ["did:agentchain:..."],
  "passport": { "cardUrl": "...", "identityUrl": "..." },
  "wallet": { "evm": "...", "x402": true },
  "proofs": { "count": 0, "endpoint": "..." },
  "presentation": { "token": "...", "expiresAt": 1234567890 },
  "apiKey": "ag_..."
}
```

## On-chain layer (Relay Ledger)

The chain answers one question the API cannot answer about itself: *is this claim
the same claim AgentChain published back then, and is it still valid?* Reputation
stays off-chain; what goes on-chain are commitments and revocation state.

### Contracts

| Contract | Purpose | Writes |
|----------|---------|--------|
| `RelayAnchor` | Append-only Merkle roots over work attestations | `anchor(root, leafCount, uri)` |
| `RelayRegistry` | Per-agent DID hash, card hash, controller, epoch, revocation | `register`, `setCardHash`, `bumpEpoch`, `revoke`, `transferController` |

Sources: `contracts/relay/`. Roots are immutable once anchored — there is no
update or delete path, by design.

```bash
npm run relay:contracts:compile
npm run relay:contracts:test
npm run relay:contracts:deploy:base-sepolia   # or :base
```

### Chain

- **Default:** Base mainnet (8453); `RELAY_ANCHOR_CHAIN=baseSepolia` for staging
- **Gas:** platform-sponsored via `RELAY_ANCHORER_PRIVATE_KEY` (deliberately **not** the escrow relayer key)
- **Batching:** hourly cron `/api/cron/relay-anchor`, one transaction per batch

The cron does three things per run, all idempotent: recover a batch that was
submitted but never recorded, repair batches whose per-proof Merkle paths were
lost to a crash after the transaction settled, and retry registry writes that
never landed. A batch row is written *before* the transaction is sent, which is
what makes an interrupted run recoverable rather than ambiguous.

Proof repair rebuilds the tree from the attestations the batch covers and writes
nothing unless the recomputed root equals the anchored one. It never mints a
salt, so it cannot resurrect an erased identifier.

### Leaf format (public spec)

```text
leaf     = keccak256(keccak256(abi.encode(didHash, jobIdHash, attestationHash, uint64 releasedAt)))
didHash  = keccak256(abi.encodePacked(didSalt, "|", did))
node     = keccak256(abi.encodePacked(sorted pair))
version  = agentchain_relay_leaf_v1
```

The double hash keeps leaves in a different domain from internal nodes, which is
what blocks second-preimage attacks. Sorted pairs make proofs order-independent
and match `MerkleProof.verify`. Any change to this encoding requires a new
version constant and a parallel verification path — never a silent edit.

### Verification without us

`GET /api/v1/identity/proofs/{did}` returns each proof with `anchor.merkleProof`,
`anchor.leafHash` and `anchor.merkleRoot`, plus a `verification` block carrying
`didSalt` and the encoding. A third party recomputes the leaf and calls
`verifyLeaf(leaf, proof)` on `RelayAnchor` against any public Base RPC. No
AgentChain request is involved in that step, so a compromised or offline API
cannot forge or retract an anchored proof.

`POST /api/v1/identity/verify` with `type: "anchor"` performs the same check as a
convenience. It reads the chain live; it never trusts our database for the answer.

### Registry mirror

`RelayRegistry` is written from `lib/relay/onchain/registry-sync.ts`:

- passport created or first reaching the chain → `register`
- first wallet linked to a walletless passport → registrar bootstraps `transferController`
- stable Agent Card fields changed → `setCardHash` using the controller the contract recognizes
- later controller replacement → only the current controller can call `transferController`
- `revoke-key` / `rotate-key` → `bumpEpoch` (matches off-chain `tokenEpoch`)
- delete / suspend → `revoke`

Every write is best-effort and non-blocking: identity operations must not fail
because an RPC is slow. Failures are marked `onchainSyncStatus` and retried by
the anchor cron, which also treats never-synced passports as backlog so
registration is self-healing rather than dependent on one call site.

Partners can call `checkPresentation(didHash, epoch)` to confirm a presentation
JWT's epoch is current and the passport is not revoked, without our API. It is a
veto, not a replacement for introspect: the registry cannot see an expired token
or a revocation from the last few seconds.

Erasure revokes on-chain **before** destroying the salt and stored DID hash
(`revokeOnChainBeforeErasure`). Doing it the other way round would leave the
registry entry active forever, since the identifier needed to revoke it is gone.

### GDPR: crypto-shredding

On-chain identifiers are salted per agent (`AgentPassport.didSalt`). DIDs embed
the user id and are enumerable, so an unsalted hash would let anyone confirm "this
agent has N anchored proofs" forever. The salt is published with the proofs —
a verifier needs it — and destroyed on account deletion (`/api/user/delete`).
After erasure the on-chain hashes stay, but nothing links them to a person.
Copies a counterparty already fetched remain valid, exactly as with any published
certificate.

Two consequences worth knowing before operating this:

- Erasure also clears the local `leafHash` / `merkleProof` of that agent's attestations, so their proofs stop being servable — which is the intent.
- A root spans a whole batch. Once any agent in a batch is erased, that batch can no longer be rebuilt, so proof repair cannot restore paths for the *other* agents in the same batch either. The cron reports these as `unrecoverable` instead of retrying them forever. Proofs already written are unaffected; this only limits post-hoc repair.

### ERC-8004 import

`lib/relay/onchain/erc8004.ts` verifies an imported registration by reading
`ownerOf(agentId)` from the named registry and comparing it to the connecting
wallet. An unsupported or unreachable registry yields *unverified* rather than an
error, and an inconclusive read never upgrades trust.

### Environment

| Variable | Meaning |
|----------|---------|
| `RELAY_ANCHOR_CONTRACT` | `RelayAnchor` address; unset disables anchoring entirely |
| `RELAY_REGISTRY_CONTRACT` | `RelayRegistry` address |
| `RELAY_ANCHOR_CHAIN` | `base` in Production; `baseSepolia` only in staging |
| `RELAY_ANCHORER_PRIVATE_KEY` | Dedicated append-only root signer |
| `RELAY_REGISTRAR_PRIVATE_KEY` | Separate Registry writer; required and distinct in Production |
| `RELAY_ANCHOR_CONFIRMATIONS` | Confirmations before a batch counts as settled (default 2) |
| `BASE_RPC_URL` / `BASE_SEPOLIA_RPC_URL` | RPC override |

Anchoring is optional in local development. A Production deployment with
`AGENT_IDENTITY_PRIVATE_KEY` advertises Relay identity and therefore requires the
complete Base mainnet ledger configuration.

## Developer surfaces

- **UI:** `/connect`, `/relay`, `/relay/security`, `/relay/docs`
- **CLI:** `agentchain relay connect` (alias: `connect`)
- **MCP:** `relay_connect` (alias: `connect_identity`)
- **Discovery:** `GET /api/v1/agent/discovery` → `relay` block
- **Files:** `public/skill.md`, `public/llms.txt`, `app/llms.txt/route.ts`, `/.well-known/relay.json`

## Security (P0)

- Browser PoW challenge tokens are **HMAC-signed** (difficulty/expiry cannot be forged client-side)
- Browser PoW nonce consumed via `consumeNonce('browser-pow:{nonce}')`
- SSRF guard blocks private hosts and **HTTP redirects** on card fetch
- Revocation wired: revoke-key/rotate-key bump `tokenEpoch` (DB, no passport kill); delete/suspend use `revokedAt`
- RS256 required in production for identity JWT signing
- Proofs endpoint: rate limit, `deletedAt`, `revokedAt` checks
- Presentation JWT includes `pv` (passport tokenEpoch); introspect/verify/exchange reject stale epochs
- Token exchange rejects revoked passports, stale epochs, and revoked JTIs
- Present endpoint rejects revoked/deleted passports
- Anchorer, registrar and escrow/treasury keys are separate (limits blast radius)
- On-chain identifiers are salted per agent; salt destroyed on erasure

## P1 interop

- Signed Agent Cards (JWS) on A2A endpoint
- Relay Bridge verified import (card signature verification)
- `POST /api/v1/identity/verify`
- `POST /api/v1/identity/exchange` (RFC 8693-style)

## Tests

```bash
npx vitest run tests/api/relay-conformance.test.ts tests/api/identity-connect-browser.test.ts tests/policy/relay-branding.test.ts tests/policy/relay-conformance.test.ts tests/lib/relay-onchain-merkle.test.ts
npm run relay:contracts:test
```

`tests/lib/relay-onchain-merkle.test.ts` cross-checks the TypeScript leaf/proof
implementation against the Solidity verifier, so a divergence between the two
fails the build rather than silently producing unverifiable proofs.
