# パブリック Verifier

PAXの運用台帳にあるすべてのイベントはハッシュチェーンで連結され、Merkleツリーにバッチ化され、外部の改ざん検知可能なストレージにアンカーされます。このページは検証インターフェースを公開しており、監査人、投資家、サードパーティの開発者がPAXサポートに連絡することなく、PAX APIを信頼することなく、チェーンを独立して再構築し、任意の約定の包含を確認できるようにします。

## ライブステータス

`GET /v1/audit/status` からページ読み込み時に更新されます。カウントが表示される場合、チェーンは稼働中です。

—

ハッシュチェーンされたイベント

読み込み中…

—

Merkle バッチ

読み込み中…

—

アンカー遅延 (秒)

前回のR2公開からの経過時間

—

パブリッシャーモード

R2 = Cloudflare改ざん検知バケット

## チェーンモデル

第三者がそれぞれ独立して検証できる、3 層の改ざん検出機能:

レイヤー 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 文字の小文字 hex テキスト（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`に対してチェックされ、すべてのイベントハッシュは依然として検証可能です。イベント、イベントハッシュ、またはマー​​クルートは変更されていません。他のすべてのバッチのアンカーオブジェクトは、最初に公開されたものとバイト単位で同一です。

これらのバッチでは、アンカーオブジェクトは`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`、3つの`previous_*`値、および`reanchored_at_ms`としての再公開時間と同様のものを保持します。それ以前は、これらのバッチに対して以前のファイルのダイジェストを提供していました。

## 検証用エンドポイント（認証不要）

6つのエンドポイントすべてはパブリックで、読み取り専用、ソース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}` | 1つのイベント: `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` を再計算して、包含証明（ソート済みペア SHA-256、正確な証明長）を WebCrypto を使用してブラウザ内で完全に検証します。両方のチェックはクライアントサイドで実行されます。これだけで、API が返したイベント、証明、バッチルートが互いに一致していることを示せます。独立して取得したルート（アンカーされたオブジェクト、または以前に記録したルート）と照合するには、任意のフィールドに貼り付けてください。

上記のライブステータスに表示されている最新の seq をお試しください。

## ご自身のコードで再現してください

2つのチェック、いずれもローカルで行います: (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`にイベントを出力します。アプリが取引をルーティングした場合、イベントのペイロードにはあなたの`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が同時に2つの異なるビルドを実行する必要があり、デプロイパイプラインではこれが禁止されています。
- **改ざん検知機能はAPIの存続期間を超えて維持されます。** R2にアンカーされたバッチは、書き込みロックされた署名付きオブジェクトとして永続化されます。`api.predictasiax.com` が侵害された場合でも、過去のアンカーにより監査人は、過去のイベントの事後の書き換えを検出できます。

**不一致の報告。** 独立した検証で不一致が見つかった場合は、イベントの `seq`、計算されたハッシュ、および期待されるハッシュを添えて、[Request access](https://docs.predictasiax.com/ja/request-access) でチケットを作成してください。すべての正当な不一致報告は24h以内に調査されます。

Source: https://docs.predictasiax.com/ja/verify
