快速开始¶
本指南带你签发第一个 LedgerFlow 授权令,并使用授权验证 x402 支付。
前置条件¶
第 1 步:安装¶
第 2 步:生成密钥¶
生成发行者密钥对和代理密钥对:
# 生成发行者密钥(Ed25519)
cargo run -p ledgerflow-cli -- gen-key --label issuer
# 生成代理密钥(Ed25519)
cargo run -p ledgerflow-cli -- gen-key --label agent
第 3 步:签发授权令¶
创建授权令授权代理进行支付:
cargo run -p ledgerflow-cli -- issue-warrant \
--issuer-keys issuer.key \
--agent-keys agent.key \
--merchant "api.example.com" \
--max-amount 10.00 \
--asset USDC \
--ttl 3600 \
--tools "web_search,code_execution"
这创建一个授权令:
- 由发行者签名
- 授权由
agent.key标识的代理 - 限制到商户
api.example.com - 每次请求限制支出 $10 USDC
- 1 小时后过期
- 限制到
web_search和code_execution工具
第 4 步:构建 x402 支付¶
当代理收到 x402 402 Payment Required 响应时:
cargo run -p ledgerflow-cli -- build-payment \
--warrant warrant.cbor \
--agent-keys agent.key \
--challenge-id "01HV7W8M7BX3Q6P0WJ7T5QK1V2" \
--accepted-hash "sha256:abc123..." \
--request-hash "sha256:def456..."
这生成带有 LedgerFlow 扩展的 x402 支付负载。
第 5 步:验证(商户端)¶
商户中间件验证授权:
验证检查:
- 授权令签名有效性
- 证明签名有效性
- 授权令时间有效性
- 受众范围
- 所有约束
- 证明绑定
- 重放保护
编程使用¶
签发授权令¶
use ledgerflow_core::{Warrant, SignerRef, Constraint};
let warrant = Warrant::builder()
.issuer(issuer_signer)
.subject_signer(agent_signer)
.payment_subjects(vec![payment_subject])
.audience(AudienceScope::MerchantIds(vec!["api.example.com".into()]))
.not_before(now_ms)
.expires_at(now_ms + 3600_000)
.delegation(DelegationPolicy { can_delegate: true, max_depth: 2 })
.constraints(vec![
Constraint::Merchant(MerchantConstraint {
host_suffixes: vec![".example.com".into()],
..Default::default()
}),
Constraint::Payment(PaymentConstraint {
max_per_request: AmountLimit { amount: "10000000".into(), asset: "USDC".into() },
..Default::default()
}),
])
.sign(&issuer_key)?;
验证授权¶
use ledgerflow_x402::{verify_authorization, VerifierContext};
let ctx = VerifierContext::new()
.with_challenge_id(challenge_id)
.with_request(request)
.with_accepted(accepted);
let result = verify_authorization(&extension, &ctx)?;
match result {
AuthzResult::Authorized { warrant_id, .. } => {
// 继续 x402 结算
}
AuthzResult::Denied { reason, .. } => {
// 拒绝支付
}
}
集成模式¶
模式 1:网关中间件¶
将 LedgerFlow 验证放在 x402 中间件层:
模式 2:Sidecar¶
将 LedgerFlow 验证作为 sidecar 服务运行:
模式 3:MCP 代理¶
对于 Model Context Protocol 集成,在 MCP 代理层验证:
测试¶
运行验收场景: