# 5-层架构总览 5-Layer Architecture

## 总览图

```
┌─────────────────────────────────────────────────────────────────────────┐
│  L4 — 监管锚点 Regulatory Anchor                                        │
│  • PolicyRegistry policy hash (例 EU AI Act high-risk)                  │
│  • 0xfc53fc5e88de7760db17d4f0e39289edebfb8bfe10d277dbef22e9e85bdd6732   │
│  Algo: keccak256(rego_full_text)                                       │
├─────────────────────────────────────────────────────────────────────────┤
│  L3 — 解释层 Explanation Layer                                          │
│  • ExplanationRegistry: (decisionId, explanationHash, modelVersion)    │
│  • baby-explanation Rust crate: deterministic stub (PoC)               │
│  Algo: SLM 摘要 + XAI feature attribution → keccak256                   │
├─────────────────────────────────────────────────────────────────────────┤
│  L2 — 策略引擎 Policy Engine                                            │
│  • PolicyRegistry + BehaviorSpec 绑定                                   │
│  • baby-opa-policy Rust mini-Rego evaluator                            │
│  Algo: Rego DSL → AST → eval against BehaviorSpec context              │
├─────────────────────────────────────────────────────────────────────────┤
│  L1 — 决策回执 Decision Receipt                                         │
│  • PoDRegistry + ModelRegistry + 3 verifier:                            │
│    - EcdsaInferenceVerifier (真 ECDSA)                                  │
│    - TeeInferenceVerifier (mock DCAP, 主网前 swap)                       │
│    - ZkmlInferenceVerifier (mock Halo2, 主网前 EZKL swap)                │
│  • CausalChainLinker: PoD DAG (parent → child)                         │
│  Algo: ECDSA secp256k1 / Halo2 / Intel DCAP                            │
├─────────────────────────────────────────────────────────────────────────┤
│  L0 — 行为记录 Behavior Recording                                       │
│  • PoBRegistry v2 + BehaviorSpecRegistry v2                            │
│  • StakeManager (aggregator 抵押)                                       │
│  • ChallengeManager v2 (7-day fraud-proof window, 50% slash reward)    │
│  • Groth16PoBVerifier + PoBComplianceGroth16Verifier                   │
│  Algo: Positional Merkle proof + Groth16 ZK + ECDSA + EIP-191         │
├─────────────────────────────────────────────────────────────────────────┤
│  基础设施 Infra (chain 391)                                           │
│  • OracleHub (system contract slot 0x8016) + L1OracleReader            │
│  • DIDRegistryLocal + CredentialRegistryLocal + IdentityVerifierLocal  │
│  • L1BridgeContract + L2BridgeContract + FastWithdrawalPoolV2          │
│  • ERC8004Adapter (Identity / Reputation / Validation)                 │
└─────────────────────────────────────────────────────────────────────────┘
            ⬇ 全部基于 zkSync-era fork chain 391 (anvil-zksync demo)
```

## 每层职责矩阵

| 层      | 核心问题                | 主合约                            | 链上事实                          | 详细页                                                   |
| ------ | ------------------- | ------------------------------ | ----------------------------- | ----------------------------------------------------- |
| **L4** | "这个 AI 服务是否符合法规？"   | PolicyRegistry                 | EU AI Act hash on-chain       | [→ L4](/protocol-mechanics/regulatory-anchor.md)      |
| **L3** | "这个决策能否解释？解释什么？"    | ExplanationRegistry            | deterministic explainer LIVE  | [→ L3](/protocol-mechanics/explanation-layer.md)      |
| **L2** | "这个行为是否符合策略？"       | PolicyRegistry + BehaviorSpec  | 3-case OPA SDK e2e            | [→ L2](/protocol-mechanics/policy-engine-opa.md)      |
| **L1** | "这个决策真是这个模型产出的吗？"   | PoDRegistry + 3 Verifier       | ECDSA 真验签, ZK/TEE mock        | [→ L1](/protocol-mechanics/pod-decision-receipt.md)   |
| **L0** | "这个 Agent 真做过这件事吗？" | PoBRegistry + ChallengeManager | 真 fraud-proof + 0.5 ETH slash | [→ L0](/protocol-mechanics/pob-behavior-recording.md) |

## 一笔典型流程：AI Agent 做了一次决策

以"医疗 triage AI 拒绝某个低风险患者紧急救护推送"为例：

```
1. Agent 内部推理 → 生成 BehaviorEvent {agent_id, action_id, input_hash, ts}
2. Agent 调 baby-pob-aggregator (Rust):
   • 攒一个 Merkle batch (含本 BehaviorEvent + 其他 N-1 条)
   • aggregator 用 ECDSA 签名 batch header
   • 调 PoBRegistry.submitBatch(batchData, sig) ─→ 上链 (L0 完成)
3. Agent 同时生成 DecisionReceipt {modelHash, publicInput, inferenceProof}
   • inferenceProof = ECDSA(privKey, eth_signed_msg(publicInput))
   • 调 PoDRegistry.submitReceipt(...) → EcdsaInferenceVerifier 验签 → 上链 (L1 完成)
4. PolicyRegistry.evaluate(behaviorSpecHash, eventContext) (off-chain Rego eval)
   • 输出 verdict: Compliant / Denied / NonCompliant
   • PolicyRegistry.setPolicyHash 锁定 policy 引用 (L2 完成)
5. baby-explanation crate 生成 (decisionId, explanationText) 摘要
   • ExplanationRegistry.submitExplanation(...) (L3 完成)
6. PolicyRegistry 关联 EU AI Act high-risk hash (L4 完成)
```

