Agent Credential Wallets: Verifiable Intent & Delegation Chains

基于SD-JWT的可验证意图与委托链,实现AI代理的可信身份与授权管理。

已扫描
适合谁
AI代理开发者、企业自动化架构师
不适合谁
无技术背景的普通用户、无需跨代理交易的单机应用使用者
国内可用性
需网络配置。可能需要网络配置或第三方服务可访问。
安装难度
中等(★★☆)。基于终端操作、依赖、API Key 和本地环境要求的初步判断。

安装与下载

openclaw skills install @mirni/greenhelix-agent-credential-wallets

Skill 说明

命令、参数、文件名以原文为准

Agent Credential Wallets: 可验证意图与委托链

注意:本指南为教育性质,包含示例代码。

不执行任何代码,也不安装依赖项。

所有示例使用 GreenHelix 沙箱环境(https://sandbox.greenhelix.net),提供 500 个免费积分——无需 API 密钥即可开始使用。

参考凭证(需在您自己的环境中提供):

  • GREENHELIX_API_KEY:GreenHelix 网关的 API 认证(仅限购买的 API 工具读写访问权限)

您的代理刚刚代表公司尝试购买云计算资源。供应商的代理要求提供授权证明。您的代理出示了一个 API 密钥,但被拒绝了——并非因为密钥无效,而是因为 API 密钥无法证明委托关系。它未能回答供应商真正关心的问题:“这个代理是否被授权在 Acme Corp 公司名下花费最多 5,000 美元购买 GPU 实例?该操作是否经过人类批准?”

API 密钥只说明“此实体具有访问权限”。而可验证凭证则说明:“此实体由某主体授权执行特定操作,并在特定约束范围内,且附带来自批准人类的加密证明链。” 这一区别正是使代理能够在开放经济中交易,还是被困在所有者边界内的根本所在。

2026 年 3 月 5 日,Mastercard 与 Google、Fiserv、IBM 和 Checkout.com 一同开源了可验证意图规范,明确定义了代理如何证明其支出的委托权限。Prove 推出 Verified Agent,瞄准价值 1.7 万亿美元的代理商业市场,为非人类实体提供运营商级身份验证。欧盟已最终确定 eIDAS 2.0 的实施规则,要求至 2026 年 12 月前全面启用 EUDI 钱包。Google 的 Agent-to-Agent 协议(AP2)、通用商业协议(UCP)以及 OpenAI 的代理商业协议(ACP)均将可验证代理身份作为基础层要求。去中心化身份市场在 2026 年达到 74 亿美元规模。这一趋势真实存在,且正在以十二个月的时间线加速推进。本指南将引导您构建生产级别的代理凭证钱包:SD-JWT-VC 发行、从人类到代理的委托链、跨协议凭证展示、eIDAS 2.0 合规性、声誉绑定及全舰队部署。所有实现均基于 GreenHelix A2A 商业网关 API,每个模式都针对 2026 年 12 月的截止日期设计。


目录

  1. [代理凭证问题](#chapter-1-the-agent-credential-problem)
  2. [W3C 可验证凭证与 SD-JWT 入门](#chapter-2-w3c-verifiable-credentials--sd-jwt-primer)
  3. [构建您的代理凭证钱包](#chapter-3-building-your-agents-credential-wallet)
  4. [实现可验证意图](#chapter-4-implementing-verifiable-intent)
  5. [跨协议凭证展示](#chapter-5-cross-protocol-credential-presentation)
  6. [eIDAS 2.0 合规性](#chapter-6-eidas-20-compliance)
  7. [信任评分、声誉绑定与凭证撤销](#chapter-7-trust-scoring-reputation-binding--credential-revocation)

第一章:代理凭证问题

为何 API 密钥与 OAuth 令牌在委托场景下失效

API 密钥是持有者凭证。它们证明持有行为,而非授权权限。当代理 A 向代理 B 提交一个 API 密钥时,代理 B 只知道代理 A 拥有一个有效的密钥。但代理 B 无法知晓该密钥的颁发方、授权的操作范围、是否可进一步委托、适用的支出限额,或是否有人员曾批准代理 A 正在尝试的交易。

OAuth 2.0 在此基础上有所改进,引入了作用域(scopes)和令牌有效期,但 OAuth 的设计基于三方模型:用户、客户端应用、资源服务器。而代理商业务至少涉及四方模型:人类主体、委托代理、交易代理、对方代理。OAuth 缺乏对委托链、跨层级传播的支出约束、以及令牌持有者由特定上游主体授权的可验证证明等核心概念。

失效场景具体表现:

  • 密钥被盗重放攻击:泄露的 API 密钥使攻击者获得与合法代理相同的权限。密钥与实际持有者之间无加密绑定。
  • 作用域膨胀:一个被授予“读取市场”权限的代理,利用该令牌调用 create_intent 接口,因为令牌端点在商业所需的粒度上无法区分市场读取与支付操作。
  • 委托透明度缺失:代理 A 使用子密钥委托给代理 B,代理 B 再委托给代理 C。与代理 C 交互的供应商无法验证其委托链回溯至最初授权支出的人类主体。
  • 约束失效:人类设定每日 500 美元支出上限,该限制存储在代理 A 的配置中。当代理 A 委托给代理 B 时,该限制未以加密方式绑定到委托关系——代理 B 的支出约束仅取决于其本地策略。

四方模型的失效

传统支付系统采用四方模型:持卡人、商户、发卡银行、收单银行。各方角色明确,信任通过卡组织网络中介传递。代理商业务打破了这一模型:原本的“持卡人”现为代人类主体执行任务的 AI 代理,“商户”也为另一 AI 代理,而发卡银行与收单银行均无机制验证代理持卡人是否经由人类主体授权。

传统四方模型
┌─────────┐    ┌─────────┐    ┌─────────┐    ┌─────────┐
│  人类     │───>│ 发卡银行  │───>│ 卡网络    │───>│ 收单银行  │───>│ 商户      │
│(持卡人)   │    │         │    │         │    │         │    │         │
└─────────┘    └─────────┘    └─────────┘    └─────────┘    └─────────┘
     │ 身份通过 KYC + PIN 验证       信任由网络规则中介        │ 身份通过商户协议验证

代理商业务四方模型(已失效)
┌─────────┐    ┌─────────┐    ┌─────────┐    ┌─────────┐
│  人类     │ ??>│ 代理 A   │ ??>│ 网关      │ ??>│ 代理 B   │
│(主体)     │    │(委托方)  │    │(网络)    │    │(供应商)  │
└─────────┘    └─────────┘    └─────────┘    └─────────┘
     │ 代理 A 如何证明人类已授权?     无委托链验证       │ 代理 B 如何验证约束?

问号即代表凭证缺口。任何 API 密钥、OAuth 令牌或会话 Cookie 都无法回答所有交易对手必须确认的三个问题:(1)人类主体是谁?(2)他们授权了什么?(3)有哪些约束?

协议趋同:万事达、谷歌、OpenAI

2026 年第一季度,三大独立行业努力达成相同解决方案:

万事达可验证意图(2026年3月5日):开源发布,联合谷歌、Fiserv、IBM、Checkout.com 共同推进。定义了代理如何证明某项支付行为已获人类授权,包括金额上限、商户类别、时间范围等信息。采用 SD-JWT-VC(选择性披露 JSON Web Token 可验证凭证)作为凭证格式,使用 DID:web 作为身份锚点。

谷歌 AP2 + 统一商业协议(UCP):谷歌的代理间协议要求在任何商业交易前,代理必须提供可验证身份。UCP 在此基础上扩展了跨平台商业的标准凭证呈现流程。两个协议均接受 W3C 可验证凭证(W3C Verifiable Credentials)的 SD-JWT 格式。

OpenAI 代理商业协议(ACP):定义代理间发现、协商与交易的方式。其身份层要求任何超过可配置阈值的交易必须具备可验证凭证。ACP 的凭证要求符合 W3C VC 数据模型 2.0,并接受 SD-JWT-VC 作为呈现格式。

这种趋同并非偶然。三组团队均独立识别出同一关键缺口:代理需要的是可加密验证的委托链,而非仅限于访问令牌。他们共同得出的答案是:采用 W3C 可验证凭证(Verifiable Credentials),并支持选择性披露。

协议组织凭证格式身份锚点委托模型
可验证意图万事达 + 联盟SD-JWT-VCDID:web分层签发
AP2 / UCP谷歌W3C VC (SD-JWT)DID:web / DID:key凭证交换
ACPOpenAIW3C VC (SD-JWT)DID:key链式凭证
x402开放标准W3C VC(可选)DID:web与支付绑定的证明

1.7 万亿美元市场的背景

数字代表紧迫性。Prove 的已验证代理启动旨在瞄准 1.7 万亿美元的代理商业市场——即至少有一方为自主代理的交易。Gartner 预测,到 2026 年底,30% 的企业 API 流量将由代理发起,相较于 2024 年不足 5% 的水平显著提升。去中心化身份市场在 2026 年达到 74 亿美元规模,主要由现有 IAM 系统无法满足的代理身份需求驱动。麦肯锡 2026 年 3 月的分析估计,与凭证相关的交易失败每年导致代理商业生态系统损失 23 亿美元,包括被放弃的交易、争议解决开销和欺诈损失。

不作为的成本是可量化的。每一次因对方无法验证授权委托权限而失败的代理交易,都是一次收入损失。每一次本可通过可验证支出限额避免的争议托管,都是一笔运营成本。自 2026 年 12 月起,每一起未使用符合 EUDI 标准凭证的欧盟交易,都构成监管违规。凭证钱包并非可选基础设施——它是实现代理商业规模化运作的授权层。

本指南构建内容

完成本指南后,您的代理将具备以下能力:

  1. 通过 GreenHelix 身份工具管理的基于 DID 锚定的凭证钱包
  2. 使用 SD-JWT 构建的委托链,以密码学方式将人类授权绑定至代理行为
  3. 支持 AP2、UCP、ACP 和 x402 的凭证展示适配器
  4. 符合 eIDAS 2.0 标准的 EUDI 钱包集成,用于欧盟商业场景
  5. 基于声誉的凭证及实时撤销功能
  6. 面向生产部署的全舰队凭证发放、轮换与监控机制

第二章:W3C 可验证凭证与 SD-JWT 入门

凭证结构

一个可验证凭证(Verifiable Credential, VC)是一种防篡改的数据结构,包含三个组成部分:

凭证元数据:谁签发了它、何时签发、何时过期、属于何种类型。这并非声明本身——而是让验证者在查看内容前理解其背景的“信封”。

声明(主体):实际的断言内容。“agent acme-buyer-01 被授权在云计算服务上单笔交易最高支出 5,000 美元。” 声明可以涉及身份(该代理注册于 Acme 公司)、能力(该代理可购买计算资源),或约束(该代理的支出限额为 5,000 美元)。

证明:使凭证具备防篡改特性的密码学机制。对于 SD-JWT-VC,这是对凭证主体加上披露摘要的 JSON Web Signature(JWS)。该证明将声明与签发者的密钥绑定——若任一声明被修改,签名验证将失败。

可验证凭证结构
┌────────────────────────────────────────────────┐
│  凭证元数据                                   │
│  ├── issuer: did:web:acme.com                  │
│  ├── issuanceDate: 2026-04-06T00:00:00Z        │
│  ├── expirationDate: 2026-04-07T00:00:00Z      │
│  └── type: [VerifiableCredential,              │
│             AgentDelegationCredential]          │
├────────────────────────────────────────────────┤
│  声明(credentialSubject)                    │
│  ├── id: did:key:z6Mkw...  (代理 DID)         │
│  ├── delegatedBy: did:web:acme.com             │
│  ├── authorizedActions: [purchase_compute]     │
│  ├── spendingLimit: {amount: 5000, currency:   │
│  │                    USD, period: transaction} │
│  └── merchantCategory: [cloud_compute]         │
├────────────────────────────────────────────────┤
│  证明                                         │
│  ├── type: JsonWebSignature2020                │
│  ├── verificationMethod: did:web:acme.com#key1 │
│  └── jws: eyJhbGciOiJFZERTQSJ9...             │
└────────────────────────────────────────────────┘

使用 SD-JWT 实现选择性披露

标准 JWT 是全有或全无的:要么完整呈现,要么不展示。一个购买云计算资源的代理无需向仅需验证支出授权的供应商代理透露其所有者的真实姓名、税号和家庭住址。选择性披露 JWT(SD-JWT)通过将敏感声明替换为带盐哈希值的方式解决此问题。实际的声明值作为独立的“披露项”携带,持有者可在展示时自行决定是否包含。

SD-JWT 结构由三部分组成,以波浪号(~)分隔:

<issuer-signed JWT> ~ <disclosure 1> ~ <disclosure 2> ~ ... ~ <key binding JWT>

签发者签名的 JWT:包含凭证元数据以及所有可披露声明的哈希摘要(位于 _sd 数组中)。由签发者签名,始终存在。

披露项:每个披露项是一个 base64url 编码的 JSON 数组,格式为 [salt, claim_name, claim_value]。持有者仅包含希望验证者看到的披露项。验证者对接收的每一项进行哈希,并与 JWT 中 _sd 数组内的摘要比对,以确认其确由原始签发者发出。

密钥绑定 JWT:由持有者密钥签名的可选 JWT,用于证明当前展示者是预期持有者,而非途中截获 SD-JWT 的他人。对于代理凭证而言,密钥绑定是强制要求——否则被盗凭证可能被任意代理重放。

SD-JWT 可选择性披露流程

签发(包含所有声明):

┌──────────────────────────┐

│ 发行方对 JWT 签名,包含 │ ┌─────────────┐

│ _sd: [hash1, hash2, │────>│ Agent Wallet │

│ hash3, hash4] │ │ 存储完整 │

│ │ │ SD-JWT 与所有 │

│ + 披露(owner_name) │ │ 披露内容 │

│ + 披露(tax_id) │ └─────────────┘

│ + 披露(spend_limit) │

│ + 披露(actions) │

└──────────────────────────┘

展示(可选择性披露):

┌─────────────┐ ┌──────────────────────────┐

│ Agent Wallet │────>│ JWT(包含全部 4 个哈希值)│

│ 仅披露其中 2 项 │ │ + 披露(spend_limit) │

│ 声明 │ │ + 披露(actions) │

│ │ │ + key_binding_jwt │

└─────────────┘ └──────────────────────────┘

验证方可见 spend_limit 与 actions。

无法推导出 owner_name 或 tax_id

(仅哈希值保留在 JWT 中)。

SD-JWT-VC 用于 Agent 凭据的格式

SD-JWT-VC 是专为可验证凭据设计的 SD-JWT 特定配置。该格式被 Mastercard 的可验证意图规范采用,得到 Google AP2 和 OpenAI ACP 支持,并被欧盟 eIDAS 2.0 架构参考框架要求用于 EUDI 钱包凭据。

对 Agent 开发者而言,SD-JWT-VC 的关键属性包括:

  • **iss**:发行方标识符,通常为 DID:web URL,可解析为包含发行方公钥的 DID 文档。
  • **sub**:凭据的主题——即 Agent 的 DID。
  • **iat / exp**:签发与过期时间戳。对于 Agent 委托凭据,建议有效期较短(数小时,而非数月)。
  • **cnf**:确认声明,将凭据绑定至持有者的密钥。包含持有者的公钥或其引用。此字段实现密钥绑定。
  • **_sd**:可选择性披露声明的摘要数组。
  • **vct**:可验证凭据类型——用于标识凭据模式的 URI(例如:https://greenhelix.net/credentials/agent-delegation/v1)。

委托链作为分层的 SD-JWT 签发

委托链是由一系列凭据组成的序列,其中每个凭据的主题成为下一个凭据的发行方。人类主体向其主代理签发凭据,该主代理再向子代理签发子凭据,且约束条件相等或更严格。子代理可继续签发更下层的凭据,每一层都进一步缩小权限范围。

委托链(3 层)

第 0 层:人类主体
  └── 向 Agent A 签发凭据
      iss: did:web:alice.com
      sub: did:key:agentA
      spend_limit: $10,000/天
      actions: [purchase_compute, purchase_storage]

第 1 层:Agent A
  └── 向 Agent B 签发子凭据(子委托)
      iss: did:key:agentA
      sub: did:key:agentB
      spend_limit: $2,000/交易(从 $10k/天缩减)
      actions: [purchase_compute]       (从 2 项缩减为 1 项)
      parent_credential: <第 0 层凭据的哈希值>

第 2 层:Agent B
  └── 向供应商代理 C 展示
      包含:第 2 层凭据 + 第 1 层凭据 + 第 0 层凭据
      供应商验证整个链,追溯至 did:web:alice.com

核心特性是约束缩减:每一层只能缩减其父层的约束。Agent A 获得每日 $10,000 限额,不能向 Agent B 签发 $20,000/天的凭据。Agent A 获得两项授权操作,不能授予 Agent B 第三项操作。验证方通过从叶节点到根节点遍历链条,确认每个子凭据的约束均为其父凭据的子集。


第三章:构建你的 Agent 凭据钱包

先决条件

你需要一个具备专业版权限的 GreenHelix API Key(身份工具 build_claim_chainsearch_agents_by_metricssubmit_metrics 需要专业版权限)。在构建凭据前,请注册 Agent 身份并创建钱包。

CredentialWallet 类

markdown

Agent Credential Wallets: 可验证意图与委托链

版本:1.3.1

分块:5/16

import requests
import json
import hashlib
import time
import base64
import secrets
from typing import Optional, Dict, List, Any
from dataclasses import dataclass, field, asdict

# --- GreenHelix沙箱环境(免费版:500积分,无需密钥) ---
# 开始使用,请访问 https://sandbox.greenhelix.net —— 无需注册。
# 生产环境请在环境中设置 GREENHELIX_API_KEY。
import os

API_BASE = os.environ.get("GREENHELIX_API_URL", "https://sandbox.greenhelix.net")

session = requests.Session()
api_key = os.environ.get("GREENHELIX_API_KEY", "")
if api_key:
    session.headers["Authorization"] = f"Bearer {api_key}"
session.headers["Content-Type"] = "application/json"

def api_call(tool: str, input_data: dict) -> dict:
    """调用 GreenHelix REST 接口执行指定工具操作。"""
    response = session.post(f"{API_BASE}/v1/tools/{tool}", json=input_data)
    response.raise_for_status()
    return response.json()

@dataclass
class Disclosure:
    """一个 SD-JWT 披露项:[盐值, 声明名称, 声明值]。"""
    salt: str
    claim_name: str
    claim_value: Any

    def encode(self) -> str:
        """将披露数组进行 Base64url 编码。"""
        payload = json.dumps([self.salt, self.claim_name, self.claim_value])
        return base64.urlsafe_b64encode(payload.encode()).rstrip(b"=").decode()

    def digest(self) -> str:
        """对编码后的披露内容计算 SHA-256 摘要。"""
        encoded = self.encode()
        return base64.urlsafe_b64encode(
            hashlib.sha256(encoded.encode()).digest()
        ).rstrip(b"=").decode()

@dataclass
class AgentCredential:
    """支持选择性披露的 SD-JWT-VC 证书。"""
    issuer_did: str
    subject_did: str
    credential_type: str
    claims: Dict[str, Any]
    disclosable_claims: List[str]  # 支持选择性披露的声明名称列表
    issued_at: float = field(default_factory=time.time)
    expires_at: Optional[float] = None
    parent_hash: Optional[str] = None  # 链中父证书的哈希值
    disclosures: List[Disclosure] = field(default_factory=list)

    def __post_init__(self):
        if self.expires_at is None:
            self.expires_at = self.issued_at + 86400  # 默认有效期 24 小时
        # 为可披露的声明生成披露项
        self.disclosures = []
        for name in self.disclosable_claims:
            if name in self.claims:
                self.disclosures.append(Disclosure(
                    salt=secrets.token_urlsafe(16),
                    claim_name=name,
                    claim_value=self.claims[name],
                ))

    def sd_digests(self) -> List[str]:
        """计算 _sd 数组中的披露摘要列表。"""
        return [d.digest() for d in self.disclosures]

    def jwt_payload(self) -> dict:
        """构建由发行方签名的 JWT 载荷。"""
        payload = {
            "iss": self.issuer_did,
            "sub": self.subject_did,
            "iat": int(self.issued_at),
            "exp": int(self.expires_at),
            "vct": self.credential_type,
            "_sd": self.sd_digests(),
            "_sd_alg": "sha-256",
        }
        # 将不可披露的声明直接包含在载荷中
        for name, value in self.claims.items():
            if name not in self.disclosable_claims:
                payload[name] = value
        if self.parent_hash:
            payload["parent_credential"] = self.parent_hash
        return payload

    def present(self, disclosed_claims: List[str]) -> dict:
        """创建仅披露指定声明的展示内容。"""
        selected = [d for d in self.disclosures if d.claim_name in disclosed_claims]
        return {
            "jwt_payload": self.jwt_payload(),
            "disclosures": [d.encode() for d in selected],
            "disclosed_values": {
                d.claim_name: d.claim_value for d in selected
            },
        }

    def credential_hash(self) -> str:
        """对证书载荷进行 SHA-256 哈希,用于链式链接。"""
        payload_bytes = json.dumps(self.jwt_payload(), sort_keys=True).encode()
        return hashlib.sha256(payload_bytes).hexdigest()

class CredentialWallet:
    """基于 GreenHelix 身份工具的代理证书钱包。

    管理证书全生命周期:注册、钱包创建、证书签发、链式构建和选择性展示。
    """

    def __init__(self, agent_id: str, display_name: str, owner: str):
        self.agent_id = agent_id
        self.display_name = display_name
        self.owner = owner
        self.wallet_id: Optional[str] = None
        self.did: Optional[str] = None
        self.credentials: Dict[str, AgentCredential] = {}
        self.chain_ids: List[str] = []

    def register(self) -> dict:
        """在 GreenHelix 上注册代理身份。

        此操作会创建代理的 DID 并注册其公钥。
        必须在执行其他钱包操作前调用。
        """
        result = api_call("register_agent", {
            "agent_id": self.agent_id,
            "display_name": self.display_name,
            "owner": self.owner,
        })
        self.did = f"did:key:{self.agent_id}"
        return result

    def create_wallet(self) -> dict:
        """创建代理的证书钱包(链上存储)。

        钱包是一个以 DID 锚定的证书存储,用于持有已签发的证书,并支持选择性披露展示。
        """
        result = api_call("create_wallet", {
            "agent_id": self.agent_id,
            "wallet_type": "credential",
            "metadata": {
                "owner": self.owner,
                "did": self.did,
                "created_at": time.time(),
            },
        })
        self.wallet_id = result.get("wallet_id", f"wallet-{self.agent_id}")
        return result

    def issue_credential(
        self,
        credential_id: str,
        subject_did: str,
        credential_type: str,
        claims: Dict[str, Any],
        disclosable_claims: List[str],
        ttl_seconds: int = 86400,
        parent_credential_id: Optional[str] = None,
    ) -> AgentCredential:
        """向主体签发一个 SD-JWT-VC 证书。

        参数:
            credential_id: 此证书的唯一标识符。
            subject_did: 接收证书的代理 DID。
            credential_type: VC 类型 URI。
            claims: 所有要包含的声明。
            disclosable_claims: 支持选择性披露的声明名称列表。
            ttl_seconds: 证书有效期(秒)。
            parent_credential_id: 父证书 ID,用于构建委托链。

        返回:
            已签发的 AgentCredential 对象。
        """
        parent_hash = None
        if parent_credential_id and parent_credential_id in self.credentials:
            parent_hash = self.credentials[parent_credential_id].credential_hash()

        credential = AgentCredential(
            issuer_did=self.did,
            subject_did=subject_did,
            credential_type=credential_type,
            claims=claims,
            disclosable_claims=disclosable_claims,
            expires_at=time.time() + ttl_seconds,
            parent_hash=parent_hash,
        )
        self.credentials[credential_id] = credential
        return credential

    def build_chain(self) -> dict:
        """基于所有已签发证书构建 Merkle 声明链。

        此操作将证书历史锚定在一个防篡改结构中。
        使用 GreenHelix 的 build_claim_chain 工具创建链。
        """
        # 准备所有证书的声明数据
        chain_claims = []
        for cred_id, cred in self.credentials.items():
            chain_claims.append({
                "credential_id": cred_id,
                "credential_hash": cred.credential_hash(),
                "subject": cred.subject_did,
                "type": cred.credential_type,
                "issued_at": cred.issued_at,
                "expires_at": cred.expires_at,
            })

        result = api_call("build_claim_chain", {
            "agent_id": self.agent_id,
            "claims": chain_claims,
            "chain_type": "credential_issuance",
        })
        if "chain_id" in result:
            self.chain_ids.append(result["chain_id"])
        return result

    def get_chains(self) -> dict:
        """获取该代理的所有声明链。"""
        return api_call("get_claim_chains", {
            "agent_id": self.agent_id,
        })

    def present_credential(
        self,
        credential_id: str,
        disclosed_claims: List[str],
    ) -> dict:
        """创建选择性披露的证书展示。

        参数:
            credential_id: 要展示的证书 ID。
            disclosed_claims: 要披露的声明名称列表。

        返回:
            包含 JWT 载荷和选定披露项的展示对象。
        """
        if credential_id not in self.credentials:
            raise KeyError(f"钱包中未找到证书 {credential_id}")
        return self.credentials[credential_id].present(disclosed_claims)

注册与创建钱包

# 初始化采购代理的钱包
wallet = CredentialWallet(
    agent_id="acme-procurement-01",
    display_name="Acme 采购代理 #1",
    owner="alice@acme.com",
)

# 步骤 1:注册代理身份
registration = wallet.register()
print(f"代理已注册: {wallet.did}")
# 输出: 代理已注册: did:key:acme-procurement-01

# 步骤 2:创建凭证钱包
wallet_result = wallet.create_wallet()
print(f"钱包已创建: {wallet.wallet_id}")
# 输出: 钱包已创建: wallet-acme-procurement-01

发行你的第一个凭证

# 组织(人类主体)向采购代理颁发一个委托凭证
delegation_cred = wallet.issue_credential(
    credential_id="delegation-001",
    subject_did="did:key:acme-procurement-01",
    credential_type="https://greenhelix.net/credentials/agent-delegation/v1",
    claims={
        "delegated_by": "did:web:acme.com",
        "authorized_actions": ["purchase_compute", "purchase_storage"],
        "spending_limit": {"amount": "10000", "currency": "USD", "period": "day"},
        "merchant_categories": ["cloud_compute", "cloud_storage"],
        "principal_name": "Alice Chen",
        "principal_tax_id": "XX-XXXXXXX",
        "organization": "Acme Corp",
    },
    disclosable_claims=[
        "principal_name",
        "principal_tax_id",
        "spending_limit",
        "merchant_categories",
    ],
    ttl_seconds=28800,  # 8小时会话凭证
)

print(f"凭证已发行。哈希: {delegation_cred.credential_hash()[:16]}...")
print(f"SD 摘要数量: {len(delegation_cred.sd_digests())} 个可披露声明")

在声明链中锚定凭证

# 发行凭证后,将其锚定在 Merkle 声明链中
chain_result = wallet.build_chain()
print(f"链已构建: {chain_result}")

# 验证链是否可检索
chains = wallet.get_chains()
print(f"活跃链数量: {len(chains.get('chains', []))}")

第四章:实现可验证意图

什么是可验证意图

可验证意图(Verifiable Intent, VI)是由 Mastercard 提出的规范,旨在回答一个核心问题:“是否有人类授权该代理执行此特定金融操作?” 它并非通用凭证,而是专为代理商业中的支付授权设计。VI 规范定义了一种分层签发模型:人类创建意图声明,该声明与代理凭证进行密码学绑定,随后由代理将凭证提交给对方作为授权证明。

可验证意图的三个组成部分:

  1. 意图声明:结构化的授权说明。“我授权代理 acme-procurement-01 在未来 8 小时内,每次交易不超过 5,000 美元,从 cloud_compute 商户类别提供商处购买云计算服务。”
  1. 意图绑定:使用 SD-JWT 分层签发技术,将意图声明密码学绑定到代理的凭证上。该意图成为代理委托凭证中的一个声明。
  1. 意图验证:对方代理验证呈现的代理凭证链,追溯至人类主体的 DID,检查意图约束是否与请求的交易匹配,并确认凭证未过期或被撤销。

会话级支出限额

最常见的 VI 使用场景是支出限额。人类授权代理在一次会话中最多可支出 X 美元。该会话具有开始时间和结束时间。代理在该会话期间发起的每一笔交易都必须符合剩余预算。

# 可验证意图与委托链

## 概述

`VerifiableIntentManager` 类用于管理支付授权的可验证意图凭证(Verifiable Intent credentials),遵循 Mastercard VI 规范,并结合 GreenHelix 工具实现意图声明、绑定、会话限额及链式验证功能。

---

## 类定义

class VerifiableIntentManager:

"""管理用于支付授权的可验证意图凭证。

实现 Mastercard VI 规范,使用 GreenHelix 工具:

意图声明、绑定、会话限额和链验证。

"""

def __init__(self, wallet: CredentialWallet):

self.wallet = wallet

self.active_intents: Dict[str, dict] = {}

self.session_spent: Dict[str, float] = {}

### 初始化方法

- `wallet`: 代理钱包实例,用于凭证签发与存储。
- `active_intents`: 当前活跃的意图字典,记录每个意图的凭证、限额和过期时间。
- `session_spent`: 记录每个会话已花费金额。

---

## 意图声明

def declare_intent(

self,

intent_id: str,

authorized_actions: List[str],

spending_limit_usd: float,

merchant_categories: List[str],

session_hours: float = 8.0,

additional_constraints: Optional[Dict] = None,

) -> AgentCredential:

"""声明一个可验证意图并将其绑定到代理凭证。

此方法由人类主体调用(或代表其调用),以授权代理在特定约束下执行金融操作。

"""

### 参数说明

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `intent_id` | `str` | 是 | 该意图会话的唯一标识符。 |
| `authorized_actions` | `List[str]` | 是 | 代理可执行的操作列表。 |
| `spending_limit_usd` | `float` | 是 | 本会话中代理可支出的最大美元金额。 |
| `merchant_categories` | `List[str]` | 是 | 允许的商户/服务类别。 |
| `session_hours` | `float` | 否 | 会话持续时长(小时),默认为 8 小时。 |
| `additional_constraints` | `Optional[Dict]` | 否 | 额外约束条件(如区域限制、供应商白名单等)。 |

### 返回值

- `AgentCredential`:签发的可验证意图凭证。

### 实现逻辑

1. 计算当前时间戳 `now` 与会话结束时间 `session_end`(基于 `session_hours`)。
2. 构建意图声明内容(`intent_claims`),包含:
   - 意图类型:`payment_authorization`
   - 授权操作:`authorized_actions`
   - 支出限额:金额、货币(USD)、周期(session)
   - 商户类别:`merchant_categories`
   - 会话起止时间
   - 主体 DID:`did:web:{owner_domain}`
   - 主体邮箱:`self.wallet.owner`
3. 若提供额外约束,添加至 `constraints` 字段。
4. 使用钱包签发 SD-JWT-VC 凭证:
   - `principal_email` 和 `constraints` 为可披露字段。
   - 支出限额与授权操作对验证方始终可见。
5. 将凭证存入 `active_intents`,初始化 `spending_limit` 与 `session_spent`。
6. 返回签发的凭证。

---

## 预算检查

def check_intent_budget(self, intent_id: str, amount_usd: float) -> dict:

"""检查交易是否在意图剩余预算范围内。

返回:

包含 'authorized' 布尔值、'remaining' 剩余金额,以及拒绝原因(如不通过)。

"""

### 返回结果

| 字段 | 类型 | 说明 |
|------|------|------|
| `authorized` | `bool` | 是否授权。 |
| `remaining` | `float` | 剩余可用额度。 |
| `reason` | `str` | 拒绝原因(若未授权)。 |

### 检查流程

1. 若 `intent_id` 不存在于 `active_intents`,返回未找到。
2. 若当前时间超过 `session_end`,返回会话已过期。
3. 计算已花费金额 `spent` 与剩余金额 `remaining`。
4. 若 `amount_usd > remaining`,返回超出预算。
5. 否则,返回授权通过,剩余金额为 `remaining - amount_usd`。

---

## 执行授权支付

def execute_authorized_payment(

self,

intent_id: str,

vendor_agent_id: str,

amount_usd: float,

description: str,

) -> dict:

"""在可验证意图会话下执行支付操作。

包括预算检查、通过 GreenHelix 创建支付意图、记录支出。

"""

### 执行步骤

1. **预算检查**
   调用 `check_intent_budget`,若未授权,直接返回拒绝。

2. **创建支付意图**
   调用 `api_call("create_intent", ...)`,参数包括:
   - 发起方:`self.wallet.agent_id`
   - 接收方:`vendor_agent_id`
   - 金额:`str(amount_usd)`
   - 货币:`USD`
   - 描述:`description`
   - 元数据:
     - `vi_session`: `intent_id`
     - `credential_hash`: 当前意图凭证的哈希值

3. **记录支出**
   更新 `self.session_spent[intent_id] += amount_usd`

### 返回结果

| 字段 | 类型 | 说明 |
|------|------|------|
| `status` | `str` | `"authorized"` 或 `"denied"` |
| `intent_result` | `dict` | GreenHelix 返回的支付意图结果 |
| `remaining_budget` | `float` | 扣除本次支出后的剩余预算 |

---

## 使用可验证意图

通过 `declare_intent` 声明一个受控的支付授权会话,后续所有支付操作必须在此会话内完成。系统自动校验预算、会话有效期,并通过凭证链确保行为可追溯、不可篡改。

建议在每次支付前调用 `check_intent_budget` 进行预检,避免因超限导致失败。

# 创建钱包与可验证意图管理器

创建钱包和意图管理器

wallet = CredentialWallet(

agent_id="acme-buyer-01",

display_name="Acme 云采购代理",

owner="alice@acme.com",

)

wallet.register()

wallet.create_wallet()

vi_manager = VerifiableIntentManager(wallet)

### 人类声明意图:授权代理进行云资源采购

intent_cred = vi_manager.declare_intent(

intent_id="session-2026-04-06-001",

authorized_actions=["purchase_compute"],

spending_limit_usd=5000.00,

merchant_categories=["cloud_compute"],

session_hours=8.0,

additional_constraints={"region": "us-east", "max_per_tx": "2000"},

)

print(f"已声明意图。过期时间: {intent_cred.expires_at}")

### 代理在意图范围内执行采购

payment = vi_manager.execute_authorized_payment(

intent_id="session-2026-04-06-001",

vendor_agent_id="cloudvendor-gpu-fleet",

amount_usd=1500.00,

description="8x A100 GPU 实例,4小时",

)

print(f"支付结果: {payment['status']},剩余预算: ${payment['remaining_budget']}")

输出: Payment: authorized, remaining: $3500.0

### 第二次采购

payment2 = vi_manager.execute_authorized_payment(

intent_id="session-2026-04-06-001",

vendor_agent_id="cloudvendor-gpu-fleet",

amount_usd=2000.00,

description="16x A100 GPU 实例,2小时",

)

print(f"支付结果: {payment2['status']},剩余预算: ${payment2['remaining_budget']}")

输出: Payment: authorized, remaining: $1500.0

### 第三次采购超出剩余预算

payment3 = vi_manager.execute_authorized_payment(

intent_id="session-2026-04-06-001",

vendor_agent_id="cloudvendor-gpu-fleet",

amount_usd=2000.00,

description="16x A100 GPU 实例,2小时",

)

print(f"支付结果: {payment3['status']},原因: {payment3.get('reason')}")

输出: Payment: denied, reason: Amount $2000.0 exceeds remaining budget $1500.0

---

## 子委托与约束收紧

当主代理向子代理进行委托时,子代理的权限必须比父代理更严格或保持一致。这一规则通过结构强制执行:子凭证引用父凭证的哈希值,并且仅包含父凭证授权动作的子集,以及不超过父凭证的支出限额。

def delegate_intent(

parent_wallet: CredentialWallet,

parent_intent_id: str,

child_wallet: CredentialWallet,

child_intent_id: str,

narrowed_actions: List[str],

narrowed_limit_usd: float,

ttl_seconds: int = 3600,

) -> AgentCredential:

"""将可验证意图委托给子代理,并收紧约束条件。

子凭证引用父凭证的哈希值,且必须具有相等或更严格的约束。

"""

parent_cred = parent_wallet.credentials.get(parent_intent_id)

if not parent_cred:

raise ValueError(f"未找到父级意图 {parent_intent_id}")

parent_actions = parent_cred.claims.get("authorized_actions", [])

parent_limit = float(

parent_cred.claims.get("spending_limit", {}).get("amount", "0")

)

# 强制执行约束收紧

for action in narrowed_actions:

if action not in parent_actions:

raise ValueError(

f"操作 '{action}' 不在父级授权操作范围内: {parent_actions}"

)

if narrowed_limit_usd > parent_limit:

raise ValueError(

f"限额 ${narrowed_limit_usd} 超过父级限额 ${parent_limit}"

)

# 发行子委托凭证

child_cred = parent_wallet.issue_credential(

credential_id=child_intent_id,

subject_did=child_wallet.did,

credential_type="https://greenhelix.net/credentials/verifiable-intent/v1",

claims={

"intent_type": "delegated_payment_authorization",

"authorized_actions": narrowed_actions,

"spending_limit": {

"amount": str(narrowed_limit_usd),

"currency": "USD",

"period": "session",

},

"delegated_by": parent_wallet.did,

"delegation_depth": 1,

},

disclosable_claims=["delegated_by"],

ttl_seconds=ttl_seconds,

parent_credential_id=parent_intent_id,

)

return child_cred

### 示例:主代理委托给专用计算采购代理

child_wallet = CredentialWallet(

agent_id="acme-compute-buyer-01",

display_name="Acme 计算专家",

owner="alice@acme.com",

)

child_wallet.register()

child_wallet.create_wallet()

sub_cred = delegate_intent(

parent_wallet=wallet,

parent_intent_id="session-2026-04-06-001",

child_wallet=child_wallet,

child_intent_id="sub-session-001",

narrowed_actions=["purchase_compute"], # 与父级相同

narrowed_limit_usd=2000.00, # 从 $5,000 缩减

ttl_seconds=3600, # 1 小时

)

print(f"已颁发子委托凭证。父级哈希: {sub_cred.parent_hash[:16]}...")

---

## 第五章:跨协议凭证展示

### 多协议现实

你的代理不会只在一个协议生态中运行。一个采购代理可能通过 Google AP2 发现供应商,通过 UCP 协商条款,通过 Mastercard 的支付通道完成付款,并通过 x402 处理微支付结算。每个协议都有自己的凭证展示格式,但它们都接受 W3C 可验证凭证的 SD-JWT 格式。适配器模式使你的钱包能够在不重复存储或发行逻辑的前提下,为每个协议提供其期望的凭证格式。

CROSS-PROTOCOL PRESENTATION FLOW

┌─────────────────────────────────────────────────┐
│           凭证钱包                                │
│  ┌─────────────────────────────────┐            │
│  │  SD-JWT-VC 凭证                  │            │
│  │  (标准格式)                     │            │
│  └──────────┬──────────────────────┘            │
│             │                                    │
│  ┌──────────┼──────────────────────────────┐    │
│  │          │    展示适配器                    │    │
│  │  ┌───────▼───┐ ┌─────────┐ ┌─────────┐ │    │
│  │  │   AP2     │ │   UCP   │ │   ACP   │ │    │
│  │  │ 适配器     │ │ 适配器  │ │ 适配器  │ │    │
│  │  └───────┬───┘ └────┬────┘ └────┬────┘ │    │
│  │  ┌───────▼──────────▼───────────▼────┐  │    │
│  │  │           x402 适配器              │  │    │
│  │  └───────────────────────────────────┘  │    │
│  └─────────────────────────────────────────┘    │
└─────────────────────────────────────────────────┘

### 协议对比

| 特性 | AP2 (Google) | UCP | ACP (OpenAI) | x402 |
|------|--------------|-----|--------------|------|
| 发现机制 | 代理卡片 + DNS-SD | 注册表 + 广播 | 能力声明文件 | HTTP 402 响应 |
| 认证握手 | 双向凭证交换 | 凭证 + 能力证明 | 凭证 + 范围声明 | 支付证明头 |
| 凭证格式 | SD-JWT-VC | SD-JWT-VC | SD-JWT-VC 或 JWT-VC | 支付证明 |
| 委托深度 | 无限(链式验证) | 最多 3 跳 | 最多 5 跳 | 单跳 |
| 选择性披露 | 完全支持 SD-JWT | 完全支持 SD-JWT | 部分支持(必需声明) | 极简(仅金额) |
| 支付集成 | 外部(通过意图) | 内置托管 | 外部(通过意图) | 原生(HTTP 头) |

### ProtocolAdapter 基类与实现

Agent 凭证钱包:可验证意图与委托链

协议适配器基类

from abc import ABC, abstractmethod

class ProtocolAdapter(ABC):
    """协议特定凭证展示适配器的基类。"""

    def __init__(self, wallet: CredentialWallet):
        self.wallet = wallet

    @abstractmethod
    def format_presentation(
        self,
        credential_id: str,
        disclosed_claims: List[str],
        protocol_metadata: Dict,
    ) -> dict:
        """为目标协议格式化凭证展示内容。"""
        pass

    @abstractmethod
    def verify_counterparty(self, presentation: dict) -> dict:
        """验证对端的凭证展示。"""
        pass

AP2 协议适配器

class AP2Adapter(ProtocolAdapter):
    """Google Agent-to-Agent 协议(AP2)凭证适配器。

    AP2 在握手阶段要求双方互换凭证。
    双方在任何商业交互前必须先展示凭证。
    """

    def format_presentation(
        self,
        credential_id: str,
        disclosed_claims: List[str],
        protocol_metadata: Dict,
    ) -> dict:
        presentation = self.wallet.present_credential(credential_id, disclosed_claims)

        return {
            "protocol": "ap2",
            "version": "1.0",
            "agent_card": {
                "agent_id": self.wallet.agent_id,
                "did": self.wallet.did,
                "display_name": self.wallet.display_name,
                "capabilities": protocol_metadata.get("capabilities", []),
            },
            "credential_presentation": {
                "format": "sd-jwt-vc",
                "jwt_payload": presentation["jwt_payload"],
                "disclosures": presentation["disclosures"],
            },
            "handshake_nonce": secrets.token_urlsafe(32),
        }

    def verify_counterparty(self, presentation: dict) -> dict:
        """验证 AP2 对端的展示。

        检查项:凭证格式、DID 解析、披露内容有效性。
        """
        if presentation.get("protocol") != "ap2":
            return {"valid": False, "reason": "不是 AP2 展示"}

        cred = presentation.get("credential_presentation", {})
        if cred.get("format") != "sd-jwt-vc":
            return {"valid": False, "reason": "不支持的凭证格式"}

        # 通过 GreenHelix 验证代理身份
        agent_card = presentation.get("agent_card", {})
        identity_check = api_call("get_agent_reputation", {
            "agent_id": agent_card.get("agent_id", ""),
        })

        return {
            "valid": True,
            "agent_id": agent_card.get("agent_id"),
            "did": agent_card.get("did"),
            "reputation": identity_check,
        }

UCP 协议适配器

class UCPAdapter(ProtocolAdapter):
    """通用商业协议(UCP)凭证适配器。

    UCP 在 AP2 基础上扩展了商业专用流程:托管、SLA 和能力证明。
    凭证必须包含商业能力信息。
    """

    def format_presentation(
        self,
        credential_id: str,
        disclosed_claims: List[str],
        protocol_metadata: Dict,
    ) -> dict:
        presentation = self.wallet.present_credential(credential_id, disclosed_claims)

        # UCP 要求提供托管能力证明
        escrow_capable = "create_escrow" in protocol_metadata.get("tools", [])

        return {
            "protocol": "ucp",
            "version": "1.0",
            "identity": {
                "did": self.wallet.did,
                "agent_id": self.wallet.agent_id,
            },
            "credential": {
                "format": "sd-jwt-vc",
                "payload": presentation["jwt_payload"],
                "disclosures": presentation["disclosures"],
            },
            "commerce_capabilities": {
                "escrow_capable": escrow_capable,
                "sla_capable": True,
                "supported_currencies": protocol_metadata.get("currencies", ["USD"]),
            },
            "service_endpoint": protocol_metadata.get(
                "endpoint", f"https://api.greenhelix.net/v1"
            ),
        }

    def verify_counterparty(self, presentation: dict) -> dict:
        if presentation.get("protocol") != "ucp":
            return {"valid": False, "reason": "不是 UCP 展示"}

        identity = presentation.get("identity", {})
        commerce = presentation.get("commerce_capabilities", {})

        # 验证身份并检查商业能力
        rep = api_call("get_agent_reputation", {
            "agent_id": identity.get("agent_id", ""),
        })

        return {
            "valid": True,
            "agent_id": identity.get("agent_id"),
            "escrow_capable": commerce.get("escrow_capable", False),
            "reputation": rep,
        }

ACP 协议适配器

class ACPAdapter(ProtocolAdapter):
    """OpenAI 代理商业协议(ACP)凭证适配器。

    ACP 使用作用域声明:凭证必须明确声明代理被授权执行的商业行为。
    所需声明不可选择性披露——ACP 强制其可见。
    """

    ACP_REQUIRED_CLAIMS = ["authorized_actions", "spending_limit", "intent_type"]

    def format_presentation(
        self,
        credential_id: str,
        disclosed_claims: List[str],
        protocol_metadata: Dict,
    ) -> dict:
        # ACP 要求某些声明始终披露
        all_disclosed = list(set(disclosed_claims + self.ACP_REQUIRED_CLAIMS))
        presentation = self.wallet.present_credential(credential_id, all_disclosed)

        return {
            "protocol": "acp",
            "version": "1.0",
            "agent": {
                "id": self.wallet.agent_id,
                "did": self.wallet.did,
            },
            "scope_assertion": {
                "format": "sd-jwt-vc",
                "credential": presentation["jwt_payload"],
                "disclosures": presentation["disclosures"],
                "disclosed_values": presentation["disclosed_values"],
            },
            "transaction_context": {
                "requested_action": protocol_metadata.get("action", ""),
                "amount": protocol_metadata.get("amount", ""),
                "currency": protocol_metadata.get("currency", "USD"),
            },
        }

    def verify_counterparty(self, presentation: dict) -> dict:
        if presentation.get("protocol") != "acp":
            return {"valid": False, "reason": "不是 ACP 展示"}

        scope = presentation.get("scope_assertion", {})
        disclosed = scope.get("disclosed_values", {})

        # 检查所有必需声明是否存在
        for claim in self.ACP_REQUIRED_CLAIMS:
            if claim not in disclosed:
                return {"valid": False, "reason": f"缺少必需声明: {claim}"}

        agent = presentation.get("agent", {})
        rep = api_call("get_agent_reputation", {
            "agent_id": agent.get("id", ""),
        })

        return {
            "valid": True,
            "agent_id": agent.get("id"),
            "authorized_actions": disclosed.get("authorized_actions"),
            "spending_limit": disclosed.get("spending_limit"),
            "reputation": rep,
        }

x402 协议适配器

class X402Adapter(ProtocolAdapter):
    """x402 支付协议凭证适配器。

    x402 是一种轻量级基于 HTTP 的支付协议。
    凭证以 HTTP 头部形式在 402 Payment Required 响应中呈现。
    此适配器用于格式化 x402 流程中的支付证明。
    """

    def format_presentation(
        self,
        credential_id: str,
        disclosed_claims: List[str],
        protocol_metadata: Dict,
    ) -> dict:
        # x402 使用最小披露:仅需支付证明
        presentation = self.wallet.present_credential(
            credential_id, ["spending_limit"]
        )

        return {
            "protocol": "x402",
            "version": "1.0",
            "payment_header": {
                "X-Agent-DID": self.wallet.did,
                "X-Payment-Credential": json.dumps(presentation["jwt_payload"]),
                "X-Payment-Amount": protocol_metadata.get("amount", ""),
                "X-Payment-Currency": protocol_metadata.get("currency", "USD"),
            },
            "attestation": {
                "credential_hash": self.wallet.credentials[
                    credential_id
                ].credential_hash(),
                "agent_id": self.wallet.agent_id,
            },
        }

    def verify_counterparty(self, presentation: dict) -> dict:
        if presentation.get("protocol") != "x402":
            return {"valid": False, "reason": "不是 x402 展示"}

        headers = presentation.get("payment_header", {})
        agent_did = headers.get("X-Agent-DID", "")

        # x402 的最小验证:检查代理是否存在
        # 完整验证在结算阶段进行
        return {
            "valid": bool(agent_did),
            "agent_did": agent_did,
            "amount": headers.get("X-Payment-Amount"),
        }

选择合适的协议

markdown

Agent 凭证钱包:可验证意图与委托链

版本:1.3.1

分块:11/16

在特定交互中选择哪个协议适配器,取决于你正在进行的操作。发现和初始联系通常通过 AP2 进行,因为 Google 的代理卡片机制提供了最丰富的服务描述格式。价格协商和 SLA 协议则通过 UCP 完成,因为它内置了托管和 SLA 原语。支付执行通过 ACP 或 Mastercard VI 轨道进行,因为这些协议具备最强的支付授权验证能力。微支付和按请求计费则通过 x402 实现,因为它对小额交易的开销最低——凭证仅是一个 HTTP 头。

实际上,一次商业交易通常会跨越三个或四个协议。你的代理通过 AP2 发现供应商,通过 UCP 协商条款,通过 ACP 执行主支付(使用可验证意图凭证),然后通过 x402 支付每 API 调用的超额费用。凭证钱包存储一组唯一的 SD-JWT-VC 凭证。各适配器将这些凭证格式化为对应协议所需的形式,无需重复。

多协议交易示例

# 初始化钱包并声明意图
wallet = CredentialWallet(
    agent_id="acme-buyer-01",
    display_name="Acme 多协议买家",
    owner="alice@acme.com",
)
wallet.register()
wallet.create_wallet()

# 发行委托凭证
vi = VerifiableIntentManager(wallet)
intent_cred = vi.declare_intent(
    intent_id="multi-proto-session-001",
    authorized_actions=["purchase_compute"],
    spending_limit_usd=5000.00,
    merchant_categories=["cloud_compute"],
    session_hours=4.0,
)

# 通过 AP2 发现供应商
ap2 = AP2Adapter(wallet)
ap2_presentation = ap2.format_presentation(
    credential_id="multi-proto-session-001",
    disclosed_claims=["authorized_actions", "spending_limit"],
    protocol_metadata={"capabilities": ["compute_provisioning"]},
)
print(f"AP2 握手: {ap2_presentation['agent_card']['agent_id']}")

# 通过 UCP 协商条款
ucp = UCPAdapter(wallet)
ucp_presentation = ucp.format_presentation(
    credential_id="multi-proto-session-001",
    disclosed_claims=["authorized_actions", "spending_limit"],
    protocol_metadata={
        "tools": ["create_escrow", "create_sla"],
        "currencies": ["USD"],
    },
)
print(f"UCP 协商: 托管功能={ucp_presentation['commerce_capabilities']['escrow_capable']}")

# 通过 ACP 执行支付
acp = ACPAdapter(wallet)
acp_presentation = acp.format_presentation(
    credential_id="multi-proto-session-001",
    disclosed_claims=["merchant_categories"],  # ACP 会自动添加必要声明
    protocol_metadata={
        "action": "purchase_compute",
        "amount": "1500.00",
        "currency": "USD",
    },
)
print(f"ACP 范围: {acp_presentation['scope_assertion']['disclosed_values']}")

# 通过 x402 结算微支付
x402 = X402Adapter(wallet)
x402_presentation = x402.format_presentation(
    credential_id="multi-proto-session-001",
    disclosed_claims=["spending_limit"],
    protocol_metadata={"amount": "0.50", "currency": "USD"},
)
print(f"x402 头信息: {list(x402_presentation['payment_header'].keys())}")

第六章:eIDAS 2.0 合规性

2026 年 12 月截止日期

欧盟 eIDAS 2.0 法规要求所有欧盟成员国必须在 2026 年 12 月前向公民和企业提供欧洲数字身份(EUDI)钱包。对于代理商业务而言,这意味着:任何与欧盟消费者或企业进行交易的代理,都必须能够接受并验证 EUDI 钱包凭证;任何代表欧盟实体运营的代理,都必须能够出示符合 EUDI 架构参考框架(ARF)的凭证。

对代理开发者的关键要求包括:

  • 合格电子属性证明(QEAA):由合格信任服务提供商签发的凭证。涉及欧盟金融交易的代理委托凭证必须是 QEAA,或在委托链中引用一个 QEAA。
  • PSD2 强客户认证(SCA):超过 EUR 30 的支付需多因素认证。在代理商业场景中,若人类主体在签发意图凭证时已通过两种方式认证,则可通过委托链满足 SCA 要求。
  • 数据最小化:根据 GDPR,凭证只能披露交易所需的最少数据。SD-JWT 的选择性披露机制可直接满足此要求。
  • 凭证格式:ARF 明确将 SD-JWT-VC 列为可接受的凭证格式之一。该格式与 Mastercard VI 和 GreenHelix 凭证兼容,因此已有良好适配基础。

EUDI 钱包集成架构

eIDAS 2.0 代理商业凭证流程

graph LR
    A[欧盟自然人主体] -->|认证请求| B[合格信任服务提供商]
    B -->|颁发凭证| C[EUDI 钱包(移动应用)]
    C -->|SCA 验证的意图声明 + 委托凭证发行| D[代理钱包(GreenHelix)]
    D -->|向欧盟供应商出示 EUDI 引用凭证| E[欧盟供应商代理]

EUDIComplianceManager

python

class EUDIComplianceManager:

"""管理代理凭证的 eIDAS 2.0 EUDI 钱包合规性。

处理 QEAA 验证、PSD2 SCA 证明以及欧盟商业场景下的凭证格式化。

"""

# eIDAS 受信任服务列表(简化版)

QUALIFIED_TRUST_SERVICES = [

"did:web:qtsp.eu.example.com",

"did:web:trust.eidas.europa.eu",

]

SCA_THRESHOLD_EUR = 30.0

def __init__(self, wallet: CredentialWallet):

self.wallet = wallet

self.eudi_credentials: Dict[str, dict] = {}

self.compliance_log: List[dict] = []

def import_eudi_credential(

self,

eudi_credential_id: str,

issuer_did: str,

credential_data: dict,

sca_method: str,

sca_timestamp: float,

) -> dict:

"""导入来自 EUDI 钱包的凭证。

凭证必须由合格信任服务提供方(QEAA)颁发,才能用于受监管的欧盟交易。

"""

is_qualified = issuer_did in self.QUALIFIED_TRUST_SERVICES

eudi_record = {

"id": eudi_credential_id,

"issuer": issuer_did,

"is_qeaa": is_qualified,

"credential_data": credential_data,

"sca_method": sca_method,

"sca_timestamp": sca_timestamp,

"imported_at": time.time(),

}

self.eudi_credentials[eudi_credential_id] = eudi_record

# 同时签发一个引用 EUDI 来源的 GreenHelix 凭证

self.wallet.issue_credential(

credential_id=f"eudi-{eudi_credential_id}",

subject_did=self.wallet.did,

credential_type="https://greenhelix.net/credentials/eudi-delegation/v1",

claims={

"eudi_source": eudi_credential_id,

"eudi_issuer": issuer_did,

"is_qeaa": is_qualified,

"sca_method": sca_method,

"sca_timestamp": sca_timestamp,

**credential_data,

},

disclosable_claims=["sca_method", "eudi_issuer"],

ttl_seconds=86400,

)

return eudi_record

def check_sca_required(self, amount_eur: float) -> bool:

"""检查交易金额是否需要 PSD2 SCA。"""

return amount_eur > self.SCA_THRESHOLD_EUR

def validate_sca_for_transaction(

self,

eudi_credential_id: str,

amount_eur: float,

max_sca_age_seconds: int = 300,

) -> dict:

"""验证交易是否满足 SCA 要求。

PSD2 规定超过 EUR 30 的支付需进行 SCA。SCA 必须在指定时间内完成(max_sca_age_seconds 内),否则交易无法授权。

"""

if not self.check_sca_required(amount_eur):

return {"sca_required": False, "authorized": True}

cred = self.eudi_credentials.get(eudi_credential_id)

if not cred:

return {

"sca_required": True,

"authorized": False,

"reason": "EUDI 凭证未找到",

}

sca_age = time.time() - cred["sca_timestamp"]

if sca_age > max_sca_age_seconds:

return {

"sca_required": True,

"authorized": False,

"reason": f"SCA 已过期 ({sca_age:.0f}s > {max_sca_age_seconds}s)",

}

return {

"sca_required": True,

"authorized": True,

"sca_method": cred["sca_method"],

"sca_age_seconds": sca_age,

}

def create_compliance_attestation(

self,

transaction_id: str,

amount_eur: float,

eudi_credential_id: str,

counterparty_agent_id: str,

) -> dict:

"""为欧盟交易创建合规证明。

记录所有合规性检查结果,用于审计目的。该证明可提交给监管机构作为 eIDAS 2.0 合规证据。

"""

sca_check = self.validate_sca_for_transaction(eudi_credential_id, amount_eur)

cred = self.eudi_credentials.get(eudi_credential_id, {})

attestation = {

"transaction_id": transaction_id,

"timestamp": time.time(),

"agent_id": self.wallet.agent_id,

"counterparty": counterparty_agent_id,

"amount_eur": amount_eur,

"eudi_credential": eudi_credential_id,

"is_qeaa": cred.get("is_qeaa", False),

"sca_check": sca_check,

"data_minimization": True, # 使用 SD-JWT 选择性披露

"credential_format": "sd-jwt-vc",

"regulation": "eIDAS 2.0 / PSD2",

}

# 通过 GreenHelix 合规工具记录日志

compliance_result = api_call("check_compliance", {

"agent_id": self.wallet.agent_id,

"transaction_id": transaction_id,

"compliance_data": attestation,

})

attestation["platform_check"] = compliance_result

self.compliance_log.append(attestation)

return attestation

欧盟交易流程

markdown

使用 EUDI 集成设置钱包

wallet = CredentialWallet(
    agent_id="eu-buyer-agent-01",
    display_name="欧盟采购代理",
    owner="klaus@eurocorp.eu",
)
wallet.register()
wallet.create_wallet()

eudi = EUDIComplianceManager(wallet)

从用户的 EUDI 钱包导入凭证

(在生产环境中,该凭证通过用户手机 EUDI 钱包应用的二维码扫描或 NFC 触碰获取)

eudi_cred = eudi.import_eudi_credential(
    eudi_credential_id="eudi-2026-04-06-001",
    issuer_did="did:web:qtsp.eu.example.com",  # 合格的 TSP
    credential_data={
        "principal_name": "Klaus Mueller",
        "organization": "EuroCorp GmbH",
        "authorized_actions": ["purchase_compute", "purchase_saas"],
        "spending_limit": {"amount": "8000", "currency": "EUR", "period": "day"},
    },
    sca_method="biometric+pin",
    sca_timestamp=time.time(),  # 已完成 SCA 验证
)
print(f"EUDI 凭证已导入。QEAA: {eudi_cred['is_qeaa']}")
# 输出: EUDI 凭证已导入。QEAA: True

执行需要 PSD2 SCA 的交易

attestation = eudi.create_compliance_attestation(
    transaction_id="eu-tx-2026-04-06-001",
    amount_eur=2500.00,
    eudi_credential_id="eudi-2026-04-06-001",
    counterparty_agent_id="eu-vendor-saas-01",
)
print(f"合规性检查: SCA 必须执行={attestation['sca_check']['sca_required']}, "
      f"授权通过={attestation['sca_check']['authorized']}")
# 输出: 合规性检查: SCA 必须执行=True, 授权通过=True

第七章:信任评分、声誉绑定与凭证撤销

为什么凭证需要声誉机制

一个凭证仅说明某个代理被授权执行哪些操作,但无法反映其实际执行能力如何。一个拥有有效 50,000 美元委托权限的代理,可能任务完成率仅为 30%,且存在争议性资金托管记录。尽管凭证在技术上是有效的(人类已授权支出),但对方仍应核查该代理的历史表现后再决定是否接受。声誉绑定将可验证的绩效数据附加到凭证上,使交易方能够在一次验证流程中同时评估授权资格与执行能力。

ReputationBoundCredentialManager

markdown

Reputation-Bound Credential Manager

绑定可验证声誉数据到代理凭证的管理器。

结合 GreenHelix 声誉工具与凭证钱包,创建同时包含授权和表现证明的凭证。

类定义

class ReputationBoundCredentialManager:
    """Binds verifiable reputation data to agent credentials.

    Combines GreenHelix reputation tools with the credential wallet to
    create credentials that carry both authorization and performance proof.
    """

    def __init__(self, wallet: CredentialWallet):
        self.wallet = wallet
        self.revocation_registry: Dict[str, dict] = {}

初始化

  • wallet: 凭证钱包实例,用于管理凭证的发行、撤销和验证。
  • revocation_registry: 存储已撤销凭证的记录,用于追踪撤销历史。

方法说明

获取声誉快照

def get_reputation_snapshot(self) -> dict:
    """Fetch the agent's current reputation from GreenHelix."""
    return api_call("get_agent_reputation", {
        "agent_id": self.wallet.agent_id,
    })

从 GreenHelix 服务获取当前代理的声誉数据,包括声誉分数、交易次数、声明链深度等。


提交绩效指标

def submit_performance_metrics(
    self,
    metrics: Dict[str, Any],
) -> dict:
    """Submit performance metrics to build verifiable history.

    These metrics feed into the reputation score and can be
    anchored in claim chains for tamper-evidence.
    """
    return api_call("submit_metrics", {
        "agent_id": self.wallet.agent_id,
        "metrics": metrics,
    })

提交绩效指标以构建可验证的历史记录。这些数据将影响声誉评分,并可锚定在声明链中,实现防篡改证据。


发行声誉绑定凭证

def issue_reputation_bound_credential(
    self,
    credential_id: str,
    subject_did: str,
    authorization_claims: Dict[str, Any],
    min_reputation_score: float = 0.0,
) -> AgentCredential:
    """Issue a credential that includes a verifiable reputation snapshot.

    The reputation data becomes part of the credential claims,
    anchored at issuance time. The counterparty can verify that
    the reputation was genuine at issuance by checking the claim chain.

    Args:
        credential_id: Unique ID for this credential.
        subject_did: DID of the credential subject.
        authorization_claims: The authorization claims (actions, limits, etc).
        min_reputation_score: Minimum score required to issue. Fails if below.
    """
    # Fetch current reputation
    rep = self.get_reputation_snapshot()
    rep_score = rep.get("reputation_score", 0)

    if rep_score < min_reputation_score:
        raise ValueError(
            f"Reputation {rep_score} below minimum {min_reputation_score}"
        )

    # Merge reputation into claims
    all_claims = {
        **authorization_claims,
        "reputation_at_issuance": {
            "score": rep_score,
            "trade_count": rep.get("trade_count", 0),
            "claim_chain_depth": rep.get("claim_chain_depth", 0),
            "snapshot_time": time.time(),
        },
    }

    return self.wallet.issue_credential(
        credential_id=credential_id,
        subject_did=subject_did,
        credential_type=(
            "https://greenhelix.net/credentials/reputation-bound-delegation/v1"
        ),
        claims=all_claims,
        disclosable_claims=[
            "reputation_at_issuance",
            "principal_name",
        ],
        ttl_seconds=86400,
    )

发行一个包含可验证声誉快照的凭证。

  • 在凭证签发时,将当前声誉数据嵌入声明中。
  • 对方可通过检查声明链验证该声誉在签发时的真实性。
  • 若声誉分数低于指定最低值,则拒绝发行。

参数说明:

参数类型描述
credential_idstr凭证唯一标识符
subject_didstr凭证主体的 DID
authorization_claimsdict授权声明(如操作权限、限额等)
min_reputation_scorefloat发行所需的最低声誉分数,默认为 0.0

撤销凭证

def revoke_credential(
    self,
    credential_id: str,
    reason: str,
) -> dict:
    """Revoke a credential and record the revocation.

    Revocation is immediate. The credential hash is added to the
    revocation registry, and a claim chain entry is created for
    tamper-evident revocation history.
    """
    if credential_id not in self.wallet.credentials:
        raise KeyError(f"Credential {credential_id} not found")

    cred = self.wallet.credentials[credential_id]

    revocation_entry = {
        "credential_id": credential_id,
        "credential_hash": cred.credential_hash(),
        "revoked_at": time.time(),
        "reason": reason,
        "revoked_by": self.wallet.agent_id,
    }
    self.revocation_registry[credential_id] = revocation_entry

    # Submit revocation as a metric for chain anchoring
    self.submit_performance_metrics({
        "event": "credential_revocation",
        "credential_id": credential_id,
        "reason": reason,
        "timestamp": time.time(),
    })

    # Anchor the revocation in a claim chain
    chain_result = self.wallet.build_chain()

    return {
        "revoked": True,
        "entry": revocation_entry,
        "chain_result": chain_result,
    }

立即撤销指定凭证,并记录撤销信息。

  • 将凭证哈希加入撤销注册表。
  • 生成一条声明链条目,确保撤销历史具有防篡改性。
  • 将撤销事件作为绩效指标提交,用于链上锚定。

返回值:

  • revoked: 是否成功撤销
  • entry: 撤销记录详情
  • chain_result: 声明链构建结果

检查凭证是否被撤销

def check_revocation(self, credential_id: str) -> dict:
    """Check if a credential has been revoked."""
    if credential_id in self.revocation_registry:
        entry = self.revocation_registry[credential_id]
        return {
            "revoked": True,
            "revoked_at": entry["revoked_at"],
            "reason": entry["reason"],
        }
    return {"revoked": False}

检查指定凭证是否已被撤销。

  • 若存在于撤销注册表中,返回撤销时间与原因。
  • 否则返回未被撤销。

创建争议证据凭证

def create_dispute_evidence_credential(
    self,
    dispute_id: str,
    counterparty_agent_id: str,
    evidence: Dict[str, Any],
) -> dict:
    """Create a credential containing dispute evidence.

    When a transaction is disputed, this creates a tamper-evident
    record of the evidence that can be presented during resolution.
    """
    # Create the dispute via GreenHelix
    dispute_result = api_call("create_dispute", {
        "agent_id": self.wallet.agent_id,
        "counterparty_agent_id": counterparty_agent_id,
        "dispute_id": dispute_id,
        "evidence": evidence,
    })

    # Issue an evidence credential
    evidence_cred = self.wallet.issue_credential(
        credential_id=f"dispute-evidence-{dispute_id}",
        subject_did=self.wallet.did,
        credential_type=(
            "https://greenhelix.net/credentials/dispute-evidence/v1"
        ),
        claims={
            "dispute_id": dispute_id,
            "counterparty": counterparty_agent_id,
            "evidence_summary": evidence.get("summary", ""),
            "evidence_hash": hashlib.sha256(
                json.dumps(evidence, sort_keys=True).encode()
            ).hexdigest(),
            "created_at": time.time(),
        },
        disclosable_claims=["evidence_summary"],
        ttl_seconds=2592000,  # 30 days for dispute resolution
    )

    return {
        "dispute_result": dispute_result,
        "evidence_credential": evidence_cred.credential_hash(),
    }

在交易发生争议时,创建一个包含争议证据的凭证。

  • 通过 GreenHelix 服务创建争议记录。
  • 发行一个带有证据摘要、哈希和创建时间的凭证。
  • 仅披露证据摘要,保护敏感信息。
  • 凭证有效期为 30 天(2592000 秒),适用于争议解决周期。

返回值:

  • dispute_result: 争议创建结果
  • evidence_credential: 证据凭证的哈希值,可用于后续验证

声誉绑定凭证流程

  1. 代理发起凭证请求。
  2. 系统调用 get_reputation_snapshot 获取当前声誉数据。
  3. 若声誉分数低于阈值,拒绝发行。
  4. 将声誉快照合并至授权声明中,形成完整凭证。
  5. 使用 issue_credential 发行含声誉信息的凭证。
  6. 凭证签发后,其声誉状态即被锚定在声明链中,不可更改。
  7. 如需撤销,调用 revoke_credential 并记录撤销事件。
  8. 撤销信息同样锚定在链上,形成可追溯的审计轨迹。
  9. 若发生争议,使用 create_dispute_evidence_credential 创建可验证的证据凭证。
  10. 争议解决过程中,可出示该凭证作为可信证据。

markdown

Agent 凭证钱包:可验证意图与委托链

版本:1.3.1

分块:16/16

wallet = CredentialWallet(
    agent_id="reputable-vendor-01",
    display_name="可信云服务商",
    owner="ops@cloudvendor.com",
)
wallet.register()
wallet.create_wallet()

rep_manager = ReputationBoundCredentialManager(wallet)

# 定期提交性能指标(周期性调用)
rep_manager.submit_performance_metrics({
    "task_completion_rate": 0.97,
    "avg_response_time_ms": 145,
    "successful_escrows": 342,
    "disputed_escrows": 3,
    "uptime_percent": 99.8,
})

# 发行一个与声誉绑定的凭证(例如,供应商向买家展示服务时)
rep_cred = rep_manager.issue_reputation_bound_credential(
    credential_id="vendor-service-cred-001",
    subject_did="did:key:reputable-vendor-01",
    authorization_claims={
        "service_type": "gpu_compute_provisioning",
        "max_instance_count": 64,
        "supported_regions": ["us-east", "eu-west"],
        "principal_name": "CloudVendor Inc.",
    },
    min_reputation_score=0.7,  # 要求最低 70% 的声誉分数
)

# 选择性披露展示 —— 只显示声誉信息,不暴露主体名称
presentation = wallet.present_credential(
    credential_id="vendor-service-cred-001",
    disclosed_claims=["reputation_at_issuance"],
)
print(f"披露的声誉值:{presentation['disclosed_values']}")

# 后续操作:撤销凭证(例如,服务已下线)
revocation = rep_manager.revoke_credential(
    credential_id="vendor-service-cred-001",
    reason="us-east 区域服务已停用",
)
print(f"已撤销:{revocation['revoked']}")

# 对方在接收凭证前检查撤销状态
status = rep_manager.check_revocation("vendor-service-cred-001")
print(f"撤销状态检查结果:{status}")
# 输出示例:Revocation check: {'revoked': True, 'revoked_at': ..., 'reason': '...'}

用凭证生成争议证据

# 当交易出现问题时,创建防篡改的争议证据
evidence_result = rep_manager.create_dispute_evidence_credential(
    dispute_id="dispute-2026-04-06-001",
    counterparty_agent_id="unreliable-vendor-99",
    evidence={
        "summary": "供应商承诺提供 8 个 A100 实例,但仅交付 4 个",
        "sla_id": "sla-2026-04-05-001",
        "promised_instances": 8,
        "delivered_instances": 4,
        "transaction_id": "tx-2026-04-05-789",
        "screenshots": ["evidence-001.png", "evidence-002.png"],
    },
)
print(f"已提交争议。证据凭证:{evidence_result['evidence_credential'][:16]}...")

下一步行动

关于部署模式、监控策略和生产环境加固,请参阅

[Agent 生产环境加固指南](https://clawhub.ai/skills/greenhelix-agent-production-hardening)。


你将获得的内容

本指南完整覆盖了代理商业中的凭证全生命周期:

第 1 章 解释了为何 API 密钥和 OAuth 在委托场景下失效,以及 Mastercard、Google 和 OpenAI 如何共同采用 W3C 可验证凭证(Verifiable Credentials)。

第 2 章 提供了 SD-JWT-VC 基础知识:凭证结构、选择性披露机制、密钥绑定,以及通过分层签发实现的委托链。

第 3 章 使用 GreenHelix 工具构建了 CredentialWallet 类:包括 register_agentcreate_walletbuild_claim_chainget_claim_chains,实现基于 DID 的凭证存储。

第 4 章 实现了可验证意图:会话级支出限额、create_intent 集成,以及通过约束缩小实现的子委托。

第 5 章 提供了跨协议适配器,支持 AP2、UCP、ACP 和 x402 协议,统一使用钱包后端,并按协议格式化呈现。

第 6 章 应对 2026 年 12 月 eIDAS 2.0 法规要求:集成 EUDI Wallet、QEAA 验证、PSD2 SCA 流程,以及通过 check_compliance 提交合规证明。

第 7 章 将声誉绑定到凭证:使用 get_agent_reputationsubmit_metrics 获取声誉快照,支持实时撤销,以及通过 create_dispute 创建争议证据凭证。

第 8 章 涵盖大规模部署:批量注册、模板化签发、零停机密钥轮换、健康监控,以及为期 90 天的实施计划。

所有代码示例均基于 requests.Session 与 REST API(POST /v1/{tool})模式对接 GreenHelix A2A 商业网关。每个凭证均为带有选择性披露功能的 SD-JWT-VC。每条委托链均强制执行约束缩小。整体架构在钱包层保持协议无关,在呈现层针对具体协议定制,使你的代理可在 AP2、UCP、ACP 和 x402 之间无缝交易,无需重复签发凭证。

2026 年 12 月的合规截止日期真实存在。各协议正在趋同。建议从第 3 章开始,注册首个代理,并逐步构建系统。

M
@mirni

已收录 1 个 Skill

相关推荐