# 公共验证器

PAX 运营账本中的每个事件均经过哈希链式处理，批量构建为 Merkle 树，并锚定到外部防篡改存储。此页面公开验证器接口，使任何审计人员、投资者或第三方开发者都能独立重建链，并确认任意成交的包含性——无需联系 PAX 支持，也无需信任 PAX API。

## 实时状态

页面加载时从 `GET /v1/audit/status` 刷新。如果你看到计数，说明链正在运行。

—

哈希链事件

加载中…

—

Merkle 批次

加载中…

—

锚点延迟 (秒)

距上次 R2 发布的时间

—

发布者模式

R2 = Cloudflare 防篡改存储桶

## 链模型

三层防篡改证据，每一层均可由第三方独立验证：

第 1 层 — 哈希链事件日志（行级）

```
event_log {
  seq             — monotonically increasing sequence number
  event_type      — canonical event name (e.g. fast_round.commit, order.filled)
  payload         — the full event body (JSON)
  prev_event_hash — event_hash of the previous event (64 zeros for seq 1)
  event_hash      — sha256_hex( utf8( prev_event_hash + canonical ) )
  canonical       — the exact string that was hashed, returned verbatim by
                    GET /v1/audit/events/{seq} (Postgres jsonb text of
                    {event_id, seq, event_type, payload, idempotency_key,
                     created_at (UTC, microseconds), emitter, schema_version})
}
```

`prev_event_hash` 以 64 个字符的小写十六进制文本（TEXT）拼接，而不是原始字节。不要自行重新序列化 `payload`：直接对给定的 `canonical` 做哈希，再用 `JSON.parse(canonical)` 读取它所承诺的字段。

篡改检测：修改任何历史行，都会使该行的 `event_hash` 以及其后每一行的 `prev_event_hash` 失效。

第 2 层 — Merkle 批次根（批次级，约每 60 秒一次）

```
event_batches {
  batch_num       — monotonically increasing batch number
  first_seq       — inclusive lower bound
  last_seq        — inclusive upper bound
  event_count     — number of leaves
  merkle_root     — sorted-pair SHA-256 over the batch's event_hash values
                    (each hash decoded to its raw 32 bytes before hashing, NOT the hex string)
  prev_batch_hash — the previous batch's merkle_root (64 zeros for batch 1)
}
```

算法：对每一对排序后的原始 32 字节摘要计算 SHA-256（不是 keccak256）；节点数为奇数的层会复制其最后一个节点。

只有当每个元素都是 32 字节摘要，并且 `proof.length == ceil(log2(last_seq - first_seq + 1))` 时，证明才有效；证明响应中也带有 `leaf_count` 和 `expected_proof_length`。如果不检查长度，树的内部节点可能被当作叶子，配上缩短的证明蒙混过关，所以务必检查长度，并始终把叶子与事件绑定（第 1 层）。

第 3 层 — 外部锚定（Cloudflare R2）

每个批次都会以 JSON 对象的形式发布到 Cloudflare R2：

```
Key:  pax-audit/batches/{batch_num}.json
Read: GET /v1/audit/anchor/{batch_num}/raw  (anchor_public_url)
Body: { batch_num, merkle_root, prev_batch_hash, first_seq, last_seq,
        event_count, created_at, pax_version, sig_algo, sig_key_id, ... }
```

自 2026-11-22 起，该存储桶对 `pax-audit/` 前缀实施了仅一次写入锁定：已锚定的对象无法被覆盖或删除。请比较锚定对象中的 `merkle_root` 与 `/v1/audit/batches/{batch_num}` 以及你重建的根哈希。`anchor_ref` 是内部 S3 地址（需要凭证且无法公开获取）；请使用 `anchor_public_url`。HMAC 签名由 PAX 持有密钥，因此它能让 PAX 检测篡改，但并非第三方证明——独立的、最小化信任的层是计划在上架后实施的 Polygon 锚定。

于 2026-11-22 重新发布的批次