**用时 \~5 秒（chain 391 出块速率 1 block/min）+ \~3 笔 tx（L0 batch + L1 receipt + L3 explanation）**。

如果 aggregator 作弊（提交假 BehaviorEvent），baby-pob-challenger Rust daemon 会在 7 天 challenge window 内自动 open challenge，触发 ChallengeManager.resolveExpired → StakeManager.slash 0.5 ETH 真扣。

## 33 合约清单（按 layer 分组）

### L0 (5)

* `PoBRegistry.sol` (`0xdD7870A759Cbe9B755e33ce10Fbc16962c6b44B7`)
* `BehaviorSpecRegistry.sol`
* `StakeManager.sol` (`0x1f6A315850489B949735Dc3F37ca90B2d1d4A2B8`)
* `ChallengeManager.sol` (`0x87211Ff26Ae70300917119ded51FBc88714dB544`)
* `Groth16PoBVerifier.sol` + `PoBComplianceGroth16Verifier.sol`

### L1 (8)

* `PoDRegistry.sol`
* `ModelRegistry.sol`
* `EcdsaInferenceVerifier.sol`
* `TeeInferenceVerifier.sol` + `MockDcapVerifier.sol` + `TeeProfileRegistry.sol`
* `ZkmlInferenceVerifier.sol` + `MockHalo2Verifier.sol` + `ZkmlCircuitRegistry.sol`
* `CausalChainLinker.sol`

### L2 (1)

* `PolicyRegistry.sol` (`0x07De5CBeaB32e6b86ae6b993A62B4a1759c66217`)

### L3 (1)

* `ExplanationRegistry.sol`

### L4 (隐式)

* 通过 PolicyRegistry policy hash 字段实现

### Infra / Bridge / Oracle / DID (18)

* Bridge: `L1BridgeContract.sol`, `L2BridgeContract.sol`, `FastWithdrawalPool.sol`, `FastWithdrawalPoolV2.sol`
* Oracle: `OracleHub.sol`, `OracleHubLocal.sol`, `L1OracleReader.sol`
* DID: `DIDRegistryLocal.sol`, `CredentialRegistryLocal.sol`, `IdentityVerifierLocal.sol`, `EnterpriseIAMLocal.sol`, `DIDFacetLocal.sol`, `DIDMessageLib.sol`
* ERC-8004: `ERC8004Adapter.sol`
* Credit: `CreditScore.sol`
* Prediction (Polymarket fork, P2): `ConditionalTokens.sol`, `CTFExchange.sol`, `OracleResolver.sol`

完整地址表见 [Chain 391 合约地址](/consolidated-resources/contract-addresses-chain-391.md)。

## 设计原则

1. **每一层独立可验证** — 任何一层的 fraud / 升级不影响其他层正常工作
2. **写权限 permissionless，读权限公开** — 任何人都可以注册 BehaviorSpec / Model / Policy；consumer 自己选信任谁
3. **经济安全 + 时间窗口** — L0 用 7-day challenge + 0.5 ETH stake (PoC) 保证 aggregator 不能无成本作恶
4. **跨语言 byte-pin** — Rust / Sol / TypeScript 三栈通过 12 个 keccak literal 保持一致；任何一栈改了 leaf encoding，其他栈编译期 fail
5. **Mock 必有 swap 路径** — 当前 mock 的 Halo2 / DCAP / SLM 都有明确的真实现 roadmap（[EZKL roadmap](https://github.com/leeleeEcho/babyDriver_Layer2/blob/main/docs/guides/ezkl-halo2-swap-roadmap-2026-04-30.md)）

## 与传统区块链的差异

| 维度            | 传统 EVM L1 | 一般 L2 Rollup | **AxBlade**                                      |
| ------------- | --------- | ------------ | ------------------------------------------------ |
| 主要服务对象        | 用户钱包      | 用户钱包 + DeFi  | **AI Agent** + 用户                                |
| 系统合约扩展        | 不支持       | 不支持          | OracleHub / DID / IdentityVerifier 入 system slot |
| Fraud-proof 域 | DA only   | 任意 tx        | **Behavior layer**                               |
| 监管协议          | 无         | 无            | **L4 EU AI Act / NIST RMF 模板**                   |
| 解释性协议         | 无         | 无            | **L3 SLM + XAI on-chain**                        |
| 可解释 ZK        | optional  | optional     | **L1 zkML 内置**                                   |

相关：

[系统拓扑图](/overview/system-diagram.md) → 部署形态、链下基础设施、消息流。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://yellowpaper.axblade.io/overview/5-layer-architecture.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
