# ProofGraph Protocol v1

## Create a proof

`POST /v1/proofs` with `Content-Type: application/json`.

### Required headers

| Header | Meaning |
|---|---|
| `X-Signature-Version` | `pg-hmac-sha256-v1` |
| `X-Timestamp` | Unix seconds inside the configured replay/skew window |
| `X-Request-ID` | Caller-generated idempotency token, max 128 characters |
| `X-Source-System` | Registered source-system identifier |
| `X-Key-ID` | Active signing-key identifier |
| `X-Signature` | 64-hex HMAC-SHA256 digest |

Each signed security header must occur exactly once. Duplicate signed headers are rejected.

The source/key resolves through trusted server configuration to a tenant. **Tenant ID is never accepted as caller-controlled routing input.** Unknown, revoked, malformed and incorrect credentials deliberately share `401 Unauthorized`.

### Signature preimage

```text
"PGSIG\x01"
+ frame("pg-hmac-sha256-v1")
+ frame(X-Timestamp)
+ frame(X-Request-ID)
+ frame(X-Source-System)
+ frame(X-Key-ID)
+ frame(exact raw request body bytes)
```

`frame(value)` is a four-byte unsigned big-endian byte length followed by the exact bytes. The signature is `hex(HMAC-SHA256(signing_secret, preimage))`. Prefer `proofgraph.signing.sign_request()` rather than reimplementing it.

### Body

```json
{
  "artifact": {
    "uri": "s3://proofgraph-internal/run/42.json",
    "file_hash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  },
  "actor": {"external_ref": "agent-run-42"},
  "claim": {
    "schema": "pg.claim.v1",
    "assertion": "model emitted artifact"
  }
}
```

The body is strict deterministic JSON. Duplicate keys, floating point values, NaN/Infinity, excessive nesting, unsupported fields, invalid SHA-256 values, unallowlisted artifact origins and detected PII patterns are rejected. Query strings are forbidden in artifact URIs so signed storage credentials cannot enter provenance.

Actor references are HMAC-pseudonymised **inside the authenticated tenant namespace** before persistence.

## Canonical JSON and the receipt hash

The receipt hash is `lowercase_hex(SHA-256(canonical_bytes(record)))`, where `record` is the stored provenance record and `canonical_bytes` is **ProofGraph Canonical JSON v1**:

