# 公開驗證器

PAX 營運帳本中的每個事件都經過雜湊鏈接，批次組裝成默克爾樹，並錨定到外部防竄改儲存。此頁面公開驗證器介面，讓任何稽核人員、投資人或第三方開發者都能獨立重建鏈條並確認任何成交的包含性——無需聯繫 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 起，該 bucket 對 `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 回傳的事件、證明與批次根彼此一致；若要與你獨立取得的根（錨定物件，或你先前記錄的根）進行比對，請將其貼上至選填欄位。

請嘗試上方 Live status 中顯示的最新 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 分潤（位於 `apps/api/src/index.ts` 中的 `computeFeeSplit`）會寫入以 `fee_split:<trade_id>:<event_type>` 為鍵的冪等 `financial_event` 列。即使在高頻重試情況下，同一筆交易也不會被重複歸因。
- **手續費估算 = 結算。**`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-hant/request-access) 開啟工單，並附上事件 `seq`、計算出的雜湊值以及預期雜湊值。所有合法的差異回報都會在 24h 內調查。

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