2026-11-22 在设置锁定之前，重新发布了 22,118 个批次：批次 1–21,990、21,993 至 22,465 之间的 125 个批次，以及批次 31,071、40,737 和 45,318（[完整列表](https://docs.predictasiax.com/downloads/republished-batches-2026-11-22.txt)）。这些文件曾被配置错误的非生产环境发布者覆盖，无法逐字节恢复，因此根据存储的事件进行了重建。每次重建都与批次未变的 `merkle_root` 进行了核对，所有事件哈希均验证通过：没有任何事件、事件哈希或 Merkle 根发生变化。其他所有批次的锚定对象与首次发布的版本逐字节一致。

对于这些批次，锚定对象携带 `updated_at` 以及它所替换文件的摘要：`previous_events_content_sha256`、`previous_events_r2_etag` 和 `previous_metadata_etag`，这些字段均包含在签名覆盖范围内。自 2026-12-02 起，`/v1/audit/batches/{batch_num}` 中的 `anchor_proof` 包含相同内容：当前的 `events_content_sha256`、`events_r2_etag` 和 `metadata_etag`，三个 `previous_*` 值，以及作为 `reanchored_at_ms` 的重新发布时间。在此之前，它仍然提供这些批次先前文件的摘要。

## 验证器接口（无需身份验证）

所有六个接口均为公开、只读，并按源 IP 进行速率限制。响应信封采用规范的 `{data, meta}` 结构，并包含 `trace_id` 以支持调试。

| 接口 | 用途 |
|---|---|
| `GET /v1/audit/head` | 账本头部：最新 Merkle 批次 `{batch_num, last_seq, merkle_root, created_at_ms}` + 总事件数 + `last_event_at_ms`。 |
| `GET /v1/audit/root` | 当前链尖 `root` 哈希 + 写入时间 + 每个批次发布到的外部锚点目标（当前为 Cloudflare R2；上线后为 Polygon 链上锚点）。 |
| `GET /v1/audit/batches?limit=25` | 最新的 Merkle 批次页面 (`batch_num, first_seq, last_seq, event_count, merkle_root, anchored_at`)；使用 `before=<next_before>` 翻页。 |
| `GET /v1/audit/events/{seq}` | 单个事件：`payload`、`prev_event_hash`、`event_hash` 和 `canonical` — 校验 `sha256_hex(prev_event_hash + canonical) == event_hash`。 |
| `GET /v1/audit/proof/{seq}` | 该事件的 Merkle 包含证明：`merkle_proof`、`leaf_index`、`leaf_count`、`expected_proof_length` 以及批次信息（`merkle_root`、`first_seq`、`last_seq`、`anchor_public_url`）。 |
| `GET /v1/audit/health` | 链状态：总事件数、最新时间戳、`lag_ms`（陈旧度指标）、外部锚点目标身份。 |
| `GET /v1/audit/anchor/{batch_num}` | 每批次外部锚点：`anchor_target`（当前为 `r2`）、`anchored_at`、`anchor_proof` 和 `anchor_public_url`（`/v1/audit/anchor/{batch_num}/raw`，即锚定对象本身）。链上合约字段（chain、address、cadence）将在 Polygon 锚点于上线后发布时填充。 |

## 交互式验证演示

在下方输入事件的 `seq`。页面将获取该事件及其 Merkle 包含证明和批次的 `merkle_root`，并根据其 `canonical` 字符串重新计算事件的 `event_hash`，然后完全在浏览器中通过 WebCrypto 验证包含证明（排序对 SHA-256，精确证明长度）。这两项检查均在客户端运行。仅凭此操作可验证 API 返回的事件、证明和批次根彼此一致；若要对照你独立获取的根（锚定对象，或你之前记录的根），请将其粘贴到可选字段中。

请尝试上方实时状态中显示的最新 seq。

## 在你自己的代码中复现它

两项检查，均在本地执行：(1) 该叶子节点确实对应该事件 — `sha256_hex(prev_event_hash + canonical) == event_hash`；(2) 该叶子节点在批次中 — 包含证明（恰好为 `expected_proof_length` 个 32 字节元素）可重建 `merkle_root`。

### TypeScript / Node

```
// npm i @predictasiax/api@3     (3.0.0+: length check + event-hash check)
import { PaxClient, AuditResource, expectedProofLength } from '@predictasiax/api';

const pax = new PaxClient();            // audit endpoints need no key

// One call: event hash, same event, seq in batch, proof length, Merkle root
const r = await pax.audit.verify(110841);
console.log(r.ok, r.checks);

// Or step by step
const ev = await pax.audit.getEvent(110841);
const proof = await pax.audit.getProof(110841);
const n = proof.batch.last_seq - proof.batch.first_seq + 1;
const leafOk = AuditResource.verifyEventHash(ev);   // sha256(prev_event_hash + canonical)
const inBatch = AuditResource.verifyProof(          // sync; verifyProofAsync for WebCrypto
  ev.event_hash, proof.batch.merkle_root, proof.merkle_proof, expectedProofLength(n),
);
```

### Python

```
# pip install "pax-api>=3"      (3.0.0+: length check + event-hash check)
from pax_api import PaxClient, expected_proof_length, verify_event_hash, verify_merkle_proof

pax = PaxClient()                       # audit endpoints need no key

r = pax.verify_audit_event(110841)      # all checks in one call
print(r["ok"], r["checks"])

ev = pax.audit_event(110841)["data"]
proof = pax.audit_proof(110841)["data"]
n = proof["batch"]["last_seq"] - proof["batch"]["first_seq"] + 1
leaf_ok = verify_event_hash(ev)
in_batch = verify_merkle_proof(ev["event_hash"], proof["batch"]["merkle_root"],
                               proof["merkle_proof"], expected_proof_length(n))
```

### 纯 curl + shasum（无 SDK）

```
SEQ=110841
API=https://api.predictasiax.com/v1/audit

# 1. The leaf is this event: sha256(prev_event_hash + canonical) == event_hash
curl -s $API/events/$SEQ > ev.json
printf '%s%s' "$(jq -r .data.prev_event_hash ev.json)" "$(jq -r .data.canonical ev.json)" \
  | shasum -a 256 | cut -c1-64        # must equal: jq -r .data.event_hash ev.json

# 2. The leaf is in the batch (sorted-pair sha256 over the RAW 32-byte digests)
curl -s $API/proof/$SEQ > proof.json
verify() {   # verify LEAF ROOT EXPECTED_LEN SIBLING...
  local h=$1 root=$2 want=$3; shift 3
  [[ $# -eq $want ]] || { echo "MISMATCH: proof length $# != $want"; return 1; }
  for s in "$@"; do
    [[ $s =~ ^[0-9a-f]{64}$ ]] || { echo "MISMATCH: bad element"; return 1; }
    if [[ "$h" < "$s" ]]; then pair="${h}${s}"; else pair="${s}${h}"; fi
    # xxd -r -p decodes the 128 hex chars to the 64 raw bytes BEFORE hashing.
    h=$(printf '%s' "$pair" | xxd -r -p | shasum -a 256 | cut -c1-64)
  done
  [[ "$h" == "$root" ]] && echo OK || echo MISMATCH
}
verify $(jq -r '.data.event_hash, .data.batch.merkle_root, (.data.batch.last_seq - .data.batch.first_seq + 1 | if . <= 1 then 0 else (log2 | ceil) end)' proof.json) \
       $(jq -r '.data.merkle_proof[]' proof.json)
```

### Solidity (链上)

```
// PAX anchors with SHA-256 sorted-pair. OpenZeppelin's MerkleProof.verify
// hashes with keccak256, so it will NOT match these roots — use the SHA-256
// verifier below. abi.encodePacked lays the two bytes32 down as 64 raw bytes
// and the sha256 precompile hashes those raw bytes — identical to the publisher.
// root, firstSeq and lastSeq must come from the anchored batch you trust (the
// anchored object, or a root your contract already stores), never from the
// proof response alone: whoever serves the proof also chooses those values.
// The proof length is derived here from the batch bounds and checking it is
// REQUIRED: a shorter proof would let an internal node of the tree pass as a
// leaf. Bind the leaf to the event off-chain (Layer 1) or by recomputing
// event_hash on-chain before calling this.
function paxProofLength(uint256 leafCount) internal pure returns (uint256 len) {
  uint256 width = leafCount;      // an odd level duplicates its last node
  while (width > 1) { width = (width + 1) / 2; len++; }
}

function verifyPaxEvent(
  bytes32 leaf,               // event_hash from /v1/audit/proof/{seq}
  bytes32[] calldata proof,   // merkle_proof array
  uint256 seq,                // the event's seq
  bytes32 anchoredRoot,       // merkle_root of the anchored batch
  uint256 firstSeq,           // first_seq of the anchored batch
  uint256 lastSeq             // last_seq of the anchored batch
) public pure returns (bool) {
  if (firstSeq == 0 || firstSeq > seq || seq > lastSeq) return false;
  if (proof.length != paxProofLength(lastSeq - firstSeq + 1)) return false;
  bytes32 h = leaf;
  for (uint256 i = 0; i < proof.length; i++) {
    bytes32 s = proof[i];
    h = h <= s
      ? sha256(abi.encodePacked(h, s))
      : sha256(abi.encodePacked(s, h));
  }
  return h == anchoredRoot;
}
```

## 这为你证明了什么

- **订单 → 成交溯源。** 每笔交易都会向 `event_log` 发出一个事件。如果你的应用路由了该交易，事件的 payload 中会包含你的 `execution_builder_id`——可通过 `/v1/audit/events/{seq}` 进行公开验证。
- **归因完整性。**7 方 PAF 拆分（`computeFeeSplit` 位于 `apps/api/src/index.ts`）写入幂等的 `financial_event` 行，键为 `fee_split:<trade_id>:<event_type>`。即使在重试风暴下，同一笔交易也不会被重复归因。
- **手续费估算 = 结算。** `POST /v1/fees/estimate` 接口和成交时的结算路径都调用同一个 `computeFeeSplit` 函数，并使用相同的 `PAF_BASE_BPS` / `PAF_FLOOR_BPS` / `PAF_CEILING_BPS` 常量。交易前返回的估算值与结算使用完全相同的计算逻辑——出现偏差需要 API 同时运行两个不同的构建版本，而部署流水线禁止这样做。
- **防篡改证据的生命周期长于 API。** 基于 R2 的批次作为写锁定的签名对象持久化。即使 `api.predictasiax.com` 遭到入侵，历史锚点也能让审计人员检测出对过去事件的追溯性重写。

**报告差异。** 如果你的独立验证产生不匹配，请在 [Request access](https://docs.predictasiax.com/zh-hans/request-access) 提交工单，并附上事件 `seq`、计算出的哈希值以及预期哈希值。所有合法的差异报告都会在 24h 内得到调查。

Source: https://docs.predictasiax.com/zh-hans/verify