- UTF-8, no byte-order mark, no insignificant whitespace; separators are `,` and `:`.
- Object keys sorted by Unicode **code point** (not by UTF-16 code unit: this differs from a naive JavaScript `sort()` for characters above U+FFFF).
- Strings escape only `"` `\` and control characters below U+0020 (`\b \f \n \r \t`, otherwise `\u00xx` in lower case). Everything else, including non-ASCII, is written as UTF-8.
- Integers only. Floats, `NaN`, `Infinity` and non-string keys are rejected.
- `record_hash` is never part of its own input.

The record the server hashes has these fields: `record_schema`, `signature_version`, `tenant_id`, `actor_hash`, `artifact_hash`, `artifact_uri`, `claim`, `request_timestamp_s`, `ingested_at_ms`, `request_id`, `source_system_id`, `signing_key_id`. Two of them (`ingested_at_ms`, `actor_hash`) are produced by the server, and the public verifier does not return the full record, so **a third party cannot recompute a live receipt's hash**. The owning tenant can: see *Owner record export* below. Anyone can check the algorithm itself against the published test vectors (`/protocol/test-vectors.json`).

## Owner record export

`POST /v1/records` with the same six signed headers as ingest and the body `{"proof_id": "pg_..."}` (sign the exact bytes). If the key belongs to the tenant that owns the receipt, the response is `200 {"proof_id", "proof_hash", "record"}`; hashing `record` as above must give `proof_hash`. Unknown IDs, other tenants' IDs, malformed bodies and extra fields all return the same `404 {"error": "Not found"}`; bad or stale signatures and revoked keys return `401`. It writes nothing and never counts against an allowance. `attestras.py check PROOF_ID` and `node attestras.mjs check PROOF_ID` do the fetch and the local recomputation and print `MATCH` or `MISMATCH`.

## Test vectors

`test-vectors.json` carries two records (one plain ASCII, one with non-ASCII text and escapes) with their canonical bytes and SHA-256, and one signed request with its preimage and HMAC. They are generated from the reference implementation by `scripts/make_vectors.py` and checked in the test suite against the server code (hash and signature), the Python and Node clients (signature) and the in-browser demo (canonical bytes and hash). The secret in the file is a published test value, not a credential.

## Optional external anchoring (OpenTimestamps)

Off unless the operator sets `ANCHOR_OTS_ENABLED=true`. When on, a scheduled job (`/cron/anchor`) hashes new receipt hashes into a SHA-256 Merkle tree, sends only the 32-byte **root** to public OpenTimestamps calendars, and keeps for every receipt a standard `.ots` file (header, the receipt hash, its path up the tree, the calendar's reply). Once a calendar holds a Bitcoin attestation (usually hours) the job fetches it once per batch and splices it into each file.

- `POST /v1/verify` then adds `"anchor": {"status": "pending" | "confirmed", "bitcoin_height": N, "ots": "available"}` for anchored receipts. The field is absent otherwise.
- `POST /v1/anchor` with the same body as `/v1/verify` returns the `.ots` file (`application/vnd.opentimestamps`) once both receipt values check out; `404` otherwise.
- Check it yourself with the open-source `ots` client: `ots verify -d <receipt hash> <proof_id>.ots`. The service never claims a Bitcoin confirmation it has not seen the calendar return, and it does not verify Bitcoin itself.
- The anchored value is the receipt hash, a SHA-256 of the whole record. No record content leaves the service.

## Idempotency

The authoritative namespace is `(tenant_id, source_system_id, request_id)`.

- First valid submission: `201` and a new immutable proof.
- Exact retry: `200` and the original proof ID/hash, even after timestamp refresh or signing-key rotation.
- Same tenant/source/request ID with changed body: `409`.
- The database uniqueness boundary, not a cache, owns correctness.

## Create response

```json
{
  "message": "Created",
  "proof_id": "pg_...",
  "proof_hash": "...sha256...",
  "verify_path": "/verify"
}
```

A replay returns the same `proof_id` and `proof_hash` with `message: "Already processed"`.

## Public verification — preferred

`POST /v1/verify` with `Content-Type: application/json`:

```json
{
  "proof_id": "pg_...",
  "proof_hash": "...64 hex..."
}
```

The browser verifier at `/verify` also submits both receipt values by POST body. New integrations should use POST verification so bearer receipt material is not unnecessarily placed in browser/proxy URL logs.

A deprecated compatibility endpoint remains for RC2 clients:

`GET /v1/verify/{proof_id}?proof_hash={64-hex}`

Do not use it for new integrations.

Verification requires **both** receipt values. If either is wrong, ProofGraph returns `404 {"verified": false}` and does not independently disclose whether the proof ID exists.

A successful verification returns only the privacy-minimised receipt view:

```json
{
  "verified": true,
  "proof_id": "pg_...",
  "proof_hash": "...",
  "record_schema": "pg.proof.v1",
  "source_system_id": "agent-prod",
  "artifact_hash": "...",
  "claim_schema": "pg.claim.v1",
  "recorded_at": "2026-09-29T12:34:56Z"
}
```

Tenant ID, actor pseudonym, assertion text and artifact URI are not exposed by the public verifier.

**Semantics:** verified means the stored provenance record still matches the issued receipt hash. It does not mean the underlying assertion is factually true, correct, safe, lawful or unbiased.

## Operations metering

`GET /v1/admin/usage` requires `Authorization: Bearer <PG_ADMIN_TOKEN>`. Duplicate Authorization headers are rejected. This surface is operations-only and is intentionally excluded from public API docs.

## Errors

- `400`: malformed/invalid payload, unsupported schema, unsafe URI, PII policy rejection or ambiguous verifier form fields.
- `401`: authentication/replay failure or ambiguous signed/auth headers.
- `404`: public receipt not verified.
- `409`: idempotency key reused with different content.
- `413`: body exceeds configured byte limit.
- `415`: unsupported request content type.
- `503`: expected authentication, identity, storage or verification dependency unavailable.
- `500`: internal defect or stored-proof integrity failure.
