feat(chain): 阶段 2 链上层形状层,新增主门禁第 14 条
- 新增 crates/mpc-chain:链上对象规范编码、SM3 摘要、FISCO BCOS 3.x eth_* JSON-RPC 客户端、幂等 outbox、成员准入、Signer 形状层 - 新增 mpc chain digest|submit|flush|status|admit 命令族 - 新增 tools/selftest-chain.py 桩自测(44 判据),主门禁 13 → 14 条 - 同步 catalog 守卫、domain 域分隔、CLAUDE.md、INTEGRATION_ANALYSIS.md 边界:ModuleSigner / RLP / 国密模组 provider 未落地;flush 发的是规范字节而非已签名交易,未配置签名器即拒绝,本期不宣称能上链。
This commit is contained in:
1 parent
362db1d7a8
commit
b15f0268bf
17 files changed
+2810
-30
No files matched your search
@@ -86,10 +86,18 @@ mpc-tee TEE HAL:seal / unseal / attest / sign
|
||||
★ 零 crates.io 依赖:要被拷进 OP-TEE SDK 做 armv7 离线交叉编译
|
||||
───────────
|
||||
mpc-hostd 宿主控制面(两层控制面的宿主层):e2b 兼容 API + TeeRuntime + /attestation
|
||||
★ 唯一带第三方依赖的 crate:axum / tokio / reqwest(见「依赖」)
|
||||
★ 带第三方依赖的两个 crate 之一:axum / tokio / reqwest(见「依赖」)
|
||||
模块:api / server / client / protocol / runtime / json / link(EasyTier 进程层)
|
||||
★ link 只 spawn 外部二进制,绝不链接 easytier-* crate(LGPL,见「依赖」)
|
||||
───────────
|
||||
mpc-chain 链上层(阶段 2 **形状层**):对象规范编码 / SM3 摘要 / JSON-RPC / 幂等 outbox / 准入
|
||||
模块:objects / rpc / outbox / admission / signer
|
||||
★ 存证 fail-open(outbox 等补链),成员准入 fail-closed(缓存过期即拒),**两侧不许混**
|
||||
★ 3.x RPC 是 eth_ 兼容端点(EthMethods.h);HTTP 200 + error 字段 = 失败
|
||||
★ ModuleSigner / RLP / 国密模组 provider **未落地**:flush 发的是规范字节,
|
||||
不是已签名交易;未配置签名器即拒绝。本期不宣称能上链。
|
||||
serde_json + reqwest 只落在本 crate(见「依赖」)
|
||||
───────────
|
||||
mpc-proto 帧协议:12 字节头 + 定长消息体,手写编解码(不引 protobuf/serde)
|
||||
```
|
||||
|
||||
@@ -184,14 +192,19 @@ xop --secret CUBE_API_KEY=llm_key -- python3 -u build/run_qemu.py < /dev/null
|
||||
`mpc-psi` 的 `curve25519-dalek` 是唯一允许的外部密码学 crate(X25519 必须恒定时间实现,
|
||||
手写会被时序侧信道攻击)。
|
||||
|
||||
**唯一例外是 `mpc-hostd`**(2026-11-07):宿主控制面用 `axum` + `tokio` + `reqwest`
|
||||
接管 HTTP/1.1,约 100 个传递依赖,**只许待在这个独立 crate 里**。
|
||||
**两个例外是 `mpc-hostd` 与 `mpc-chain`**(2026-11-07):宿主控制面用
|
||||
`axum` + `tokio` + `reqwest` 接管 HTTP/1.1(约 100 个传递依赖);链上层用
|
||||
`serde_json` + `reqwest` 做 JSON-RPC。**都只许待在各自的独立 crate 里**。
|
||||
`mpc-chain` 本期**零 FFI**:国密模组 / Tongsuo / SM2 交易签名尚未落地,
|
||||
不引 `openssl` —— 模组到位后若加 FFI,也只加在这一层。
|
||||
|
||||
- 硬理由:`build/build_optee.sh` 会把整个 `crates/mpc-tee` 拷进 OP-TEE SDK 的
|
||||
workspace 做 armv7 **离线**交叉编译。哪怕把依赖标成 optional,Cargo 解析阶段
|
||||
仍要能拿到 crate,没网就挂。所以 `mpc-tee` 连 `build.rs` 都不留。
|
||||
- 自查:`cargo tree -p mpc-tee --no-default-features` 应只剩 `mpc-core`。
|
||||
- 禁止把 HTTP/异步运行时依赖扩散到 `mpc-core` / `mpc-tee` / TA 侧。
|
||||
- 禁止把 HTTP/异步运行时/JSON 依赖扩散到 `mpc-core` / `mpc-tee` / TA 侧。
|
||||
- `mpc-chain` 的 `.no_proxy()` 不许删:控制面只连配置里的 `host:port`,
|
||||
系统代理会把这一跳端点换掉(也让国密 TLS 的实测结论失效),门禁第 14 条有回归探针。
|
||||
|
||||
**链路层不引任何 EasyTier crate**:`mpc_hostd::link` 只 `Command::spawn` 外部二进制
|
||||
(独立程序 + CLI/RPC 是 LGPL 明确许可的用法),`mpc_tee::link` 是 no_std 协议层。
|
||||
|
||||
Generated
+10
@@ -469,10 +469,20 @@ dependencies = [
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mpc-chain"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"mpc-core",
|
||||
"reqwest",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mpc-cli"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"mpc-chain",
|
||||
"mpc-core",
|
||||
"mpc-data",
|
||||
"mpc-fl",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "mpc-chain"
|
||||
description = "链上层:链上对象规范编码、JSON-RPC 最小面、幂等 outbox 与 fail-closed 准入"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
mpc-core = { workspace = true, features = ["std"] }
|
||||
|
||||
# 协议层用成熟组件:JSON 编解码与 HTTP 都不自己写。
|
||||
# ★ 与 mpc-hostd 同理,第三方依赖只落在本 crate —— mpc-core(no_std)
|
||||
# 与 mpc-tee(要被拷进 OP-TEE SDK 离线交叉编译)必须保持零 crates.io 依赖。
|
||||
serde_json = "1"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["blocking"] }
|
||||
@@ -0,0 +1,181 @@
|
||||
//! 链读侧准入:**fail-closed**,与 `outbox` 的 fail-open 严格相反。
|
||||
//!
|
||||
//! 成员资格 / 硬规则判错了是安全事故,所以链抖动、缓存缺失、缓存过期
|
||||
//! 一律**拒绝**,绝不「读不到就先放过」。缓存带 `expires_at`,过期即拒
|
||||
//! (与 `site_admit::MemberRoster` 同一口径)。时间由调用方传入,
|
||||
//! 框架不读系统时钟 —— 多站点端要能对账。
|
||||
|
||||
use crate::ChainError;
|
||||
|
||||
/// 从链上读回并缓存的准入依据。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MemberCache {
|
||||
pub members: Vec<String>,
|
||||
/// 硬规则查询结果(链上合约判定)。`false` / 未查到都拒绝。
|
||||
pub hard_rules_ok: bool,
|
||||
/// 缓存到期时刻(Unix 秒),到期即拒,不续用。
|
||||
pub expires_at: u64,
|
||||
}
|
||||
|
||||
impl MemberCache {
|
||||
/// 从缓存文件解析。**缺失字段一律 fail-closed**:`hard_rules_ok`
|
||||
/// 缺失当 `false`,`expires_at` 缺失直接拒绝(不能"没写就当不过期")。
|
||||
pub fn from_json(text: &str) -> Result<Self, ChainError> {
|
||||
let v: serde_json::Value = serde_json::from_str(text)
|
||||
.map_err(|e| ChainError::BadInput(format!("成员表缓存不是合法 JSON: {e}")))?;
|
||||
let m = v
|
||||
.as_object()
|
||||
.ok_or_else(|| ChainError::BadInput(String::from("成员表缓存必须是对象")))?;
|
||||
let members = m
|
||||
.get("members")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.ok_or_else(|| {
|
||||
ChainError::AdmissionDenied(String::from("成员表缓存缺少 members,fail-closed 拒绝"))
|
||||
})?
|
||||
.iter()
|
||||
.map(|x| {
|
||||
x.as_str().map(String::from).ok_or_else(|| {
|
||||
ChainError::BadInput(String::from("members 元素必须是字符串"))
|
||||
})
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let expires_at = m
|
||||
.get("expires_at")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.ok_or_else(|| {
|
||||
ChainError::AdmissionDenied(String::from(
|
||||
"成员表缓存缺少 expires_at,不能当成永不过期,fail-closed 拒绝",
|
||||
))
|
||||
})?;
|
||||
Ok(Self {
|
||||
members,
|
||||
hard_rules_ok: m
|
||||
.get("hard_rules_ok")
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(false),
|
||||
expires_at,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 链读侧准入。返回 `Ok(())` 才允许继续;任何不确定都返回带原因的拒绝。
|
||||
pub fn chain_admit(
|
||||
cache: Option<&MemberCache>,
|
||||
now: u64,
|
||||
site: &str,
|
||||
participants: &[String],
|
||||
) -> Result<(), ChainError> {
|
||||
let c = cache.ok_or_else(|| {
|
||||
ChainError::AdmissionDenied(String::from(
|
||||
"成员表缓存缺失(链读失败或未初始化),fail-closed 拒绝",
|
||||
))
|
||||
})?;
|
||||
if now >= c.expires_at {
|
||||
return Err(ChainError::AdmissionDenied(format!(
|
||||
"成员表缓存已过期(now={now} expires_at={}),fail-closed 拒绝",
|
||||
c.expires_at
|
||||
)));
|
||||
}
|
||||
if !c.hard_rules_ok {
|
||||
return Err(ChainError::AdmissionDenied(String::from(
|
||||
"链上硬规则判定未通过,fail-closed 拒绝",
|
||||
)));
|
||||
}
|
||||
if site.is_empty() || !c.members.iter().any(|m| m == site) {
|
||||
return Err(ChainError::AdmissionDenied(format!(
|
||||
"本方 {site:?} 不在联盟成员表中,fail-closed 拒绝"
|
||||
)));
|
||||
}
|
||||
if participants.len() < 2 {
|
||||
return Err(ChainError::AdmissionDenied(String::from(
|
||||
"参与方少于两方,拒绝",
|
||||
)));
|
||||
}
|
||||
let mut seen: Vec<&str> = Vec::new();
|
||||
for p in participants {
|
||||
if seen.contains(&p.as_str()) {
|
||||
return Err(ChainError::AdmissionDenied(format!(
|
||||
"参与方重复: {p:?}"
|
||||
)));
|
||||
}
|
||||
seen.push(p.as_str());
|
||||
if !c.members.iter().any(|m| m == p) {
|
||||
return Err(ChainError::AdmissionDenied(format!(
|
||||
"参与方 {p:?} 不是联盟成员,fail-closed 拒绝"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn cache() -> MemberCache {
|
||||
MemberCache {
|
||||
members: vec![String::from("alice"), String::from("bob")],
|
||||
hard_rules_ok: true,
|
||||
expires_at: 2000,
|
||||
}
|
||||
}
|
||||
fn parties() -> Vec<String> {
|
||||
vec![String::from("alice"), String::from("bob")]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admits_when_cache_is_fresh_and_all_parties_are_members() {
|
||||
assert!(chain_admit(Some(&cache()), 1000, "alice", &parties()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_cache_is_denied_not_skipped() {
|
||||
match chain_admit(None, 1000, "alice", &parties()) {
|
||||
Err(ChainError::AdmissionDenied(m)) => assert!(m.contains("缓存缺失")),
|
||||
other => panic!("缓存缺失必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_cache_is_denied_even_at_exact_boundary() {
|
||||
for now in [2000, 2001] {
|
||||
match chain_admit(Some(&cache()), now, "alice", &parties()) {
|
||||
Err(ChainError::AdmissionDenied(m)) => assert!(m.contains("过期")),
|
||||
other => panic!("now={now} 必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_json_missing_fields_is_fail_closed() {
|
||||
assert!(MemberCache::from_json(r#"{"members":["alice"]}"#).is_err());
|
||||
assert!(MemberCache::from_json(r#"{"expires_at":9999}"#).is_err());
|
||||
// hard_rules_ok 缺失 ⇒ false ⇒ 准入拒绝,不是"没写就放过"。
|
||||
let c =
|
||||
MemberCache::from_json(r#"{"members":["alice","bob"],"expires_at":9999}"#).unwrap();
|
||||
assert!(!c.hard_rules_ok);
|
||||
match chain_admit(Some(&c), 1000, "alice", &parties()) {
|
||||
Err(ChainError::AdmissionDenied(m)) => {
|
||||
assert!(m.contains("硬规则"), "必须点明是硬规则未通过: {m}")
|
||||
}
|
||||
other => panic!("hard_rules_ok 缺失必须导致拒绝,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_rule_failure_is_denied() {
|
||||
let mut c = cache();
|
||||
c.hard_rules_ok = false;
|
||||
assert!(chain_admit(Some(&c), 1000, "alice", &parties()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_member_site_duplicate_and_too_few_are_denied() {
|
||||
assert!(chain_admit(Some(&cache()), 1000, "eve", &parties()).is_err());
|
||||
assert!(chain_admit(Some(&cache()), 1000, "alice", &parties()[..1]).is_err());
|
||||
let dup = vec![String::from("alice"), String::from("alice")];
|
||||
assert!(chain_admit(Some(&cache()), 1000, "alice", &dup).is_err());
|
||||
let outsider = vec![String::from("alice"), String::from("eve")];
|
||||
assert!(chain_admit(Some(&cache()), 1000, "alice", &outsider).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
//! 链上层(阶段 2 的**形状层**)。
|
||||
//!
|
||||
//! # 这一层现在是什么、不是什么
|
||||
//!
|
||||
//! 是:链上对象的规范编码与 SM3 摘要、JSON-RPC 最小面、幂等 outbox、
|
||||
//! 以及 fail-closed 的成员准入。全部可在本机用桩验证。
|
||||
//!
|
||||
//! **不是**:能签出一笔真实国密交易的客户端。国密模组(OpenSSL provider)、
|
||||
//! Tongsuo FFI、SM2 交易签名与 RLP 编码都**还没落地** —— 模组采购、
|
||||
//! distid 对齐、TLCP 通道三项仍需拍板/实测。`Signer` 只留 trait 形状和
|
||||
//! 启动自检接口,没有实现:**未配置即拒绝**,不假装可用。
|
||||
//!
|
||||
//! # 三条不能破的纪律
|
||||
//!
|
||||
//! 1. **`sm_crypto` 必须显式给,且本期只允许 `true`**。建链后不可改;
|
||||
//! `false` 对应链上 `keccak256Hash`,而 `mpc-core` 只有 sha256 与 SM3,
|
||||
//! 链下算不出 keccak256 —— 放行就是"摘要永远对不上"的假绿。
|
||||
//! 2. **fail-open 与 fail-closed 严格分开**:成员资格 / 硬规则
|
||||
//! (`admission`)fail-closed,缓存过期即拒;订单 / 回执存证
|
||||
//! (`outbox`)fail-open,链挂只入队、不阻断计算。两者不许互相借用。
|
||||
//! 3. **JSON-RPC 200 ≠ 成功**。HTTP 200 的响应体里带 `error` 字段是
|
||||
//! JSON-RPC 的正常失败形态;只判 HTTP 状态 = 把失败当成功。
|
||||
|
||||
pub mod admission;
|
||||
pub mod objects;
|
||||
pub mod outbox;
|
||||
pub mod rpc;
|
||||
pub mod signer;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// 链上层错误。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ChainError {
|
||||
/// 缺配置 / 能力未落地 —— 一律拒绝,不降级。
|
||||
NotConfigured(String),
|
||||
/// 配置值不合法。
|
||||
Config(String),
|
||||
/// 输入形状不合法。
|
||||
BadInput(String),
|
||||
/// IO / 网络。
|
||||
Io(String),
|
||||
/// JSON-RPC 返回了错误对象,或响应形状不合契约。
|
||||
Rpc(String),
|
||||
/// 准入拒绝(fail-closed 那一侧)。
|
||||
AdmissionDenied(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for ChainError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let (tag, msg) = match self {
|
||||
ChainError::NotConfigured(m) => ("未配置", m),
|
||||
ChainError::Config(m) => ("配置错误", m),
|
||||
ChainError::BadInput(m) => ("输入错误", m),
|
||||
ChainError::Io(m) => ("IO 错误", m),
|
||||
ChainError::Rpc(m) => ("链 RPC 错误", m),
|
||||
ChainError::AdmissionDenied(m) => ("准入拒绝", m),
|
||||
};
|
||||
write!(f, "{tag}: {msg}")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ChainError {}
|
||||
|
||||
/// 链配置。**每个字段都必须显式给**,缺一个就拒绝 —— 缺省值会让
|
||||
/// "这一跳到底是不是国密"变成隐式假设,而建链后 `sm_crypto` 不可改。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ChainConfig {
|
||||
/// `bcos-rpc` 的 `host:port`,不带 scheme 与路径。
|
||||
pub rpc_endpoint: String,
|
||||
/// 群组 ID(FISCO 3.x 的 `group_id`)。
|
||||
pub group_id: String,
|
||||
/// 链 ID。
|
||||
pub chain_id: String,
|
||||
/// 是否国密链。**必须显式 `true`**;缺失或 false 都拒绝。
|
||||
pub sm_crypto: bool,
|
||||
/// 客户端到 `bcos-rpc` 这一跳是否要求国密 TLCP。
|
||||
/// 官方文档没写死,必须显式声明;`true` 本期直接拒绝(TLCP 未实现)。
|
||||
pub client_tlcp: bool,
|
||||
}
|
||||
|
||||
impl ChainConfig {
|
||||
/// 从 JSON 解析配置。字段缺失一律 `NotConfigured`,不填默认值。
|
||||
pub fn from_json(text: &str) -> Result<Self, ChainError> {
|
||||
let v: serde_json::Value = serde_json::from_str(text)
|
||||
.map_err(|e| ChainError::BadInput(format!("链配置不是合法 JSON: {e}")))?;
|
||||
let obj = v
|
||||
.as_object()
|
||||
.ok_or_else(|| ChainError::BadInput(String::from("链配置必须是 JSON 对象")))?;
|
||||
|
||||
fn string<'a>(
|
||||
obj: &'a serde_json::Map<String, serde_json::Value>,
|
||||
key: &str,
|
||||
) -> Result<&'a str, ChainError> {
|
||||
let v = obj.get(key).ok_or_else(|| {
|
||||
ChainError::NotConfigured(format!("链配置缺少 {key},必须显式给值"))
|
||||
})?;
|
||||
v.as_str().ok_or_else(|| {
|
||||
ChainError::BadInput(format!("链配置 {key} 必须是字符串"))
|
||||
})
|
||||
}
|
||||
fn boolean(
|
||||
obj: &serde_json::Map<String, serde_json::Value>,
|
||||
key: &str,
|
||||
) -> Result<bool, ChainError> {
|
||||
let v = obj.get(key).ok_or_else(|| {
|
||||
ChainError::NotConfigured(format!("链配置缺少 {key},必须显式给值"))
|
||||
})?;
|
||||
v.as_bool().ok_or_else(|| {
|
||||
ChainError::BadInput(format!("链配置 {key} 必须是布尔值"))
|
||||
})
|
||||
}
|
||||
|
||||
let cfg = Self {
|
||||
rpc_endpoint: String::from(string(obj, "rpc_endpoint")?),
|
||||
group_id: String::from(string(obj, "group_id")?),
|
||||
chain_id: String::from(string(obj, "chain_id")?),
|
||||
sm_crypto: boolean(obj, "sm_crypto")?,
|
||||
client_tlcp: boolean(obj, "client_tlcp")?,
|
||||
};
|
||||
cfg.validate()?;
|
||||
Ok(cfg)
|
||||
}
|
||||
|
||||
/// 校验配置。任何"没想清楚"的项都必须在这里被拒,不能留到联调。
|
||||
pub fn validate(&self) -> Result<(), ChainError> {
|
||||
if !self.sm_crypto {
|
||||
return Err(ChainError::Config(String::from(
|
||||
"sm_crypto=false 本期不支持:标准版链上用 keccak256Hash,链下没有 keccak256 实现,摘要会对不上",
|
||||
)));
|
||||
}
|
||||
if self.client_tlcp {
|
||||
return Err(ChainError::NotConfigured(String::from(
|
||||
"客户端到 bcos-rpc 的国密 TLCP 通道未实测、Rust 侧也未实现,拒绝假装可用",
|
||||
)));
|
||||
}
|
||||
validate_endpoint(&self.rpc_endpoint)?;
|
||||
for (name, v) in [("group_id", &self.group_id), ("chain_id", &self.chain_id)] {
|
||||
if v.is_empty() || v.chars().any(|c| c.is_control() || c.is_whitespace()) {
|
||||
return Err(ChainError::BadInput(format!("{name} 为空或含控制字符")));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 本期唯一的哈希套件。链上 `CryptoPrecompiled` 的 `sm3(bytes)` 与
|
||||
/// `mpc_core::sm3::sm3` 同源;**不要在这里换成 sha256**(国密链没有
|
||||
/// sha256 预编译,见 `docs/INTEGRATION_ANALYSIS.md` 4.3⑤)。
|
||||
pub fn hash_suite(&self) -> &'static str {
|
||||
"sm3"
|
||||
}
|
||||
}
|
||||
|
||||
/// 按配置算摘要 —— 生成端与判定端共用这一份,不各写一个 hash 调用。
|
||||
pub fn digest_for_config(cfg: &ChainConfig, bytes: &[u8]) -> Result<[u8; 32], ChainError> {
|
||||
cfg.validate()?;
|
||||
Ok(mpc_core::sm3::sm3(bytes))
|
||||
}
|
||||
|
||||
/// endpoint 只认 `host:port`:把 URL / 路径塞进地址里会拼出意外的请求目标。
|
||||
pub fn validate_endpoint(ep: &str) -> Result<(), ChainError> {
|
||||
if ep.is_empty()
|
||||
|| ep.contains("://")
|
||||
|| ep.contains('/')
|
||||
|| ep.chars().any(|c| c.is_whitespace())
|
||||
{
|
||||
return Err(ChainError::BadInput(format!(
|
||||
"rpc_endpoint 只能是 host:port: {ep:?}"
|
||||
)));
|
||||
}
|
||||
let (host, port) = ep
|
||||
.rsplit_once(':')
|
||||
.ok_or_else(|| ChainError::BadInput(String::from("rpc_endpoint 缺少端口")))?;
|
||||
if host.is_empty()
|
||||
|| host
|
||||
.chars()
|
||||
.any(|c| !c.is_ascii_alphanumeric() && c != '.' && c != '-')
|
||||
{
|
||||
return Err(ChainError::BadInput(format!(
|
||||
"rpc_endpoint 主机名不合法: {host:?}"
|
||||
)));
|
||||
}
|
||||
let p: u32 = port
|
||||
.parse()
|
||||
.map_err(|_| ChainError::BadInput(format!("rpc 端口不合法: {port:?}")))?;
|
||||
if p == 0 || p > 65535 {
|
||||
return Err(ChainError::BadInput(format!("rpc 端口越界: {p}")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 严格 hex 编码。
|
||||
pub fn to_hex(bytes: &[u8]) -> String {
|
||||
const H: &[u8; 16] = b"0123456789abcdef";
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for &b in bytes {
|
||||
out.push(H[(b >> 4) as usize] as char);
|
||||
out.push(H[(b & 0x0f) as usize] as char);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// 严格 hex 解码:只认 0-9a-fA-F,长度必须偶数。
|
||||
pub fn from_hex(s: &str) -> Result<Vec<u8>, ChainError> {
|
||||
if s.len() % 2 != 0 {
|
||||
return Err(ChainError::BadInput(String::from("hex 长度必须是偶数")));
|
||||
}
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len() / 2);
|
||||
let val = |c: u8| -> Option<u8> {
|
||||
match c {
|
||||
b'0'..=b'9' => Some(c - b'0'),
|
||||
b'a'..=b'f' => Some(c - b'a' + 10),
|
||||
b'A'..=b'F' => Some(c - b'A' + 10),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
for i in (0..b.len()).step_by(2) {
|
||||
let hi = val(b[i])
|
||||
.ok_or_else(|| ChainError::BadInput(String::from("hex 含非法字符")))?;
|
||||
let lo = val(b[i + 1])
|
||||
.ok_or_else(|| ChainError::BadInput(String::from("hex 含非法字符")))?;
|
||||
out.push((hi << 4) | lo);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const CFG: &str = r#"{"rpc_endpoint":"127.0.0.1:20200","group_id":"group0","chain_id":"chain0","sm_crypto":true,"client_tlcp":false}"#;
|
||||
|
||||
#[test]
|
||||
fn config_requires_every_field_explicitly() {
|
||||
for key in [
|
||||
"rpc_endpoint",
|
||||
"group_id",
|
||||
"chain_id",
|
||||
"sm_crypto",
|
||||
"client_tlcp",
|
||||
] {
|
||||
let v: serde_json::Value = serde_json::from_str(CFG).unwrap();
|
||||
let mut m = v.as_object().unwrap().clone();
|
||||
m.remove(key);
|
||||
let text = serde_json::to_string(&m).unwrap();
|
||||
match ChainConfig::from_json(&text) {
|
||||
Err(ChainError::NotConfigured(msg)) => assert!(
|
||||
msg.contains(key),
|
||||
"缺 {key} 的拒绝原因必须点名该字段: {msg}"
|
||||
),
|
||||
other => panic!("缺 {key} 必须 NotConfigured,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_gm_chain_is_rejected_with_reason() {
|
||||
let text = CFG.replace("\"sm_crypto\":true", "\"sm_crypto\":false");
|
||||
match ChainConfig::from_json(&text) {
|
||||
Err(ChainError::Config(msg)) => {
|
||||
assert!(msg.contains("keccak256"), "必须说明为什么不支持: {msg}");
|
||||
}
|
||||
other => panic!("sm_crypto=false 必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tlcp_declared_but_unimplemented_is_rejected() {
|
||||
let text = CFG.replace("\"client_tlcp\":false", "\"client_tlcp\":true");
|
||||
match ChainConfig::from_json(&text) {
|
||||
Err(ChainError::NotConfigured(msg)) => {
|
||||
assert!(msg.contains("TLCP"), "必须点名未实现的能力: {msg}");
|
||||
}
|
||||
other => panic!("client_tlcp=true 必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_must_be_host_port_only() {
|
||||
for bad in [
|
||||
"http://127.0.0.1:20200",
|
||||
"127.0.0.1:20200/rpc",
|
||||
"127.0.0.1",
|
||||
"127.0.0.1:0",
|
||||
"127.0.0.1:99999",
|
||||
] {
|
||||
let text = CFG.replace("127.0.0.1:20200", bad);
|
||||
assert!(ChainConfig::from_json(&text).is_err(), "{bad} 必须被拒");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digest_is_sm3_and_goes_through_config_validation() {
|
||||
let cfg = ChainConfig::from_json(CFG).unwrap();
|
||||
assert_eq!(cfg.hash_suite(), "sm3");
|
||||
let d = digest_for_config(&cfg, b"abc").unwrap();
|
||||
assert_eq!(d, mpc_core::sm3::sm3(b"abc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_roundtrip_is_strict() {
|
||||
let raw = [0u8, 1, 15, 16, 254, 255];
|
||||
assert_eq!(from_hex(&to_hex(&raw)).unwrap(), raw);
|
||||
for bad in ["abc", "zz", "0g", ""] {
|
||||
if bad.is_empty() {
|
||||
continue; // 空串是合法输入(空字节串)
|
||||
}
|
||||
assert!(from_hex(bad).is_err(), "{bad:?} 必须被拒");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_config_roundtrips() {
|
||||
let cfg = ChainConfig::from_json(CFG).unwrap();
|
||||
assert_eq!(cfg.rpc_endpoint, "127.0.0.1:20200");
|
||||
assert!(cfg.sm_crypto);
|
||||
assert!(!cfg.client_tlcp);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,515 @@
|
||||
//! 链上对象:**只存 hash 与承诺,不存数据**。
|
||||
//!
|
||||
//! # 规范编码为什么单独成层
|
||||
//!
|
||||
//! 签名对象与摘要对象必须是**唯一确定的字节序列**:字段顺序固定、列表
|
||||
//! 带元素个数、变长字段一律 4 字节大端长度前缀(否则 `"ab"+"c"` 与
|
||||
//! `"a"+"bc"` 会撞成同一串)。站点端、宿主端、链上验证方各写一份编码
|
||||
//! 必然分叉,且分叉时**没有编译错误**,只表现为「hash 对不上」——
|
||||
//! 最容易被误判成 ABI 编码问题。
|
||||
//!
|
||||
//! 这里只提供 `canonical_bytes()`;算摘要统一走
|
||||
//! [`crate::digest_for_config`],全框架只有那一处 hash 调用。
|
||||
//!
|
||||
//! # 两个刻意的设计
|
||||
//!
|
||||
//! - **签名不编进被签内容**:`Receipt.signatures` 不进 canonical body
|
||||
//! (自指)。调用方对 `canonical_bytes()` 签名,再把签名附在对象上。
|
||||
//! - **`/attestation` 的四个布尔分开**:`AttestFlags` 没有 `ok` 合并字段,
|
||||
//! 缺字段一律当 `false` —— 「没拿到」与「不成立」在安全语义上必须同向。
|
||||
|
||||
use crate::{from_hex, ChainConfig, ChainError};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub const MEMBER_TAG: &[u8] = b"member";
|
||||
pub const ORDER_TAG: &[u8] = b"order";
|
||||
pub const RECEIPT_TAG: &[u8] = b"receipt";
|
||||
pub const BUNDLE_TAG: &[u8] = b"bundle";
|
||||
|
||||
/// 变长字段:4 字节大端长度前缀 + 内容。
|
||||
pub fn push_field(out: &mut Vec<u8>, bytes: &[u8]) {
|
||||
let len = u32::try_from(bytes.len()).expect("单个字段超过 4 GiB");
|
||||
out.extend_from_slice(&len.to_be_bytes());
|
||||
out.extend_from_slice(bytes);
|
||||
}
|
||||
|
||||
/// 链上对象共同接口。`canonical_bytes()` 只实现一次,禁止各对象另写一份。
|
||||
pub trait ChainObject {
|
||||
/// 对象类型标签,防止不同对象的字段布局意外撞成同一串。
|
||||
fn kind_tag(&self) -> &'static [u8];
|
||||
/// 只写**本体**;域分隔 / 类型标签 / 版本由 `canonical_bytes` 统一加。
|
||||
fn canonical_body(&self, out: &mut Vec<u8>);
|
||||
|
||||
fn canonical_bytes(&self) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
out.extend_from_slice(mpc_core::domain::TEE_CHAIN_OBJECT);
|
||||
push_field(&mut out, self.kind_tag());
|
||||
out.extend_from_slice(b"v1");
|
||||
self.canonical_body(&mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// 统一摘要入口 —— 生成端与判定端共用,先校验配置再算。
|
||||
pub fn object_digest(
|
||||
cfg: &ChainConfig,
|
||||
obj: &dyn ChainObject,
|
||||
) -> Result<[u8; 32], ChainError> {
|
||||
crate::digest_for_config(cfg, &obj.canonical_bytes())
|
||||
}
|
||||
|
||||
/// 联盟成员。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Member {
|
||||
pub member_id: String,
|
||||
pub sign_pubkey: Vec<u8>,
|
||||
pub platform: String,
|
||||
pub host_pubkeys: Vec<Vec<u8>>,
|
||||
pub active: bool,
|
||||
pub expires_at: u64,
|
||||
}
|
||||
|
||||
/// 计算订单。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ComputeOrder {
|
||||
pub order_id: String,
|
||||
pub participants: Vec<String>,
|
||||
pub catalog_id: String,
|
||||
pub ir_hash: [u8; 32],
|
||||
pub input_hashes: Vec<[u8; 32]>,
|
||||
pub min_tcb: u32,
|
||||
pub session_pubkey: Vec<u8>,
|
||||
pub policy_bundle_hash: [u8; 32],
|
||||
pub deadline: u64,
|
||||
}
|
||||
|
||||
/// `/attestation` 四个布尔,**不许合并成 `ok`**。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AttestFlags {
|
||||
pub user_data_ok: bool,
|
||||
pub meas_ok: bool,
|
||||
pub tcb_ok: bool,
|
||||
pub chip_sig: bool,
|
||||
}
|
||||
|
||||
impl AttestFlags {
|
||||
fn canonical_body(&self, out: &mut Vec<u8>) {
|
||||
out.push(u8::from(self.user_data_ok));
|
||||
out.push(u8::from(self.meas_ok));
|
||||
out.push(u8::from(self.tcb_ok));
|
||||
out.push(u8::from(self.chip_sig));
|
||||
}
|
||||
}
|
||||
|
||||
/// 计算回执。`user_data` 存原始 64 字节(国密链没有 sha256 预编译,
|
||||
/// 链上**不能重算**绑定值,只能由验证方离线比对)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Receipt {
|
||||
pub order_id: String,
|
||||
pub decision_id: String,
|
||||
pub result_hash: [u8; 32],
|
||||
pub input_hash: [u8; 32],
|
||||
pub user_data: [u8; 64],
|
||||
pub attest: AttestFlags,
|
||||
/// 实际链路路径(`p2p` / `relay` / `unknown`),不是策略档位。
|
||||
pub link: String,
|
||||
/// `TEE_LINK_BIND` 绑定摘要(`credential_id` 已绑进会话)。
|
||||
pub link_binding: [u8; 32],
|
||||
/// 各方签名 —— **不进 canonical body**(签名是产物,不是被签内容)。
|
||||
pub signatures: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// 策略 bundle 的链上登记。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PolicyBundleRecord {
|
||||
pub bundle_hash: [u8; 32],
|
||||
pub issuer: String,
|
||||
pub valid_from: u64,
|
||||
pub valid_until: u64,
|
||||
pub revoked: bool,
|
||||
}
|
||||
|
||||
impl ChainObject for Member {
|
||||
fn kind_tag(&self) -> &'static [u8] {
|
||||
MEMBER_TAG
|
||||
}
|
||||
fn canonical_body(&self, out: &mut Vec<u8>) {
|
||||
push_field(out, self.member_id.as_bytes());
|
||||
push_field(out, &self.sign_pubkey);
|
||||
push_field(out, self.platform.as_bytes());
|
||||
out.extend_from_slice(&(self.host_pubkeys.len() as u32).to_be_bytes());
|
||||
for k in &self.host_pubkeys {
|
||||
push_field(out, k);
|
||||
}
|
||||
out.push(u8::from(self.active));
|
||||
out.extend_from_slice(&self.expires_at.to_be_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainObject for ComputeOrder {
|
||||
fn kind_tag(&self) -> &'static [u8] {
|
||||
ORDER_TAG
|
||||
}
|
||||
fn canonical_body(&self, out: &mut Vec<u8>) {
|
||||
push_field(out, self.order_id.as_bytes());
|
||||
out.extend_from_slice(&(self.participants.len() as u32).to_be_bytes());
|
||||
for p in &self.participants {
|
||||
push_field(out, p.as_bytes());
|
||||
}
|
||||
push_field(out, self.catalog_id.as_bytes());
|
||||
out.extend_from_slice(&self.ir_hash);
|
||||
out.extend_from_slice(&(self.input_hashes.len() as u32).to_be_bytes());
|
||||
for h in &self.input_hashes {
|
||||
out.extend_from_slice(h);
|
||||
}
|
||||
out.extend_from_slice(&self.min_tcb.to_be_bytes());
|
||||
push_field(out, &self.session_pubkey);
|
||||
out.extend_from_slice(&self.policy_bundle_hash);
|
||||
out.extend_from_slice(&self.deadline.to_be_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainObject for Receipt {
|
||||
fn kind_tag(&self) -> &'static [u8] {
|
||||
RECEIPT_TAG
|
||||
}
|
||||
fn canonical_body(&self, out: &mut Vec<u8>) {
|
||||
push_field(out, self.order_id.as_bytes());
|
||||
push_field(out, self.decision_id.as_bytes());
|
||||
out.extend_from_slice(&self.result_hash);
|
||||
out.extend_from_slice(&self.input_hash);
|
||||
out.extend_from_slice(&self.user_data);
|
||||
self.attest.canonical_body(out);
|
||||
push_field(out, self.link.as_bytes());
|
||||
out.extend_from_slice(&self.link_binding);
|
||||
// 故意不写 self.signatures —— 自指。
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainObject for PolicyBundleRecord {
|
||||
fn kind_tag(&self) -> &'static [u8] {
|
||||
BUNDLE_TAG
|
||||
}
|
||||
fn canonical_body(&self, out: &mut Vec<u8>) {
|
||||
out.extend_from_slice(&self.bundle_hash);
|
||||
push_field(out, self.issuer.as_bytes());
|
||||
out.extend_from_slice(&self.valid_from.to_be_bytes());
|
||||
out.extend_from_slice(&self.valid_until.to_be_bytes());
|
||||
out.push(u8::from(self.revoked));
|
||||
}
|
||||
}
|
||||
|
||||
// --- JSON 解析:手写映射,字段名与错误都可控 ---
|
||||
|
||||
fn obj<'a>(v: &'a Value) -> Result<&'a Map<String, Value>, ChainError> {
|
||||
v.as_object().ok_or_else(|| {
|
||||
ChainError::BadInput(String::from("链上对象必须是 JSON 对象"))
|
||||
})
|
||||
}
|
||||
|
||||
fn get<'a>(m: &'a Map<String, Value>, key: &str) -> Result<&'a Value, ChainError> {
|
||||
m.get(key)
|
||||
.ok_or_else(|| ChainError::BadInput(format!("链上对象缺少字段 {key}")))
|
||||
}
|
||||
|
||||
fn text(m: &Map<String, Value>, key: &str) -> Result<String, ChainError> {
|
||||
let v = get(m, key)?;
|
||||
v.as_str()
|
||||
.map(String::from)
|
||||
.ok_or_else(|| ChainError::BadInput(format!("字段 {key} 必须是字符串")))
|
||||
}
|
||||
|
||||
fn num(m: &Map<String, Value>, key: &str) -> Result<u64, ChainError> {
|
||||
let v = get(m, key)?;
|
||||
v.as_u64()
|
||||
.ok_or_else(|| ChainError::BadInput(format!("字段 {key} 必须是非负整数")))
|
||||
}
|
||||
|
||||
/// 布尔字段**缺失一律当 false**:解析失败不能伪装成「验证通过」。
|
||||
fn bool_or_false(m: &Map<String, Value>, key: &str) -> bool {
|
||||
m.get(key).and_then(Value::as_bool).unwrap_or(false)
|
||||
}
|
||||
|
||||
fn bytes(m: &Map<String, Value>, key: &str) -> Result<Vec<u8>, ChainError> {
|
||||
let s = text(m, key)?;
|
||||
from_hex(&s).map_err(|e| ChainError::BadInput(format!("字段 {key} 不是合法 hex: {e}")))
|
||||
}
|
||||
|
||||
fn fixed<const N: usize>(m: &Map<String, Value>, key: &str) -> Result<[u8; N], ChainError> {
|
||||
let b = bytes(m, key)?;
|
||||
b.try_into().map_err(|_| {
|
||||
ChainError::BadInput(format!("字段 {key} 必须正好 {N} 字节 hex"))
|
||||
})
|
||||
}
|
||||
|
||||
fn text_vec(m: &Map<String, Value>, key: &str) -> Result<Vec<String>, ChainError> {
|
||||
let arr = get(m, key)?
|
||||
.as_array()
|
||||
.ok_or_else(|| ChainError::BadInput(format!("字段 {key} 必须是数组")))?;
|
||||
arr.iter()
|
||||
.map(|v| {
|
||||
v.as_str().map(String::from).ok_or_else(|| {
|
||||
ChainError::BadInput(format!("字段 {key} 的元素必须是字符串"))
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn bytes_vec(m: &Map<String, Value>, key: &str) -> Result<Vec<Vec<u8>>, ChainError> {
|
||||
let arr = get(m, key)?
|
||||
.as_array()
|
||||
.ok_or_else(|| ChainError::BadInput(format!("字段 {key} 必须是数组")))?;
|
||||
arr.iter()
|
||||
.map(|v| {
|
||||
let s = v.as_str().ok_or_else(|| {
|
||||
ChainError::BadInput(format!("字段 {key} 的元素必须是 hex 字符串"))
|
||||
})?;
|
||||
from_hex(s).map_err(|e| ChainError::BadInput(format!("字段 {key}: {e}")))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hash32_vec(m: &Map<String, Value>, key: &str) -> Result<Vec<[u8; 32]>, ChainError> {
|
||||
bytes_vec(m, key)?
|
||||
.into_iter()
|
||||
.map(|b| {
|
||||
<[u8; 32]>::try_from(b.as_slice()).map_err(|_| {
|
||||
ChainError::BadInput(format!("字段 {key} 的元素必须正好 32 字节"))
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl Member {
|
||||
pub fn from_json(text: &str) -> Result<Self, ChainError> {
|
||||
let v: Value = serde_json::from_str(text)
|
||||
.map_err(|e| ChainError::BadInput(format!("Member 不是合法 JSON: {e}")))?;
|
||||
let m = obj(&v)?;
|
||||
Ok(Self {
|
||||
member_id: text_field(m, "member_id")?,
|
||||
sign_pubkey: bytes(m, "sign_pubkey")?,
|
||||
platform: text_field(m, "platform")?,
|
||||
host_pubkeys: bytes_vec(m, "host_pubkeys")?,
|
||||
active: bool_or_false(m, "active"),
|
||||
expires_at: num(m, "expires_at")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ComputeOrder {
|
||||
pub fn from_json(text: &str) -> Result<Self, ChainError> {
|
||||
let v: Value = serde_json::from_str(text)
|
||||
.map_err(|e| ChainError::BadInput(format!("ComputeOrder 不是合法 JSON: {e}")))?;
|
||||
let m = obj(&v)?;
|
||||
Ok(Self {
|
||||
order_id: text_field(m, "order_id")?,
|
||||
participants: text_vec(m, "participants")?,
|
||||
catalog_id: text_field(m, "catalog_id")?,
|
||||
ir_hash: fixed(m, "ir_hash")?,
|
||||
input_hashes: hash32_vec(m, "input_hashes")?,
|
||||
min_tcb: u32::try_from(num(m, "min_tcb")?)
|
||||
.map_err(|_| ChainError::BadInput(String::from("min_tcb 超出 u32")))?,
|
||||
session_pubkey: bytes(m, "session_pubkey")?,
|
||||
policy_bundle_hash: fixed(m, "policy_bundle_hash")?,
|
||||
deadline: num(m, "deadline")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Receipt {
|
||||
pub fn from_json(text: &str) -> Result<Self, ChainError> {
|
||||
let v: Value = serde_json::from_str(text)
|
||||
.map_err(|e| ChainError::BadInput(format!("Receipt 不是合法 JSON: {e}")))?;
|
||||
let m = obj(&v)?;
|
||||
let flags = get(m, "attest")?;
|
||||
let fm = obj(flags)?;
|
||||
Ok(Self {
|
||||
order_id: text_field(m, "order_id")?,
|
||||
decision_id: text_field(m, "decision_id")?,
|
||||
result_hash: fixed(m, "result_hash")?,
|
||||
input_hash: fixed(m, "input_hash")?,
|
||||
user_data: fixed(m, "user_data")?,
|
||||
attest: AttestFlags {
|
||||
user_data_ok: bool_or_false(fm, "user_data_ok"),
|
||||
meas_ok: bool_or_false(fm, "meas_ok"),
|
||||
tcb_ok: bool_or_false(fm, "tcb_ok"),
|
||||
chip_sig: bool_or_false(fm, "chip_sig"),
|
||||
},
|
||||
link: text_field(m, "link")?,
|
||||
link_binding: fixed(m, "link_binding")?,
|
||||
signatures: bytes_vec(m, "signatures")?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl PolicyBundleRecord {
|
||||
pub fn from_json(text: &str) -> Result<Self, ChainError> {
|
||||
let v: Value = serde_json::from_str(text)
|
||||
.map_err(|e| ChainError::BadInput(format!("PolicyBundleRecord 不是合法 JSON: {e}")))?;
|
||||
let m = obj(&v)?;
|
||||
Ok(Self {
|
||||
bundle_hash: fixed(m, "bundle_hash")?,
|
||||
issuer: text_field(m, "issuer")?,
|
||||
valid_from: num(m, "valid_from")?,
|
||||
valid_until: num(m, "valid_until")?,
|
||||
revoked: bool_or_false(m, "revoked"),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// `text` 与结构体方法同名会遮蔽,取个别名。
|
||||
fn text_field(m: &Map<String, Value>, key: &str) -> Result<String, ChainError> {
|
||||
text(m, key)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::to_hex;
|
||||
|
||||
fn cfg() -> ChainConfig {
|
||||
ChainConfig::from_json(
|
||||
r#"{"rpc_endpoint":"127.0.0.1:20200","group_id":"group0","chain_id":"chain0","sm_crypto":true,"client_tlcp":false}"#,
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn order() -> ComputeOrder {
|
||||
ComputeOrder {
|
||||
order_id: String::from("order-1"),
|
||||
participants: vec![String::from("alice"), String::from("bob")],
|
||||
catalog_id: String::from("psi-v1"),
|
||||
ir_hash: [1u8; 32],
|
||||
input_hashes: vec![[2u8; 32], [3u8; 32]],
|
||||
min_tcb: 7,
|
||||
session_pubkey: vec![4u8; 65],
|
||||
policy_bundle_hash: [5u8; 32],
|
||||
deadline: 4102444800,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_bytes_are_deterministic_and_tagged() {
|
||||
let a = order().canonical_bytes();
|
||||
let b = order().canonical_bytes();
|
||||
assert_eq!(a, b);
|
||||
assert!(a.starts_with(mpc_core::domain::TEE_CHAIN_OBJECT));
|
||||
assert_ne!(a, PolicyBundleRecord {
|
||||
bundle_hash: [1u8; 32],
|
||||
issuer: String::from("x"),
|
||||
valid_from: 0,
|
||||
valid_until: 1,
|
||||
revoked: false,
|
||||
}
|
||||
.canonical_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_bytes_track_every_field() {
|
||||
let base = order().canonical_bytes();
|
||||
let mut o = order();
|
||||
o.min_tcb += 1;
|
||||
assert_ne!(base, o.canonical_bytes());
|
||||
let mut o = order();
|
||||
o.participants.push(String::from("carol"));
|
||||
assert_ne!(base, o.canonical_bytes());
|
||||
let mut o = order();
|
||||
o.input_hashes[0][0] ^= 1;
|
||||
assert_ne!(base, o.canonical_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_prefix_prevents_field_concatenation_collision() {
|
||||
let mut a = order();
|
||||
a.participants = vec![String::from("ab"), String::from("c")];
|
||||
let mut b = order();
|
||||
b.participants = vec![String::from("a"), String::from("bc")];
|
||||
assert_ne!(a.canonical_bytes(), b.canonical_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signature_is_not_part_of_signed_payload() {
|
||||
let mut r = receipt();
|
||||
r.signatures = vec![vec![9u8; 64]];
|
||||
let with = r.canonical_bytes();
|
||||
r.signatures.clear();
|
||||
assert_eq!(with, r.canonical_bytes());
|
||||
}
|
||||
|
||||
fn receipt() -> Receipt {
|
||||
Receipt {
|
||||
order_id: String::from("order-1"),
|
||||
decision_id: String::from("dec-1"),
|
||||
result_hash: [6u8; 32],
|
||||
input_hash: [7u8; 32],
|
||||
user_data: [8u8; 64],
|
||||
attest: AttestFlags {
|
||||
user_data_ok: true,
|
||||
meas_ok: true,
|
||||
tcb_ok: true,
|
||||
chip_sig: false,
|
||||
},
|
||||
link: String::from("p2p"),
|
||||
link_binding: [9u8; 32],
|
||||
signatures: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_attest_bool_defaults_to_false_not_true() {
|
||||
let mut v: Value = serde_json::from_str(
|
||||
&format!(
|
||||
r#"{{"order_id":"o","decision_id":"d","result_hash":"{}","input_hash":"{}","user_data":"{}","attest":{{}},"link":"p2p","link_binding":"{}","signatures":[]}}"#,
|
||||
to_hex(&[6u8; 32]),
|
||||
to_hex(&[7u8; 32]),
|
||||
to_hex(&[8u8; 64]),
|
||||
to_hex(&[9u8; 32]),
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let r = Receipt::from_json(&serde_json::to_string(&v).unwrap()).unwrap();
|
||||
assert!(!r.attest.user_data_ok);
|
||||
assert!(!r.attest.chip_sig);
|
||||
// 四个布尔都必须进 canonical body:改任一个,字节串必须变(长度不变)。
|
||||
// 比「和另一份 receipt 长度相等」更准 —— 后者会被字段长度差异干扰。
|
||||
let base = r.canonical_bytes();
|
||||
for flip in [
|
||||
|f: &mut AttestFlags| f.user_data_ok = true,
|
||||
|f: &mut AttestFlags| f.meas_ok = true,
|
||||
|f: &mut AttestFlags| f.tcb_ok = true,
|
||||
|f: &mut AttestFlags| f.chip_sig = true,
|
||||
] {
|
||||
let mut other = r.clone();
|
||||
flip(&mut other.attest);
|
||||
assert_ne!(base, other.canonical_bytes());
|
||||
assert_eq!(base.len(), other.canonical_bytes().len());
|
||||
}
|
||||
v.as_object_mut().unwrap().remove("order_id");
|
||||
assert!(Receipt::from_json(&serde_json::to_string(&v).unwrap()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digest_is_shared_and_config_gated() {
|
||||
let c = cfg();
|
||||
let d = object_digest(&c, &order()).unwrap();
|
||||
assert_eq!(d, crate::digest_for_config(&c, &order().canonical_bytes()).unwrap());
|
||||
let bad = ChainConfig::from_json(
|
||||
&r#"{"rpc_endpoint":"127.0.0.1:20200","group_id":"g","chain_id":"c","sm_crypto":false,"client_tlcp":false}"#
|
||||
.to_string(),
|
||||
);
|
||||
assert!(bad.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_length_fields_reject_wrong_size() {
|
||||
let s = format!(
|
||||
r#"{{"order_id":"o","participants":[],"catalog_id":"c","ir_hash":"{}","input_hashes":[],"min_tcb":1,"session_pubkey":"aa","policy_bundle_hash":"{}","deadline":1}}"#,
|
||||
to_hex(&[1u8; 31]),
|
||||
to_hex(&[2u8; 32]),
|
||||
);
|
||||
match ComputeOrder::from_json(&s) {
|
||||
Err(ChainError::BadInput(m)) => assert!(m.contains("32 字节")),
|
||||
other => panic!("长度不符必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
//! 存证 outbox —— **fail-open 这一侧**。
|
||||
//!
|
||||
//! 链是审计锚,不是执行前提:链挂了计算照跑,条目先落本地、恢复后补链。
|
||||
//! 与之相反,`admission` 是 fail-closed。**两者不许互相借用策略**。
|
||||
//!
|
||||
//! # 幂等
|
||||
//!
|
||||
//! 键 = `kind:order_id:decision_id`。同一键重复提交不新增、也**不覆盖**
|
||||
//! (覆盖会让补链写出与当时承诺不一致的账)。`decision_id` 的确定性
|
||||
//! 正好当幂等键,见 `docs/INTEGRATION_ANALYSIS.md` 4.7。
|
||||
//!
|
||||
//! # 为什么落盘格式这么朴素
|
||||
//!
|
||||
//! 每行定长字段用 `|` 分隔,变长内容一律 hex。这样重启回读不需要 JSON
|
||||
//! 解析器,也不会因为某个字段里带了分隔符而把后面的状态解析错。
|
||||
//! **坏行直接报错,绝不静默跳过** —— 跳过等于悄悄丢掉一条审计记录。
|
||||
|
||||
use crate::{from_hex, to_hex, ChainError};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum OutboxState {
|
||||
/// 还没被链接受。
|
||||
Pending,
|
||||
/// 已广播成功(**不代表链上已出块确认**;查回执是另一件事)。
|
||||
Confirmed,
|
||||
}
|
||||
|
||||
impl OutboxState {
|
||||
fn tag(self) -> &'static str {
|
||||
match self {
|
||||
OutboxState::Pending => "P",
|
||||
OutboxState::Confirmed => "C",
|
||||
}
|
||||
}
|
||||
fn parse(s: &str) -> Result<Self, ChainError> {
|
||||
match s {
|
||||
"P" => Ok(OutboxState::Pending),
|
||||
"C" => Ok(OutboxState::Confirmed),
|
||||
_ => Err(ChainError::Io(format!("outbox 状态标记不认识: {s:?}"))),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OutboxEntry {
|
||||
pub key: String,
|
||||
pub state: OutboxState,
|
||||
pub attempts: u32,
|
||||
pub payload_hex: String,
|
||||
pub last_error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EnqueueOutcome {
|
||||
Added,
|
||||
/// 同键已存在 —— 不新增、不覆盖。
|
||||
AlreadyPresent,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FlushReport {
|
||||
pub attempted: usize,
|
||||
pub confirmed: usize,
|
||||
/// (key, 拒绝原因) —— 失败**不吞**,调用方必须能看见。
|
||||
pub failed: Vec<(String, String)>,
|
||||
pub remaining: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Outbox {
|
||||
path: PathBuf,
|
||||
entries: BTreeMap<String, OutboxEntry>,
|
||||
}
|
||||
|
||||
/// 只允许 ASCII 字母数字与 `-_.`:id 会拼进用 `|` 分隔的行里。
|
||||
fn safe_id(v: &str, name: &str) -> Result<(), ChainError> {
|
||||
if v.is_empty()
|
||||
|| v.len() > 128
|
||||
|| !v
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
|
||||
{
|
||||
return Err(ChainError::BadInput(format!(
|
||||
"{name} 只能是 128 字节内的 ASCII 字母数字/-_.,得到 {v:?}"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Outbox {
|
||||
/// 打开(不存在视为空表,不立即创建)。已有文件坏一行就整体拒绝。
|
||||
pub fn open(path: impl AsRef<Path>) -> Result<Self, ChainError> {
|
||||
let path = path.as_ref().to_path_buf();
|
||||
let mut entries = BTreeMap::new();
|
||||
if path.exists() {
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| ChainError::Io(format!("读 outbox 失败: {e}")))?;
|
||||
for (lineno, line) in text.lines().enumerate() {
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let parts: Vec<&str> = line.split('|').collect();
|
||||
if parts.len() != 6 || parts[0] != "v1" {
|
||||
return Err(ChainError::Io(format!(
|
||||
"outbox 第 {} 行格式损坏,拒绝静默跳过",
|
||||
lineno + 1
|
||||
)));
|
||||
}
|
||||
let key = parts[1];
|
||||
if !key.is_empty() && entries.contains_key(key) {
|
||||
return Err(ChainError::Io(format!(
|
||||
"outbox 第 {} 行重复键 {key:?},拒绝静默合并",
|
||||
lineno + 1
|
||||
)));
|
||||
}
|
||||
let attempts: u32 = parts[3].parse().map_err(|_| {
|
||||
ChainError::Io(format!("outbox 第 {} 行 attempts 非法", lineno + 1))
|
||||
})?;
|
||||
// 变长字段是 hex,这里先验一次,避免把坏字节带进后续提交。
|
||||
let _ = from_hex(parts[4]).map_err(|e| {
|
||||
ChainError::Io(format!("outbox 第 {} 行 payload 非法: {e}", lineno + 1))
|
||||
})?;
|
||||
let err_hex = from_hex(parts[5]).map_err(|e| {
|
||||
ChainError::Io(format!("outbox 第 {} 行 last_error 非法: {e}", lineno + 1))
|
||||
})?;
|
||||
let last_error = if err_hex.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(String::from_utf8(err_hex).map_err(|_| {
|
||||
ChainError::Io(format!("outbox 第 {} 行 last_error 不是 UTF-8", lineno + 1))
|
||||
})?)
|
||||
};
|
||||
entries.insert(
|
||||
String::from(key),
|
||||
OutboxEntry {
|
||||
key: String::from(key),
|
||||
state: OutboxState::parse(parts[2])?,
|
||||
attempts,
|
||||
payload_hex: String::from(parts[4]),
|
||||
last_error,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(Self { path, entries })
|
||||
}
|
||||
|
||||
/// 写盘:先写临时文件再 rename,避免半截文件被下次启动读到。
|
||||
fn save(&self) -> Result<(), ChainError> {
|
||||
let mut text = String::new();
|
||||
for e in self.entries.values() {
|
||||
let err = e
|
||||
.last_error
|
||||
.as_deref()
|
||||
.map(|s| to_hex(s.as_bytes()))
|
||||
.unwrap_or_default();
|
||||
text.push_str(&format!(
|
||||
"v1|{}|{}|{}|{}|{}\n",
|
||||
e.key,
|
||||
e.state.tag(),
|
||||
e.attempts,
|
||||
e.payload_hex,
|
||||
err
|
||||
));
|
||||
}
|
||||
let tmp = PathBuf::from(format!("{}.tmp", self.path.display()));
|
||||
std::fs::write(&tmp, text)
|
||||
.map_err(|e| ChainError::Io(format!("写 outbox 临时文件失败: {e}")))?;
|
||||
std::fs::rename(&tmp, &self.path)
|
||||
.map_err(|e| ChainError::Io(format!("outbox 落盘失败: {e}")))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 入队。**链状态不参与这一步** —— 链挂不阻断计算。
|
||||
pub fn enqueue(
|
||||
&mut self,
|
||||
kind: &str,
|
||||
order_id: &str,
|
||||
decision_id: &str,
|
||||
payload: &[u8],
|
||||
) -> Result<EnqueueOutcome, ChainError> {
|
||||
safe_id(kind, "kind")?;
|
||||
safe_id(order_id, "order_id")?;
|
||||
safe_id(decision_id, "decision_id")?;
|
||||
let key = format!("{kind}:{order_id}:{decision_id}");
|
||||
if self.entries.contains_key(&key) {
|
||||
return Ok(EnqueueOutcome::AlreadyPresent);
|
||||
}
|
||||
self.entries.insert(
|
||||
key.clone(),
|
||||
OutboxEntry {
|
||||
key,
|
||||
state: OutboxState::Pending,
|
||||
attempts: 0,
|
||||
payload_hex: to_hex(payload),
|
||||
last_error: None,
|
||||
},
|
||||
);
|
||||
self.save()?;
|
||||
Ok(EnqueueOutcome::Added)
|
||||
}
|
||||
|
||||
/// 补链。`submit` 失败**不返回 Err**(fail-open),但会记进报告的
|
||||
/// `failed` 并保持 Pending,下次继续重试。
|
||||
pub fn flush_with<F>(&mut self, mut submit: F) -> Result<FlushReport, ChainError>
|
||||
where
|
||||
F: FnMut(&OutboxEntry) -> Result<(), ChainError>,
|
||||
{
|
||||
let keys: Vec<String> = self
|
||||
.entries
|
||||
.values()
|
||||
.filter(|e| e.state == OutboxState::Pending)
|
||||
.map(|e| e.key.clone())
|
||||
.collect();
|
||||
let mut confirmed = 0usize;
|
||||
let mut failed = Vec::new();
|
||||
for key in &keys {
|
||||
let entry = self.entries.get(key).expect("键来自本表");
|
||||
match submit(entry) {
|
||||
Ok(()) => {
|
||||
if let Some(e) = self.entries.get_mut(key) {
|
||||
e.state = OutboxState::Confirmed;
|
||||
e.last_error = None;
|
||||
}
|
||||
confirmed += 1;
|
||||
}
|
||||
Err(err) => {
|
||||
let reason = err.to_string();
|
||||
if let Some(e) = self.entries.get_mut(key) {
|
||||
e.attempts = e.attempts.saturating_add(1);
|
||||
e.last_error = Some(reason.clone());
|
||||
}
|
||||
failed.push((key.clone(), reason));
|
||||
}
|
||||
}
|
||||
}
|
||||
// 本地盘写失败是真错误(审计记录丢了),必须报出来。
|
||||
self.save()?;
|
||||
let remaining = self
|
||||
.entries
|
||||
.values()
|
||||
.filter(|e| e.state == OutboxState::Pending)
|
||||
.count();
|
||||
Ok(FlushReport {
|
||||
attempted: keys.len(),
|
||||
confirmed,
|
||||
failed,
|
||||
remaining,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn entries(&self) -> Vec<OutboxEntry> {
|
||||
self.entries.values().cloned().collect()
|
||||
}
|
||||
|
||||
pub fn pending_count(&self) -> usize {
|
||||
self
|
||||
.entries
|
||||
.values()
|
||||
.filter(|e| e.state == OutboxState::Pending)
|
||||
.count()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_path(tag: &str) -> PathBuf {
|
||||
std::env::temp_dir().join(format!(
|
||||
"mpc-chain-outbox-{tag}-{}.db",
|
||||
std::process::id()
|
||||
))
|
||||
}
|
||||
|
||||
fn clean(p: &Path) {
|
||||
let _ = std::fs::remove_file(p);
|
||||
let _ = std::fs::remove_file(format!("{}.tmp", p.display()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_key_is_idempotent_and_never_overwritten() {
|
||||
let p = temp_path("idem");
|
||||
clean(&p);
|
||||
let mut o = Outbox::open(&p).unwrap();
|
||||
assert_eq!(
|
||||
o.enqueue("receipt", "order-1", "dec-1", b"first").unwrap(),
|
||||
EnqueueOutcome::Added
|
||||
);
|
||||
assert_eq!(
|
||||
o.enqueue("receipt", "order-1", "dec-1", b"different").unwrap(),
|
||||
EnqueueOutcome::AlreadyPresent
|
||||
);
|
||||
assert_eq!(o.entries().len(), 1);
|
||||
assert_eq!(o.entries()[0].payload_hex, to_hex(b"first"));
|
||||
assert_eq!(
|
||||
o.enqueue("receipt", "order-1", "dec-2", b"second").unwrap(),
|
||||
EnqueueOutcome::Added
|
||||
);
|
||||
assert_eq!(o.entries().len(), 2);
|
||||
clean(&p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chain_down_is_fail_open_and_reason_is_not_swallowed() {
|
||||
let p = temp_path("failopen");
|
||||
clean(&p);
|
||||
let mut o = Outbox::open(&p).unwrap();
|
||||
o.enqueue("receipt", "o", "d", b"payload").unwrap();
|
||||
let r = o
|
||||
.flush_with(|_| Err(ChainError::Io(String::from("链不可达"))))
|
||||
.unwrap();
|
||||
assert_eq!(r.attempted, 1);
|
||||
assert_eq!(r.confirmed, 0);
|
||||
assert_eq!(r.failed.len(), 1);
|
||||
assert!(r.failed[0].1.contains("链不可达"), "失败原因不能被吞: {:?}", r.failed);
|
||||
assert_eq!(r.remaining, 1);
|
||||
assert_eq!(o.entries()[0].state, OutboxState::Pending);
|
||||
assert_eq!(o.entries()[0].attempts, 1);
|
||||
clean(&p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_confirms_and_second_flush_does_not_resend() {
|
||||
let p = temp_path("recover");
|
||||
clean(&p);
|
||||
let mut o = Outbox::open(&p).unwrap();
|
||||
o.enqueue("receipt", "o", "d", b"payload").unwrap();
|
||||
let mut calls = 0;
|
||||
let r = o
|
||||
.flush_with(|_| {
|
||||
calls += 1;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!((r.confirmed, r.remaining, calls), (1, 0, 1));
|
||||
let r2 = o
|
||||
.flush_with(|_| {
|
||||
calls += 1;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!((r2.attempted, calls), (0, 1), "已确认条目绝不能重复发送");
|
||||
clean(&p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_reads_state_back() {
|
||||
let p = temp_path("restart");
|
||||
clean(&p);
|
||||
{
|
||||
let mut o = Outbox::open(&p).unwrap();
|
||||
o.enqueue("receipt", "o", "d", b"abc").unwrap();
|
||||
o.flush_with(|_| Ok(())).unwrap();
|
||||
}
|
||||
let o = Outbox::open(&p).unwrap();
|
||||
assert_eq!(o.entries().len(), 1);
|
||||
assert_eq!(o.entries()[0].state, OutboxState::Confirmed);
|
||||
assert_eq!(o.entries()[0].payload_hex, to_hex(b"abc"));
|
||||
clean(&p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_line_is_rejected_not_skipped() {
|
||||
let p = temp_path("corrupt");
|
||||
clean(&p);
|
||||
std::fs::write(&p, "v1|bad|line\n").unwrap();
|
||||
match Outbox::open(&p) {
|
||||
Err(ChainError::Io(m)) => assert!(m.contains("格式损坏")),
|
||||
other => panic!("坏行必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
clean(&p);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_with_separator_or_control_chars_are_rejected() {
|
||||
let p = temp_path("ids");
|
||||
clean(&p);
|
||||
let mut o = Outbox::open(&p).unwrap();
|
||||
for bad in ["a|b", "a\nb", "", "中文", "a:b"] {
|
||||
assert!(
|
||||
o.enqueue("receipt", bad, "d", b"x").is_err(),
|
||||
"{bad:?} 会破坏行格式,必须拒绝"
|
||||
);
|
||||
}
|
||||
clean(&p);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
//! JSON-RPC 最小面(FISCO BCOS 3.x)。
|
||||
//!
|
||||
//! # 方法名的来源
|
||||
//!
|
||||
//! `docs/INTEGRATION_ANALYSIS.md` 4.8 初稿写「自有 JSON-RPC、不是 `eth_`
|
||||
//! 兼容」。用 gitea 镜像核对源码后这是 **2.x 的老结论**:3.x 的
|
||||
//! `bcos-rpc/bcos-rpc/web3jsonrpc/endpoints/EthMethods.h` 里明确列了
|
||||
//! `eth_sendRawTransaction` / `eth_call` / `eth_getTransactionReceipt`,
|
||||
//! 而 `sendTransaction` 全仓搜不到。所以常量按 3.x 写,且**钉在测试里**。
|
||||
//!
|
||||
//! 仍需真机确认的一件事:国密链(`sm_crypto=true`)的交易是否也走这个
|
||||
//! web3 端点 —— RPC 方法名兼容不等于交易签名 / RLP 结构兼容。这条写进
|
||||
//! 文档待实测项,不在这里假装已知。
|
||||
//!
|
||||
//! # ★ HTTP 200 ≠ 成功
|
||||
//!
|
||||
//! JSON-RPC 的错误走响应体里的 `error` 对象,HTTP 状态仍是 200。只判
|
||||
//! HTTP 状态会把「交易被拒」当「已上链」。同理 `result: null` 是「还没
|
||||
//! 出块」,既不是成功也不是失败,绝不能折成 `true`。
|
||||
|
||||
use crate::{validate_endpoint, ChainError};
|
||||
use reqwest::blocking::Client;
|
||||
use reqwest::header::{CONNECTION, CONTENT_LENGTH, CONTENT_TYPE, TRANSFER_ENCODING};
|
||||
use reqwest::redirect::Policy;
|
||||
use serde_json::{Map, Value};
|
||||
use std::time::Duration;
|
||||
|
||||
/// 依据:`bcos-rpc/bcos-rpc/web3jsonrpc/endpoints/EthMethods.h`(3.x)。
|
||||
pub const METHOD_SEND_RAW_TX: &str = "eth_sendRawTransaction";
|
||||
pub const METHOD_GET_RECEIPT: &str = "eth_getTransactionReceipt";
|
||||
pub const METHOD_CALL: &str = "eth_call";
|
||||
|
||||
const CONNECT_TIMEOUT_SECS: u64 = 10;
|
||||
const REQUEST_TIMEOUT_SECS: u64 = 30;
|
||||
const MAX_RESPONSE_BYTES: usize = 4 * 1024 * 1024;
|
||||
|
||||
/// 构造 JSON-RPC 2.0 请求体。`id` 由调用方给,响应必须回同一个 id。
|
||||
pub fn request_json(id: u64, method: &str, params: Value) -> String {
|
||||
let mut m = Map::new();
|
||||
m.insert(String::from("jsonrpc"), Value::String(String::from("2.0")));
|
||||
m.insert(String::from("id"), Value::from(id));
|
||||
m.insert(String::from("method"), Value::String(String::from(method)));
|
||||
m.insert(String::from("params"), params);
|
||||
serde_json::to_string(&Value::Object(m)).expect("JSON-RPC 请求体序列化不会失败")
|
||||
}
|
||||
|
||||
/// 解析 JSON-RPC 响应。`Ok(None)` 表示 `result: null`(尚未出块),
|
||||
/// **不是成功**;一切不确定都返回 `Err`。
|
||||
pub fn parse_response(expected_id: u64, text: &str) -> Result<Option<Value>, ChainError> {
|
||||
let v: Value = serde_json::from_str(text)
|
||||
.map_err(|e| ChainError::Rpc(format!("响应不是合法 JSON: {e}")))?;
|
||||
let m = v
|
||||
.as_object()
|
||||
.ok_or_else(|| ChainError::Rpc(String::from("JSON-RPC 响应必须是对象")))?;
|
||||
if m.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
|
||||
return Err(ChainError::Rpc(String::from("jsonrpc 版本不是 2.0")));
|
||||
}
|
||||
let got_id = m
|
||||
.get("id")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| ChainError::Rpc(String::from("响应缺少数值 id")))?;
|
||||
if got_id != expected_id {
|
||||
return Err(ChainError::Rpc(format!(
|
||||
"响应 id={got_id} 与请求 id={expected_id} 不符,拒绝串包"
|
||||
)));
|
||||
}
|
||||
// ★ 先判 error,再判 result —— 顺序反了会把失败当成功。
|
||||
if let Some(err) = m.get("error") {
|
||||
if !err.is_null() {
|
||||
let reason = err
|
||||
.as_object()
|
||||
.and_then(|o| o.get("message"))
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("(无 message)");
|
||||
let code = err
|
||||
.as_object()
|
||||
.and_then(|o| o.get("code"))
|
||||
.map(|c| c.to_string())
|
||||
.unwrap_or_else(|| String::from("?"));
|
||||
return Err(ChainError::Rpc(format!(
|
||||
"JSON-RPC error code={code}: {reason}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
let result = m
|
||||
.get("result")
|
||||
.ok_or_else(|| ChainError::Rpc(String::from("响应缺少 result 字段,拒绝当成成功")))?;
|
||||
if result.is_null() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(result.clone()))
|
||||
}
|
||||
|
||||
/// 链上回执视图。**`status` 缺失一律 false**("没拿到"与"不成立"同向)。
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ChainReceiptView {
|
||||
pub status_ok: bool,
|
||||
pub block_number: Option<u64>,
|
||||
pub transaction_hash: String,
|
||||
}
|
||||
|
||||
/// 可插拔链客户端。桩自测用假 JSON-RPC 服务,真机换 `HttpChainClient`。
|
||||
pub trait ChainClient {
|
||||
fn send_raw_transaction(&self, raw_tx_hex: &str) -> Result<String, ChainError>;
|
||||
fn get_transaction_receipt(
|
||||
&self,
|
||||
tx_hash: &str,
|
||||
) -> Result<Option<ChainReceiptView>, ChainError>;
|
||||
fn call(&self, to: &str, data: &str) -> Result<String, ChainError>;
|
||||
}
|
||||
|
||||
/// 走 `bcos-rpc` 的 HTTP 客户端。fail-closed 判据与 `mpc_hostd::HostClient`
|
||||
/// 同口径:endpoint 只认 `host:port`、带超时、禁重定向、准确
|
||||
/// `Content-Length`、拒绝 chunked 与重复 CL。
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HttpChainClient {
|
||||
pub endpoint: String,
|
||||
}
|
||||
|
||||
impl HttpChainClient {
|
||||
pub fn new(endpoint: impl Into<String>) -> Result<Self, ChainError> {
|
||||
let endpoint = endpoint.into();
|
||||
validate_endpoint(&endpoint)?;
|
||||
Ok(Self { endpoint })
|
||||
}
|
||||
|
||||
pub fn request(
|
||||
&self,
|
||||
id: u64,
|
||||
method: &str,
|
||||
params: Value,
|
||||
) -> Result<Option<Value>, ChainError> {
|
||||
validate_endpoint(&self.endpoint)?;
|
||||
let body = request_json(id, method, params);
|
||||
let client = Client::builder()
|
||||
.connect_timeout(Duration::from_secs(CONNECT_TIMEOUT_SECS))
|
||||
.timeout(Duration::from_secs(REQUEST_TIMEOUT_SECS))
|
||||
.redirect(Policy::none())
|
||||
// ★ 只连显式配置的 host:port,绝不让系统代理把请求转走。
|
||||
// 代理会改变「这一跳的端点」:桩测试里表现为回环端口被
|
||||
// 代理接走后返回 502(而不是 Connection refused),
|
||||
// 生产里则会让「客户端到 bcos-rpc 是否需要国密 TLS」
|
||||
// 的实测结论整个失效(TLS 终止点变了)。
|
||||
.no_proxy()
|
||||
.build()
|
||||
.map_err(|e| ChainError::Io(format!("构造链客户端失败: {e}")))?;
|
||||
let resp = client
|
||||
.post(format!("http://{}", self.endpoint))
|
||||
.header(CONNECTION, "close")
|
||||
.header(CONTENT_TYPE, "application/json")
|
||||
.body(body)
|
||||
.send()
|
||||
.map_err(|e| {
|
||||
ChainError::Io(format!(
|
||||
"连 bcos-rpc 失败({CONNECT_TIMEOUT_SECS} 秒连接超时): {e}"
|
||||
))
|
||||
})?;
|
||||
|
||||
let hdrs = resp.headers();
|
||||
if hdrs
|
||||
.get_all(TRANSFER_ENCODING)
|
||||
.iter()
|
||||
.any(|v| v.to_str().unwrap_or("").to_ascii_lowercase().contains("chunked"))
|
||||
{
|
||||
return Err(ChainError::Rpc(String::from(
|
||||
"链响应使用 chunked,客户端不解析,拒绝放行",
|
||||
)));
|
||||
}
|
||||
let cl: Vec<_> = hdrs.get_all(CONTENT_LENGTH).iter().collect();
|
||||
if cl.len() > 1 || cl.iter().any(|v| v.to_str().unwrap_or("").contains(',')) {
|
||||
return Err(ChainError::Rpc(String::from(
|
||||
"链响应有重复的 Content-Length,拒绝放行",
|
||||
)));
|
||||
}
|
||||
let len: usize = cl
|
||||
.first()
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.parse().ok())
|
||||
.ok_or_else(|| {
|
||||
ChainError::Rpc(String::from("链响应缺少 Content-Length,拒绝放行"))
|
||||
})?;
|
||||
if len > MAX_RESPONSE_BYTES {
|
||||
return Err(ChainError::Rpc(format!("链响应超过 {MAX_RESPONSE_BYTES} 字节上限")));
|
||||
}
|
||||
let code = resp.status().as_u16();
|
||||
let bytes = resp
|
||||
.bytes()
|
||||
.map_err(|e| ChainError::Io(format!("读链响应失败: {e}")))?;
|
||||
if bytes.len() != len {
|
||||
return Err(ChainError::Rpc(format!(
|
||||
"链 Content-Length={len} 与实际 body={} 不符",
|
||||
bytes.len()
|
||||
)));
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes).to_string();
|
||||
if !(200..300).contains(&code) {
|
||||
return Err(ChainError::Rpc(format!(
|
||||
"bcos-rpc 返回 HTTP {code}: {}",
|
||||
text.chars().take(200).collect::<String>()
|
||||
)));
|
||||
}
|
||||
parse_response(id, &text)
|
||||
}
|
||||
}
|
||||
|
||||
impl ChainClient for HttpChainClient {
|
||||
fn send_raw_transaction(&self, raw_tx_hex: &str) -> Result<String, ChainError> {
|
||||
let v = self
|
||||
.request(1, METHOD_SEND_RAW_TX, serde_json::json!([raw_tx_hex]))?
|
||||
.ok_or_else(|| {
|
||||
ChainError::Rpc(String::from("sendRawTransaction 返回 null,不能当作已上链"))
|
||||
})?;
|
||||
v.as_str().map(String::from).ok_or_else(|| {
|
||||
ChainError::Rpc(String::from("sendRawTransaction 的 result 不是交易哈希字符串"))
|
||||
})
|
||||
}
|
||||
|
||||
fn get_transaction_receipt(
|
||||
&self,
|
||||
tx_hash: &str,
|
||||
) -> Result<Option<ChainReceiptView>, ChainError> {
|
||||
let v = self.request(2, METHOD_GET_RECEIPT, serde_json::json!([tx_hash]))?;
|
||||
let Some(v) = v else {
|
||||
return Ok(None); // 还没出块:既不是成功也不是失败。
|
||||
};
|
||||
let m = v
|
||||
.as_object()
|
||||
.ok_or_else(|| ChainError::Rpc(String::from("回执 result 不是对象")))?;
|
||||
let status_ok = match m.get("status") {
|
||||
Some(Value::String(s)) => s == "0x1" || s == "1",
|
||||
Some(Value::Number(n)) => n.as_u64() == Some(1),
|
||||
_ => false, // 缺失 / 形状不认识 ⇒ false,绝不 true。
|
||||
};
|
||||
Ok(Some(ChainReceiptView {
|
||||
status_ok,
|
||||
block_number: m.get("blockNumber").and_then(Value::as_u64),
|
||||
transaction_hash: m
|
||||
.get("transactionHash")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn call(&self, to: &str, data: &str) -> Result<String, ChainError> {
|
||||
let v = self
|
||||
.request(3, METHOD_CALL, serde_json::json!([{ "to": to, "data": data }, "latest"]))?
|
||||
.ok_or_else(|| ChainError::Rpc(String::from("call 返回 null")))?;
|
||||
v.as_str().map(String::from).ok_or_else(|| {
|
||||
ChainError::Rpc(String::from("call 的 result 不是字符串"))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::TcpListener;
|
||||
use std::thread;
|
||||
|
||||
/// 起一个只服务一次的最小 HTTP 服务,返回固定响应。
|
||||
fn serve_once(response: Vec<u8>) -> (u16, thread::JoinHandle<()>) {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let h = thread::spawn(move || {
|
||||
let (mut s, _) = listener.accept().unwrap();
|
||||
let mut buf = [0u8; 8192];
|
||||
let n = s.read(&mut buf).unwrap();
|
||||
let _ = n;
|
||||
s.write_all(&response).unwrap();
|
||||
});
|
||||
(port, h)
|
||||
}
|
||||
|
||||
fn http(body: &str, code: u16) -> Vec<u8> {
|
||||
format!(
|
||||
"HTTP/1.1 {code} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
body.len(),
|
||||
body
|
||||
)
|
||||
.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn method_names_match_upstream_3x_enum() {
|
||||
// 改这里就等于改协议,必须同步改文档与桩服务。
|
||||
assert_eq!(METHOD_SEND_RAW_TX, "eth_sendRawTransaction");
|
||||
assert_eq!(METHOD_GET_RECEIPT, "eth_getTransactionReceipt");
|
||||
assert_eq!(METHOD_CALL, "eth_call");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_json_has_exact_shape() {
|
||||
let s = request_json(7, METHOD_CALL, serde_json::json!(["x"]));
|
||||
let v: Value = serde_json::from_str(&s).unwrap();
|
||||
assert_eq!(v["jsonrpc"], "2.0");
|
||||
assert_eq!(v["id"], 7);
|
||||
assert_eq!(v["method"], "eth_call");
|
||||
assert!(v["params"].is_array());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_200_with_error_object_is_rejected_with_reason() {
|
||||
let body = r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32000,"message":"invalid signature"}}"#;
|
||||
match parse_response(1, body) {
|
||||
Err(ChainError::Rpc(m)) => {
|
||||
assert!(m.contains("invalid signature"), "必须带出服务端原因: {m}");
|
||||
assert!(m.contains("-32000"));
|
||||
}
|
||||
other => panic!("HTTP 200 + error 必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_result_is_rejected_and_null_is_not_success() {
|
||||
assert!(parse_response(1, r#"{"jsonrpc":"2.0","id":1}"#).is_err());
|
||||
assert_eq!(parse_response(1, r#"{"jsonrpc":"2.0","id":1,"result":null}"#).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mismatched_id_is_rejected() {
|
||||
let body = r#"{"jsonrpc":"2.0","id":9,"result":"0xabc"}"#;
|
||||
match parse_response(1, body) {
|
||||
Err(ChainError::Rpc(m)) => assert!(m.contains("串包")),
|
||||
other => panic!("id 不符必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receipt_status_missing_defaults_to_false_in_real_parse() {
|
||||
// ★ 必须真的走一遍 get_transaction_receipt,否则「缺失当 false」
|
||||
// 这条判据只是纸面文章(测不到就等于没有)。
|
||||
let no_status =
|
||||
http(r#"{"jsonrpc":"2.0","id":2,"result":{"transactionHash":"0x1"}}"#, 200);
|
||||
let (port, h) = serve_once(no_status);
|
||||
let c = HttpChainClient::new(format!("127.0.0.1:{port}")).unwrap();
|
||||
let r = c.get_transaction_receipt("0x1").unwrap().unwrap();
|
||||
assert!(!r.status_ok, "status 缺失绝不能伪装成上链成功");
|
||||
h.join().unwrap();
|
||||
|
||||
let good = http(
|
||||
r#"{"jsonrpc":"2.0","id":2,"result":{"transactionHash":"0x1","status":"0x1","blockNumber":7}}"#,
|
||||
200,
|
||||
);
|
||||
let (port, h) = serve_once(good);
|
||||
let c = HttpChainClient::new(format!("127.0.0.1:{port}")).unwrap();
|
||||
let r = c.get_transaction_receipt("0x1").unwrap().unwrap();
|
||||
assert!(r.status_ok);
|
||||
assert_eq!(r.block_number, Some(7));
|
||||
h.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_client_rejects_chunked_and_missing_cl() {
|
||||
let chunked = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Length: 2\r\n\r\n{}".to_vec();
|
||||
let (port, h) = serve_once(chunked);
|
||||
let c = HttpChainClient::new(format!("127.0.0.1:{port}")).unwrap();
|
||||
match c.request(1, METHOD_CALL, serde_json::json!([])) {
|
||||
Err(ChainError::Rpc(m)) => assert!(m.contains("chunked")),
|
||||
other => panic!("chunked 必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
h.join().unwrap();
|
||||
|
||||
let no_cl = b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n{}".to_vec();
|
||||
let (port, h) = serve_once(no_cl);
|
||||
let c = HttpChainClient::new(format!("127.0.0.1:{port}")).unwrap();
|
||||
assert!(c.request(1, METHOD_CALL, serde_json::json!([])).is_err());
|
||||
h.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_client_surfaces_non_2xx_body_and_parses_success() {
|
||||
let (port, h) = serve_once(http("chain down", 503));
|
||||
let c = HttpChainClient::new(format!("127.0.0.1:{port}")).unwrap();
|
||||
match c.request(1, METHOD_CALL, serde_json::json!([])) {
|
||||
Err(ChainError::Rpc(m)) => assert!(m.contains("503") && m.contains("chain down")),
|
||||
other => panic!("503 必须带出响应体,得到 {other:?}"),
|
||||
}
|
||||
h.join().unwrap();
|
||||
|
||||
let ok = http(r#"{"jsonrpc":"2.0","id":1,"result":"0xdead"}"#, 200);
|
||||
let (port, h) = serve_once(ok);
|
||||
let c = HttpChainClient::new(format!("127.0.0.1:{port}")).unwrap();
|
||||
assert_eq!(
|
||||
c.request(1, METHOD_CALL, serde_json::json!([])).unwrap(),
|
||||
Some(Value::String(String::from("0xdead")))
|
||||
);
|
||||
h.join().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_rejects_urls_and_paths() {
|
||||
for bad in ["http://127.0.0.1:20200", "127.0.0.1:20200/rpc", "127.0.0.1"] {
|
||||
assert!(HttpChainClient::new(bad).is_err(), "{bad} 必须被拒");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! 交易签名器 —— **本期只落形状,没有实现**。
|
||||
//!
|
||||
//! 生产实现应是 `ModuleSigner`:独立 `OSSL_LIB_CTX` + `Provider::load`
|
||||
//! (禁 fallback)走国密模组,私钥不出硬件。它依赖三件尚未到位的东西:
|
||||
//! 模组采购与驱动、Tongsuo ≥ 8.4 的 FFI、以及 SM2 distid 三重对齐。
|
||||
//! 在这之前**不写软件签名器充数**:RustCrypto 的 `sm2` 未经独立审计,
|
||||
//! 拿它签生产交易等于把「密评可过」这一条悄悄作废。
|
||||
//!
|
||||
//! 所以本模块只有 trait 与自检接口,配套两个纪律:
|
||||
//! - `require_signer(None)` ⇒ **拒绝**(不是「不签就放过」);
|
||||
//! - 启动自检三件任一不满足 ⇒ 拒绝启动。
|
||||
|
||||
use crate::ChainError;
|
||||
|
||||
/// 启动自检三件(对应 `docs/INTEGRATION_ANALYSIS.md` 4.3④)。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SignerSelfTest {
|
||||
/// 独立 libctx 里 provider 加载成功且 SM2 可用。
|
||||
pub provider_loaded: bool,
|
||||
/// 私钥参数不可导出(`OSSL_PKEY_PARAM_PRIV_KEY` 读取必须失败)。
|
||||
pub private_key_unexportable: bool,
|
||||
/// 已知答案试签与 KAT 向量一致(签名格式 / distid 对齐)。
|
||||
pub kat_ok: bool,
|
||||
}
|
||||
|
||||
impl SignerSelfTest {
|
||||
pub fn all_pass(&self) -> bool {
|
||||
self.provider_loaded && self.private_key_unexportable && self.kat_ok
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Signer {
|
||||
/// 算法标识,生产应为 `"SM2"`。
|
||||
fn algorithm(&self) -> &str;
|
||||
/// 公钥字节(进 `Member.sign_pubkey`)。
|
||||
fn public_key(&self) -> &[u8];
|
||||
/// 对**规范字节序列**签名。调用方传的是 `canonical_bytes()`,不是签名自身。
|
||||
fn sign(&self, payload: &[u8]) -> Result<Vec<u8>, ChainError>;
|
||||
/// 启动自检。实现方必须真的做这三件事,不能返回全 true 充数。
|
||||
fn self_test(&self) -> Result<SignerSelfTest, ChainError>;
|
||||
}
|
||||
|
||||
/// 未配置签名器即拒绝。
|
||||
pub fn require_signer(s: Option<&dyn Signer>) -> Result<&dyn Signer, ChainError> {
|
||||
s.ok_or_else(|| {
|
||||
ChainError::NotConfigured(String::from(
|
||||
"未配置 SM2 签名器(国密模组 provider 未落地),拒绝生成交易",
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
/// 自检三件任一失败就拒绝启动 —— 与「密钥缺省 ⇒ 拒绝启动」同一纪律。
|
||||
pub fn require_self_test(s: &dyn Signer) -> Result<(), ChainError> {
|
||||
let r = s.self_test()?;
|
||||
if !r.all_pass() {
|
||||
return Err(ChainError::NotConfigured(format!(
|
||||
"签名器启动自检未通过: provider_loaded={} private_key_unexportable={} kat_ok={}",
|
||||
r.provider_loaded, r.private_key_unexportable, r.kat_ok
|
||||
)));
|
||||
}
|
||||
if s.algorithm() != "SM2" {
|
||||
return Err(ChainError::Config(format!(
|
||||
"国密链只接受 SM2 签名器,得到 {:?}",
|
||||
s.algorithm()
|
||||
)));
|
||||
}
|
||||
if s.public_key().is_empty() {
|
||||
return Err(ChainError::Config(String::from("签名器公钥为空")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
struct Fake {
|
||||
test: SignerSelfTest,
|
||||
alg: &'static str,
|
||||
}
|
||||
impl Signer for Fake {
|
||||
fn algorithm(&self) -> &str {
|
||||
self.alg
|
||||
}
|
||||
fn public_key(&self) -> &[u8] {
|
||||
&[1u8, 2, 3]
|
||||
}
|
||||
fn sign(&self, _p: &[u8]) -> Result<Vec<u8>, ChainError> {
|
||||
Ok(vec![0u8; 64])
|
||||
}
|
||||
fn self_test(&self) -> Result<SignerSelfTest, ChainError> {
|
||||
Ok(self.test)
|
||||
}
|
||||
}
|
||||
const PASS: SignerSelfTest = SignerSelfTest {
|
||||
provider_loaded: true,
|
||||
private_key_unexportable: true,
|
||||
kat_ok: true,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn missing_signer_is_rejected_not_skipped() {
|
||||
match require_signer(None) {
|
||||
Err(ChainError::NotConfigured(m)) => assert!(m.contains("未配置")),
|
||||
Err(e) => panic!("必须是 NotConfigured,得到 {e}"),
|
||||
Ok(_) => panic!("未配置签名器必须拒绝"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_self_test_item_can_fail_independently() {
|
||||
// ★ 三件必须能被单独测到:并成一项 = 某一件永远没跑还显示通过。
|
||||
for (name, t) in [
|
||||
(
|
||||
"provider_loaded",
|
||||
SignerSelfTest { provider_loaded: false, ..PASS },
|
||||
),
|
||||
(
|
||||
"private_key_unexportable",
|
||||
SignerSelfTest { private_key_unexportable: false, ..PASS },
|
||||
),
|
||||
("kat_ok", SignerSelfTest { kat_ok: false, ..PASS }),
|
||||
] {
|
||||
let s = Fake { test: t, alg: "SM2" };
|
||||
match require_self_test(&s) {
|
||||
Err(ChainError::NotConfigured(m)) => assert!(
|
||||
m.contains(name),
|
||||
"失败项 {name} 必须在拒绝原因里出现: {m}"
|
||||
),
|
||||
other => panic!("{name} 失败必须拒绝,得到 {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passing_self_test_allows_and_non_sm2_is_rejected() {
|
||||
let s = Fake { test: PASS, alg: "SM2" };
|
||||
assert!(require_self_test(&s).is_ok());
|
||||
let other = Fake { test: PASS, alg: "secp256k1" };
|
||||
assert!(require_self_test(&other).is_err());
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ mpc-tee = { workspace = true, features = ["std"] }
|
||||
# 宿主控制面(e2b 兼容 API + TeeRuntime)独立成 crate:mpc-tee 要被拷进
|
||||
# OP-TEE SDK 做 armv7 离线交叉编译,不能沾 crates.io 依赖。
|
||||
mpc-hostd = { path = "../mpc-hostd" }
|
||||
# 链上层形状:对象规范编码 / JSON-RPC / 幂等 outbox(本期无 FFI、无模组签名)
|
||||
mpc-chain = { path = "../mpc-chain" }
|
||||
mpc-node = { path = "../mpc-node" }
|
||||
mpc-orch = { path = "../mpc-orch" }
|
||||
# 计算域(明文/密态)抽象:selftest 里验证「同一份表达式两域同结果」。
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
//! `mpc chain` —— 链上层(阶段 2 形状层)命令行。
|
||||
//!
|
||||
//! # 诚实边界(写在使用说明前面)
|
||||
//!
|
||||
//! `flush` 发出去的 payload 是**链上对象的规范字节**,不是已签名的
|
||||
//! FISCO 交易。SM2 签名 / RLP 编码 / 国密模组 provider 都还没落地
|
||||
//! (见 `mpc_chain::signer`)。所以这一层能验证的是「幂等、补链、
|
||||
//! fail-open/fail-closed 分离、JSON-RPC 判定」这些**框架自己的契约**,
|
||||
//! 不是「能上链」。桩自测也只判这些。
|
||||
|
||||
use mpc_chain::admission::{chain_admit, MemberCache};
|
||||
use mpc_chain::objects::{
|
||||
object_digest, ChainObject, ComputeOrder, Member, PolicyBundleRecord, Receipt,
|
||||
};
|
||||
use mpc_chain::outbox::{EnqueueOutcome, Outbox};
|
||||
use mpc_chain::rpc::{ChainClient, HttpChainClient};
|
||||
use mpc_chain::{to_hex, ChainConfig};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
|
||||
pub fn cmd_chain(args: &[String]) -> Result<(), String> {
|
||||
match args.first().map(String::as_str) {
|
||||
Some("digest") => cmd_digest(&args[1..]),
|
||||
Some("submit") => cmd_submit(&args[1..]),
|
||||
Some("flush") => cmd_flush(&args[1..]),
|
||||
Some("status") => cmd_status(&args[1..]),
|
||||
Some("admit") => cmd_admit(&args[1..]),
|
||||
_ => Err(CHAIN_USAGE.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
const CHAIN_USAGE: &str = "用法:
|
||||
mpc chain digest 算链上对象的规范字节与 SM3 摘要
|
||||
--config PATH --kind member|order|receipt|bundle --file PATH
|
||||
mpc chain submit 把回执写进 outbox(fail-open:链挂也照常入队)
|
||||
--config PATH --outbox PATH --file PATH (Receipt JSON)
|
||||
mpc chain flush 补链:把 Pending 条目发给 bcos-rpc,幂等
|
||||
--config PATH --outbox PATH
|
||||
mpc chain status 从 outbox 回读条目状态 --outbox PATH
|
||||
mpc chain admit 链读侧准入(fail-closed)
|
||||
--cache PATH --now N --site NAME --participants A,B
|
||||
|
||||
所有命令的未知参数直接报错,不静默忽略。
|
||||
★ 本期 payload 是规范字节,不是已签名交易;真机需 ModuleSigner + RLP。";
|
||||
|
||||
fn opts(args: &[String], allowed: &[&str]) -> Result<HashMap<String, String>, String> {
|
||||
let mut m = HashMap::new();
|
||||
let mut i = 0usize;
|
||||
while i < args.len() {
|
||||
let k = &args[i];
|
||||
if !k.starts_with("--") || !allowed.contains(&k.as_str()) {
|
||||
return Err(format!("未知参数 {k}(允许: {})", allowed.join(" ")));
|
||||
}
|
||||
let v = args
|
||||
.get(i + 1)
|
||||
.ok_or_else(|| format!("{k} 缺少取值"))?;
|
||||
if m.insert(k.clone(), v.clone()).is_some() {
|
||||
return Err(format!("{k} 重复给出"));
|
||||
}
|
||||
i += 2;
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
fn req<'a>(m: &'a HashMap<String, String>, key: &str) -> Result<&'a str, String> {
|
||||
m.get(key)
|
||||
.map(String::as_str)
|
||||
.ok_or_else(|| format!("缺少必填参数 {key}"))
|
||||
}
|
||||
|
||||
fn read(path: &str) -> Result<String, String> {
|
||||
fs::read_to_string(path).map_err(|e| format!("读 {path} 失败: {e}"))
|
||||
}
|
||||
|
||||
fn config(path: &str) -> Result<ChainConfig, String> {
|
||||
ChainConfig::from_json(&read(path)?).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn esc(s: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if c.is_control() => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn parse_object(kind: &str, text: &str) -> Result<Box<dyn ChainObject>, String> {
|
||||
let b: Box<dyn ChainObject> = match kind {
|
||||
"member" => Box::new(Member::from_json(text).map_err(|e| e.to_string())?),
|
||||
"order" => Box::new(ComputeOrder::from_json(text).map_err(|e| e.to_string())?),
|
||||
"receipt" => Box::new(Receipt::from_json(text).map_err(|e| e.to_string())?),
|
||||
"bundle" => Box::new(PolicyBundleRecord::from_json(text).map_err(|e| e.to_string())?),
|
||||
_ => return Err(format!("不认识的 --kind: {kind}")),
|
||||
};
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
fn cmd_digest(args: &[String]) -> Result<(), String> {
|
||||
let o = opts(args, &["--config", "--kind", "--file"])?;
|
||||
let cfg = config(req(&o, "--config")?)?;
|
||||
let kind = req(&o, "--kind")?;
|
||||
let obj = parse_object(kind, &read(req(&o, "--file")?)?)?;
|
||||
let bytes = obj.canonical_bytes();
|
||||
let digest = object_digest(&cfg, obj.as_ref()).map_err(|e| e.to_string())?;
|
||||
println!(
|
||||
"{{\"kind\":\"{}\",\"hashSuite\":\"{}\",\"digest\":\"{}\",\"canonicalHex\":\"{}\",\"canonicalBytes\":{}}}",
|
||||
esc(kind),
|
||||
esc(cfg.hash_suite()),
|
||||
to_hex(&digest),
|
||||
to_hex(&bytes),
|
||||
bytes.len()
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_submit(args: &[String]) -> Result<(), String> {
|
||||
let o = opts(args, &["--config", "--outbox", "--file"])?;
|
||||
let cfg = config(req(&o, "--config")?)?;
|
||||
let receipt = Receipt::from_json(&read(req(&o, "--file")?)?).map_err(|e| e.to_string())?;
|
||||
let bytes = receipt.canonical_bytes();
|
||||
let mut boxed = Outbox::open(req(&o, "--outbox")?).map_err(|e| e.to_string())?;
|
||||
let outcome = boxed
|
||||
.enqueue("receipt", &receipt.order_id, &receipt.decision_id, &bytes)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let tag = match outcome {
|
||||
EnqueueOutcome::Added => "added",
|
||||
EnqueueOutcome::AlreadyPresent => "already_present",
|
||||
};
|
||||
println!(
|
||||
"{{\"outcome\":\"{}\",\"key\":\"receipt:{}:{}\",\"pending\":{},\"hashSuite\":\"{}\"}}",
|
||||
tag,
|
||||
esc(&receipt.order_id),
|
||||
esc(&receipt.decision_id),
|
||||
boxed.pending_count(),
|
||||
esc(cfg.hash_suite())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_flush(args: &[String]) -> Result<(), String> {
|
||||
let o = opts(args, &["--config", "--outbox"])?;
|
||||
let cfg = config(req(&o, "--config")?)?;
|
||||
let client = HttpChainClient::new(&cfg.rpc_endpoint).map_err(|e| e.to_string())?;
|
||||
let mut boxed = Outbox::open(req(&o, "--outbox")?).map_err(|e| e.to_string())?;
|
||||
eprintln!(
|
||||
"注意: 本期 flush 的 payload 是链上对象规范字节,不是已签名交易(SM2/RLP/模组未落地);\
|
||||
此处只验证补链与幂等契约。"
|
||||
);
|
||||
let report = boxed
|
||||
.flush_with(|entry| {
|
||||
// 真机这里应该是 ModuleSigner 签名 + RLP 编码后的裸交易。
|
||||
client
|
||||
.send_raw_transaction(&format!("0x{}", entry.payload_hex))
|
||||
.map(|_| ())
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
let failed: Vec<String> = report
|
||||
.failed
|
||||
.iter()
|
||||
.map(|(k, why)| format!("[\"{}\",\"{}\"]", esc(k), esc(why)))
|
||||
.collect();
|
||||
println!(
|
||||
"{{\"attempted\":{},\"confirmed\":{},\"failed\":[{}],\"remaining\":{},\"method\":\"{}\"}}",
|
||||
report.attempted,
|
||||
report.confirmed,
|
||||
failed.join(","),
|
||||
report.remaining,
|
||||
esc(mpc_chain::rpc::METHOD_SEND_RAW_TX)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_status(args: &[String]) -> Result<(), String> {
|
||||
let o = opts(args, &["--outbox"])?;
|
||||
let boxed = Outbox::open(req(&o, "--outbox")?).map_err(|e| e.to_string())?;
|
||||
let items: Vec<String> = boxed
|
||||
.entries()
|
||||
.iter()
|
||||
.map(|e| {
|
||||
format!(
|
||||
"{{\"key\":\"{}\",\"state\":\"{:?}\",\"attempts\":{},\"payloadBytes\":{},\"lastError\":{}}}",
|
||||
esc(&e.key),
|
||||
e.state,
|
||||
e.attempts,
|
||||
e.payload_hex.len() / 2,
|
||||
e.last_error
|
||||
.as_deref()
|
||||
.map(|s| format!("\"{}\"", esc(s)))
|
||||
.unwrap_or_else(|| String::from("null"))
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
println!("{{\"entries\":[{}],\"pending\":{}}}", items.join(","), boxed.pending_count());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn cmd_admit(args: &[String]) -> Result<(), String> {
|
||||
let o = opts(args, &["--cache", "--now", "--site", "--participants"])?;
|
||||
let cache = MemberCache::from_json(&read(req(&o, "--cache")?)?).map_err(|e| e.to_string())?;
|
||||
let now: u64 = req(&o, "--now")?
|
||||
.parse()
|
||||
.map_err(|_| String::from("--now 必须是非负整数"))?;
|
||||
let site = req(&o, "--site")?;
|
||||
let participants: Vec<String> = req(&o, "--participants")?
|
||||
.split(',')
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(String::from)
|
||||
.collect();
|
||||
chain_admit(Some(&cache), now, site, &participants).map_err(|e| e.to_string())?;
|
||||
println!("{{\"decision\":\"allow\",\"site\":\"{}\",\"participants\":{}}}", esc(site), participants.len());
|
||||
Ok(())
|
||||
}
|
||||
@@ -43,6 +43,7 @@ mod sql_demo;
|
||||
mod sql_join;
|
||||
mod hostd;
|
||||
mod link;
|
||||
mod chain;
|
||||
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
@@ -67,6 +68,7 @@ fn main() -> ExitCode {
|
||||
"tee" => cmd_tee(&args[1..]),
|
||||
"hostd" => hostd::cmd_hostd(&args[1..]),
|
||||
"link" => link::cmd_link(&args[1..]),
|
||||
"chain" => chain::cmd_chain(&args[1..]),
|
||||
"plan" => cmd_plan(&args[1..]),
|
||||
"node" => cmd_node(&args[1..]),
|
||||
"cluster" => cmd_cluster(&args[1..]),
|
||||
@@ -124,6 +126,9 @@ fn usage() {
|
||||
mpc link plan|verdict|credential
|
||||
会话级链路:生成 EasyTier argv / 判实际路径 / 签发撤销凭据
|
||||
(与 e2b 兼容面独立;长驻进程由部署层 exec,不归框架托管)
|
||||
mpc chain digest|submit|flush|status|admit
|
||||
链上层形状:对象摘要 / 幂等 outbox / 补链 / fail-closed 准入
|
||||
(★ 本期 payload 是规范字节,不是已签名交易;SM2/RLP/模组未落地)
|
||||
mpc plan 把纵向 LR 梯度图编译成执行计划,报出交互轮数(不联网)
|
||||
mpc node 启动一方节点,与对端跑一次密文会话
|
||||
mpc psi 启动一方节点,与其余方做一次隐私求交(n 方 ECDH-PSI)
|
||||
|
||||
@@ -28,9 +28,10 @@ pub const CATALOG: &str = r#"【ssw-mpc 平台真实 API 清单 —— 只能用
|
||||
|
||||
待审/待生成的代码是 **Rust**(crate 名统一 `mpc-` 前缀),不是 Python。
|
||||
不要按 Python 的 import / 函数调用习惯理解,也不要引入清单外的第三方 crate
|
||||
(没有 serde_json、没有 sha2、没有 rand、没有 reqwest —— 这些都不在依赖里)。
|
||||
需要哈希用 `mpc_core::hash::sha256`,需要随机数用 `mpc_core::prg::Stream` 或
|
||||
`mpc_core::osrand::fill_random`。
|
||||
(没有 sha2、没有 rand;`serde_json` / `reqwest` 只在 `mpc-hostd` / `mpc-chain` 可用,
|
||||
**核心计算层 mpc-core / mpc-tee 仍是零第三方依赖**,生成核心代码不得引用)。
|
||||
需要哈希用 `mpc_core::hash::sha256`(国密链对象用 `mpc_core::sm3::sm3`),
|
||||
需要随机数用 `mpc_core::prg::Stream` 或 `mpc_core::osrand::fill_random`。
|
||||
|
||||
# 密态算子会话(mpc-vault)
|
||||
use mpc_vault::{Pipe, MeshPipe, Vault};
|
||||
@@ -189,6 +190,27 @@ let verdict = link_admit(policy, &obs, &whitelist, &cred, &user_data_first32, no
|
||||
#[cfg(feature = "std")] use mpc_hostd::link::{EasyTierSpec, CliCredentialIssuer, LinkRuntime, parse_peer_output};
|
||||
let argv = spec.argv()?; // **绝不产 --network-secret**(临时节点不接触联盟主密码)
|
||||
|
||||
# 链上层(mpc-chain,std only;★ 本期是形状层,不含真实交易签名,不宣称能上链)
|
||||
use mpc_chain::{ChainConfig, ChainError, digest_for_config, to_hex, from_hex};
|
||||
use mpc_chain::objects::{ChainObject, Member, ComputeOrder, Receipt, PolicyBundleRecord, AttestFlags, object_digest, push_field};
|
||||
let cfg = ChainConfig::from_json(text)?; // 5 字段必须显式;**sm_crypto=false 即拒**(链下无 keccak256)
|
||||
let bytes = obj.canonical_bytes(); // 唯一实现:域分隔 TEE_CHAIN_OBJECT + 类型标签 + 4 字节大端长度前缀
|
||||
let digest = object_digest(&cfg, obj.as_ref())?; // 2 参;**全框架唯一 hash 入口**(SM3)
|
||||
# ★ Receipt 四布尔分开(不许有 ok);签名不进被签内容(否则自指)。
|
||||
use mpc_chain::rpc::{ChainClient, HttpChainClient, parse_response, request_json, METHOD_SEND_RAW_TX, METHOD_GET_RECEIPT, METHOD_CALL};
|
||||
# ★ 3.x 是 eth_ 兼容端点(EthMethods.h);HTTP 200 + error 字段 = 失败;result:null ≠ 成功;先判 error 再判 result。
|
||||
let client = HttpChainClient::new("127.0.0.1:20200")?; // .no_proxy():系统代理不许换掉这一跳的端点
|
||||
use mpc_chain::outbox::{Outbox, OutboxEntry, OutboxState, EnqueueOutcome, FlushReport};
|
||||
let mut boxed = Outbox::open(path)?;
|
||||
let outcome = boxed.enqueue(kind, order_id, decision_id, &bytes)?; // 4 参;**fail-open**,链挂照入队;同键不新增不覆盖
|
||||
let report = boxed.flush_with(|e| client.send_raw_transaction(&format!("0x{}", e.payload_hex)).map(|_| ()))?;
|
||||
# ★ 存证 fail-open + outbox 幂等;成员/硬规则准入 fail-closed。**两侧不许混**。
|
||||
use mpc_chain::admission::{MemberCache, chain_admit};
|
||||
let cache = MemberCache::from_json(text)?;
|
||||
chain_admit(Some(&cache), now, site, &participants)?; // 4 参;缓存缺失 / 过期即拒
|
||||
use mpc_chain::signer::{Signer, SignerSelfTest, require_signer, require_self_test};
|
||||
let signer = require_signer(Some(&s))?; // **未配置签名器即拒绝**;ModuleSigner 本期未实现,不写软件签名器充数
|
||||
|
||||
# 零知识证明(mpc-zkp)
|
||||
use mpc_zkp::{keygen, schnorr_prove, schnorr_verify, pedersen_commit, prove_opening};
|
||||
|
||||
@@ -505,6 +527,50 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// 链上层的 API 必须与源码逐字对应,且必须写明形状层的诚实边界。
|
||||
///
|
||||
/// 这一层最容易被「照着想象写」:把 3.x 当成 2.x 的自有 RPC、把
|
||||
/// HTTP 200 当成成功、把存证 fail-open 与准入 fail-closed 混用、
|
||||
/// 或者以为 `flush` 已经能签出真实国密交易。每写错一条,模型都会
|
||||
/// 照抄出一个能编译但语义错的调用。
|
||||
#[test]
|
||||
fn catalog_documents_chain_layer_apis() {
|
||||
for key in [
|
||||
"use mpc_chain::{ChainConfig, ChainError, digest_for_config, to_hex, from_hex}",
|
||||
"use mpc_chain::objects::{ChainObject, Member, ComputeOrder, Receipt, PolicyBundleRecord, AttestFlags, object_digest, push_field}",
|
||||
"ChainConfig::from_json(text)?",
|
||||
"object_digest(&cfg, obj.as_ref())?",
|
||||
"use mpc_chain::rpc::{ChainClient, HttpChainClient, parse_response, request_json, METHOD_SEND_RAW_TX, METHOD_GET_RECEIPT, METHOD_CALL}",
|
||||
"HttpChainClient::new(\"127.0.0.1:20200\")?",
|
||||
"boxed.enqueue(kind, order_id, decision_id, &bytes)?",
|
||||
"boxed.flush_with(|e| client.send_raw_transaction(&format!(\"0x{}\", e.payload_hex)).map(|_| ()))?",
|
||||
"chain_admit(Some(&cache), now, site, &participants)?",
|
||||
"require_signer(Some(&s))?",
|
||||
] {
|
||||
assert!(CATALOG.contains(key), "清单缺少真实链上层签名:{key}");
|
||||
}
|
||||
assert!(
|
||||
CATALOG.contains("sm_crypto=false 即拒"),
|
||||
"必须写明非国密链本期拒绝(链下无 keccak256),否则会放行一个摘要永远对不上的假绿"
|
||||
);
|
||||
assert!(
|
||||
CATALOG.contains("HTTP 200 + error 字段 = 失败"),
|
||||
"必须写明 JSON-RPC 的失败形态,否则会把交易被拒当成已上链"
|
||||
);
|
||||
assert!(
|
||||
CATALOG.contains("fail-open") && CATALOG.contains("fail-closed"),
|
||||
"必须写明存证与准入两侧策略相反,否则会被混用"
|
||||
);
|
||||
assert!(
|
||||
CATALOG.contains("3.x 是 eth_ 兼容端点"),
|
||||
"必须写明 RPC 方法名来自 3.x 源码,否则会照 2.x 老结论写 sendTransaction"
|
||||
);
|
||||
assert!(
|
||||
CATALOG.contains("未配置签名器即拒绝") && CATALOG.contains("不宣称能上链"),
|
||||
"必须写明形状层边界,否则会以为已经能签真实交易"
|
||||
);
|
||||
}
|
||||
|
||||
/// 方向钉子:框架层不许回到容器编排路线。
|
||||
#[test]
|
||||
fn catalog_never_offers_container_orchestration_apis() {
|
||||
|
||||
@@ -146,3 +146,10 @@ pub const TEE_SITE_POLICY: &[u8] = b"mpc/tee/site/policy/v1";
|
||||
///
|
||||
/// 改这个标签 = 已登记的绑定摘要全部对不上,参与方必须同步升级。
|
||||
pub const TEE_LINK_BIND: &[u8] = b"mpc/tee/link/bind/v1";
|
||||
|
||||
/// 链上对象规范编码的域分隔标签(`Member` / `ComputeOrder` / `Receipt` /
|
||||
/// `PolicyBundleRecord` 共用前缀,各自再带类型标签,见 `mpc_chain::objects`)。
|
||||
///
|
||||
/// 这份字节序列就是签名对象与 SM3 摘要的输入:站点端、宿主端、验证方
|
||||
/// 必须算出同一串。改一个字节 = 已上链的摘要全部对不上,参与方必须同步升级。
|
||||
pub const TEE_CHAIN_OBJECT: &[u8] = b"mpc/tee/chain/object/v1";
|
||||
@@ -165,7 +165,7 @@ DELETE /sandboxes/{id} VM → kill + reaper 确认
|
||||
**为什么必须独立(这是约束,不是偏好)**
|
||||
|
||||
- `build/build_optee.sh` 的必需环境是 `OPTEE_OS`(已构建的 optee_os 源码树)+ `SDK_DIR`(teaclave-trustzone-sdk)+ `arm-linux-gnueabihf-` 交叉工具链 + 固定 nightly。主门禁机器上不可能齐备。
|
||||
- 主门禁的形态与它冲突:十三条里有"跨目标 x86_64-musl 零告警""12 示例冒烟",而 OP-TEE 的产物是 armv7 的**已签名 `.ta`**,签名和 verify 都要过 `sign_encrypt.py`。混进去会让所有人的本地 `ci.sh` 变红。
|
||||
- 主门禁的形态与它冲突:十四条里有"跨目标 x86_64-musl 零告警""12 示例冒烟",而 OP-TEE 的产物是 armv7 的**已签名 `.ta`**,签名和 verify 都要过 `sign_encrypt.py`。混进去会让所有人的本地 `ci.sh` 变红。
|
||||
|
||||
**段一:进主门禁的部分(零 SDK 依赖)**
|
||||
|
||||
@@ -611,15 +611,29 @@ OPA 的位置不变:跑在 guest 内,decision 落 `Receipt`。三条硬要
|
||||
|
||||
outbox 必须**幂等**:同一 `order_id` + 同一 `decision_id` 重复提交不产生两条记录,否则补链会写出重复账。`decision_id` 的确定性正好当幂等键。
|
||||
|
||||
### 4.8 mpc-chain 接入形态
|
||||
### 4.8 mpc-chain 接入形态 —— [修正] 3.x 有 `eth_` 兼容端点
|
||||
|
||||
- 新建 `crates/mpc-chain`(`std` only):JSON-RPC over HTTP + RLP + SM2/SM3 签名
|
||||
- 新建 `crates/mpc-chain`(`std` only):本期落**形状层**(对象规范编码 + SM3 摘要 + JSON-RPC 最小面 + 幂等 outbox + fail-closed 准入);RLP / SM2 交易签名**待模组**
|
||||
- **不进 `mpc-core`**(零依赖、no_std),**不进 `mpc-tee`**(TA 侧要 no_std)
|
||||
- **链交互在宿主,不在 guest**:SM2 是全新 crypto 依赖,塞进 TEE 会同时扩大 TCB 和破坏"零依赖"叙事。guest 只产出证明、decision 与结果 hash
|
||||
|
||||
FISCO 3.x 的接入面是**自有 JSON-RPC**(`sendTransaction` / `call` / `getTransactionReceipt`),不是 `eth_` 兼容。Rust 侧没有官方 SDK。**先做最小面**:两个方法(发交易、查回执)就够跑通存证闭环。
|
||||
**[修正]** 初稿写「3.x 接入面是自有 JSON-RPC(`sendTransaction` / `call` / `getTransactionReceipt`),不是 `eth_` 兼容」—— 用 gitea 镜像核对 `FISCO-BCOS/FISCO-BCOS` 源码后,这是 **2.x 的老结论**:
|
||||
|
||||
**一个待确认的阻塞项**:国密 SSL 双证书用在节点间与 Gateway 之间,**客户端到 `bcos-rpc` 这一跳是否也要求国密 TLS,官方文档没有明确说法,必须实测**。如果要求,Rust 侧会被卡住——`rustls` 不支持 TLCP(GB/T 38636),只能引 Tongsuo/BabaSSL 做旁路(多一个运行时 + FFI 边界)。**这条要在建链前问清楚,不能等联调。**
|
||||
- (以下为**上游 FISCO-BCOS 仓库**路径)`bcos-rpc/bcos-rpc/web3jsonrpc/endpoints/EthMethods.h` 的 `EthMethod` 枚举明确列出 `eth_sendRawTransaction`、`eth_call`、`eth_getTransactionReceipt`、`eth_blockNumber` 等;`EndpointsMapping.cpp` 按 `methodString(EthMethod::...)` 注册 handler。
|
||||
- `sendTransaction` 全仓搜不到。Rust 侧仍没有官方 SDK,所以只做**最小面**:发交易、查回执、call 三个方法。
|
||||
- 本期 `mpc_chain::rpc` 的三个方法常量按 `eth_*` 写,并同时钉在单测与桩自测里(防止有人照旧文档改回去)。
|
||||
|
||||
**★ 方法名兼容 ≠ 交易结构兼容**:`sm_crypto=true` 时交易是 SM2 签名 + FISCO 自有 RLP,web3 端点是否接受国密交易**尚未实测**(写进第 7 节)。方法名只解决「怎么调」,没解决「发什么」。
|
||||
|
||||
**本期形状层的诚实边界**:`mpc chain flush` 发出去的 payload 是**链上对象的规范字节**,不是已签名交易。它验证的是幂等 / 补链 / fail-open 与 fail-closed 分离 / JSON-RPC 判定这些框架自己的契约,**不宣称能上链**。模组到位后要让 `ModuleSigner` + RLP 编码接进 `flush`,并补一笔真机交易对拍。
|
||||
|
||||
**★ 三条配置纪律(把待拍板项做成显式拒绝,而不是隐式假设)**:
|
||||
① `sm_crypto` 必须显式给、`false` 直接拒(标准版链上用 `keccak256Hash`,链下没有 keccak256 实现,放行等于「摘要永远对不上」的假绿);
|
||||
② `client_tlcp=true` 直接拒(Rust 侧 TLCP 未实现);③ 未配置 `Signer` 即拒绝,`ModuleSigner` 只留 trait 与启动自检三件的形状 —— **不写软件签名器充数**(`sm2` crate 未经独立审计,进生产等于把「密评可过」悄悄作废)。
|
||||
|
||||
**★ `HttpChainClient` 显式 `.no_proxy()`**:控制面只连配置里的 `host:port`。系统代理会把这一跳的端点换掉 —— 桩测试里表现为回环端口被代理接走后返回 502(而不是 Connection refused),生产里会让「客户端到 `bcos-rpc` 是否需要国密 TLS」的实测结论整个失效(TLS 终止点变了)。门禁第 14 条有专门回归探针。
|
||||
|
||||
**仍待确认的阻塞项**:国密 SSL 双证书用在节点间与 Gateway 之间,**客户端到 `bcos-rpc` 这一跳是否也要求国密 TLS,官方文档没有明确说法,必须实测**(配置里 `client_tlcp` 必须显式给,`true` 本期直接拒)。如果要求,Rust 侧会被卡住——`rustls` 不支持 TLCP(GB/T 38636),只能引 Tongsuo/BabaSSL 做旁路(多一个运行时 + FFI 边界)。**这条要在建链前问清楚,不能等联调。**
|
||||
|
||||
### 4.9 不要重复 WeDPR
|
||||
|
||||
@@ -666,11 +680,11 @@ FISCO 3.x 的接入面是**自有 JSON-RPC**(`sendTransaction` / `call` / `get
|
||||
| **0a** | 拆两层:`mpc-hostd`(e2b 兼容)+ `TeeRuntime` + `/attestation` + 站点侧 `session_admit` | 中(**axum + tokio + reqwest**,只在独立 `mpc-hostd` crate) | 中(协议设计、token 信任链) | — |
|
||||
| **0b** | OP-TEE 独立通道:`tools/ci-optee.sh` + 五条验证规则 + `ta_admit` | 零(复用 `build/build_optee.sh`) | 低(不碰主链路) | — |
|
||||
| **1** | 链路:EasyTier 进程化 + 三档 `--link-policy` + credential + `link` 上报 | 零(外部二进制) | 中(LGPL 合规、TUN 权限、relay 可见性) | 0a |
|
||||
| **2** | `mpc-chain`:Pro 版建链(国密)+ `Member`/`ComputeOrder`/`Receipt` 存证 + outbox | 高(FFI + 国密模组 + RLP + HTTP client) | 高(国密不可逆、模组 distid、CSV 验签待实测) | 0a |
|
||||
| **2** | `mpc-chain`:**形状层已完成**(对象规范编码 + JSON-RPC + 幂等 outbox + 准入);真链建链 / SM2 签名 / RLP 仍待模组 | 中(`serde_json` + `reqwest`,仅 `mpc-chain`;**FFI 未落地**) | 高(国密不可逆、模组 distid、CSV 验签待实测) | 0a |
|
||||
| **3** | 策略:OPA 进 guest + 控制面签发 bundle + decision 上链 | 中(OPA 二进制 + bundle 分发) | 高(bundle 灰度与撤销、TCB 边界) | 2 |
|
||||
| ~~4~~ | ~~Rego→WASM 上链~~ | — | — | **删除(决策 6)** |
|
||||
|
||||
**阶段状态(2026-11-07)**:**0a 已完成并进主门禁**(第 12 条)、**1 已完成并进主门禁**(第 13 条);0b 的编排与判据已实现、**QEMU 实跑待有 SDK 的机器**;2/3 未开工。
|
||||
**阶段状态(2026-11-07)**:**0a 已完成**(第 12 条)、**1 已完成**(第 13 条)、**2 形状层已完成**(第 14 条);0b 的编排与判据已实现、**QEMU 实跑待有 SDK 的机器**;3 未开工。**阶段 2 的「形状层」不含真实交易签名** —— SM2 / RLP / 国密模组 provider 未落地,见 4.8。
|
||||
|
||||
**为什么 0a 必须第一**:后三件都要"可编排的对象"。没有 `TeeRuntime` 和 e2b 接口,"给这个会话签 credential""把这轮登记上链"都没有承载点。
|
||||
|
||||
@@ -702,6 +716,21 @@ CLI `crates/mpc-cli/src/link.rs`(`mpc link plan|verdict|credential`)。
|
||||
|
||||
**没换的部分**:`json.rs`(自研 JSON 编解码)保留。它不是 HTTP 层,且被 `TeeRuntime` 的状态落盘复用;换它要动 1500 行运行时代码,风险大于收益。若要彻底替换,应作为独立一轮做,并保留「键有序 + 状态文件可回读」的回归测试。
|
||||
|
||||
**阶段 2 形状层落地(2026-11-07)**:新建独立 crate `crates/mpc-chain`(`serde_json` + `reqwest`,**零 FFI**),
|
||||
模块:`objects`(`ChainObject::canonical_bytes` 唯一实现,域分隔 `TEE_CHAIN_OBJECT` + 类型标签 + 4 字节大端长度前缀,
|
||||
`Receipt` 四布尔分开、签名不进被签内容)、`rpc`(3.x `eth_*` 方法、HTTP 200 + `error` 判失败、`result:null` 不算成功、
|
||||
`.no_proxy()`)、`outbox`(复合幂等键、fail-open、坏行拒绝、临时文件 + rename 落盘)、`admission`(fail-closed、
|
||||
`expires_at` 过期即拒)、`signer`(trait 形状 + 自检三件,**未实现**)。
|
||||
CLI `mpc chain digest|submit|flush|status|admit`;`tools/selftest-chain.py` **44 条判据进主门禁第 14 条**,
|
||||
用 Python 假 `bcos-rpc` 跑完整链路(本机无 FISCO 节点与国密模组)。
|
||||
|
||||
**★ fail-open 与 fail-closed 不许混**:链是审计锚(存证侧链挂照算、条目入队等补链),
|
||||
成员资格与硬规则是安全前提(缓存缺失 / 过期 / 非成员一律拒绝)。两侧各写一份,绝不互相借用策略。
|
||||
|
||||
**★ 本期抓到并修掉的两个真问题**:① reqwest 默认跟随系统代理,链挂时返回代理的 502
|
||||
而不是「连不上 bcos-rpc」—— 显式 `.no_proxy()` + 回归探针;② JSON-RPC 的失败走 HTTP 200
|
||||
响应体里的 `error` 字段,`parse_response` 必须**先判 error 再判 result**,顺序反了就是假绿。
|
||||
|
||||
门禁见 `tools/selftest-hostd.py`(主门禁第 12 条,33 条判据),其中新增「连续 20 次请求都拿到完整响应体」——这条就是钉死上述偶发失败的回归探针。
|
||||
|
||||
**为什么 1 可以紧跟 0a**:改动面在 `mpc-node` 之外(地址列表 + 编排层),与 0a 不冲突。
|
||||
@@ -740,6 +769,12 @@ CLI `crates/mpc-cli/src/link.rs`(`mpc link plan|verdict|credential`)。
|
||||
`peer` 只给 `p2p`/`relay`,不报经的是哪个中继网,所以 `allowlist` 档目前靠
|
||||
`--relay-network` 的宿主**配置声明**核对,真机要补 RPC / `route` 观测后才能算
|
||||
「实际路径已核对」。`p2p-only` 档不受影响(见 relay 即拒)。
|
||||
9c. **FISCO 真机必须补的三处对拍**(本期用桩 + 形状层,别拿"本机没链"当通过):
|
||||
① `sm_crypto=true` 的国密交易是否走 web3 端点(`eth_sendRawTransaction`)—— 方法名兼容
|
||||
不等于 RLP / SM2 签名结构兼容;② 客户端到 `bcos-rpc` 是否要求国密 TLCP;
|
||||
③ `CryptoPrecompiled.sm2Verify` 的三个入参(CSV 公钥编码 / message 是 hash 还是原文 /
|
||||
distid),见 4.4。**另外**:模组到位后要让 `flush` 发出去的是**已签名交易**
|
||||
而非规范字节,并补一笔真机交易对拍。
|
||||
10. **OP-TEE 在 TA 共享语义下的租户隔离**。TA 是设备级单例,多机构共存时密钥域怎么分——`optee/core.rs` 的 seal 格式是否已带租户维度,要核对。**这条现在是生效的**(OP-TEE 已进本轮,见 1.7)。
|
||||
|
||||
**已有建议,等你拍**
|
||||
@@ -767,14 +802,22 @@ CLI `crates/mpc-cli/src/link.rs`(`mpc link plan|verdict|credential`)。
|
||||
- `crates/mpc-hostd/src/link.rs`(**链路进程层**:`EasyTierSpec::argv()` 三档参数 + 被禁 flag 自检(`--network-secret` / `--relay-all-peer-rpc` / `--disable-encryption` / `-u`);RPC portal 只绑回环;`CliCredentialIssuer` 调 `credential generate|revoke`;`parse_peer_output` 认不出一律 `Unknown`;`LinkRuntime` 持 `Child` 句柄 + `try_wait()` 收割)
|
||||
- `crates/mpc-cli/src/link.rs`(`mpc link plan|verdict|credential`;凭据只走 0600 文件、不进命令行;`--argv` 输出真实 argv 并警告,`--argv-redacted` 输出**合法 JSON** 脱敏版;未知参数直接报错,不静默忽略)
|
||||
- `tools/selftest-link.py`(**进主门禁第 13 条**;53 条判据,用 fake-easytier-cli / fake-easytier-core 两个桩跑完整链路;**每条负向带期望特征**;含「混合 peer 假绿」「进程真回收」两条回归探针)
|
||||
- `crates/mpc-core/src/domain.rs`(`TEE_LINK_BIND` 域分隔常量;改一个字节 = 已登记的绑定摘要全部对不上)
|
||||
- `crates/mpc-chain/src/lib.rs`(`ChainConfig` 每字段必须显式、`sm_crypto=false` 拒绝并说明 keccak256 未实现、`client_tlcp=true` 拒绝;`digest_for_config` 是**全框架唯一** hash 入口)
|
||||
- `crates/mpc-chain/src/objects.rs`(`ChainObject::canonical_bytes` 唯一实现:域分隔 `TEE_CHAIN_OBJECT` + 类型标签 + 4 字节大端长度前缀;四类对象摘要;`Receipt` 四布尔分开、签名不进被签内容)
|
||||
- `crates/mpc-chain/src/rpc.rs`(3.x `eth_*` 方法常量;`parse_response` 先判 error 再判 result、缺 result 拒、id 不匹配拒、`result:null` 不算成功;`.no_proxy()`)
|
||||
- `crates/mpc-chain/src/outbox.rs`(`kind:order_id:decision_id` 复合幂等键、重复不覆盖、fail-open、坏行整体拒绝、临时文件 + rename)
|
||||
- `crates/mpc-chain/src/admission.rs`(fail-closed:缓存缺失 / 过期 / 硬规则失败 / 非成员一律拒;`expires_at` 缺失不当永不过期)
|
||||
- `crates/mpc-chain/src/signer.rs`(`Signer` trait 形状 + 启动自检三件;**`ModuleSigner` 未实现**,未配置即拒绝,不假装可用)
|
||||
- `crates/mpc-cli/src/chain.rs`(`mpc chain digest|submit|flush|status|admit`;**flush 输出明确标注 payload 不是已签名交易**)
|
||||
- `tools/selftest-chain.py`(**进主门禁第 14 条**;44 条判据,Python 假 `bcos-rpc`;每条负向带期望特征;含 `.no_proxy()` 回归探针)
|
||||
- `crates/mpc-core/src/domain.rs`(`TEE_LINK_BIND` / `TEE_CHAIN_OBJECT` 域分隔常量;改一个字节 = 已登记摘要全部对不上)
|
||||
- `crates/mpc-tee/src/session.rs:75`(`user_data` 两段 sha256 拆分)
|
||||
- `crates/mpc-tee/src/verify.rs:89`(`CSV_REPORT_LEN = 2548`,真机实测;注释明确 4096 是 hypercall 页不是报告长度)
|
||||
- `crates/mpc-tee/src/platform.rs`(`PlatformProfile::builtin()` 对 `Optee` / `Tdx` 返回 `None`,有断言钉死;本轮已把该文件开头误写的"CSV 4096 字节"改为 2548)
|
||||
- `crates/mpc-tee/src/optee/{mod,core,proto}.rs`(CA↔TA 三层范式、seal 格式、命令协议;`ta/`、`ca/` 需 OP-TEE SDK 交叉编译,`build/build_optee.sh` 驱动)
|
||||
- `build/build_optee.sh`(需要 `OPTEE_OS` + `SDK_DIR` + `arm-linux-gnueabihf-`;`UUID` 硬编码 `a1b2c3d4-…`;`SIGN_KEY` 留空即用开发密钥 `default_ta.pem`;`MPC_SIM_DEV` A/B 跨设备解封失败的机制已串进 `tools/optee-cross-device.sh`,但**QEMU 未实跑**)
|
||||
- `crates/mpc-tee/Cargo.toml`(**没有 `optee` feature**;TA 走 `default-features = false`,所以 `mpc-tee` 的 no_std 是 OP-TEE 的硬前置)
|
||||
- `tools/ci.sh`(**十三条**;第 3 条已从"mpc-core no_std"扩展为"mpc-core + mpc-tee no_std + TA UUID 对拍";第 4 条有"跳过:目标未安装"的既有语义,`ci-optee.sh` 的 skip 输出照此设计;**第 11 条 = OP-TEE 判据逻辑自测**,零 SDK 依赖;**第 12 条 = 宿主控制面端到端自测**;**第 13 条 = 会话级链路层端到端自测**,见下)
|
||||
- `tools/ci.sh`(**十四条**;第 3 条已从"mpc-core no_std"扩展为"mpc-core + mpc-tee no_std + TA UUID 对拍";第 4 条有"跳过:目标未安装"的既有语义,`ci-optee.sh` 的 skip 输出照此设计;**第 11 条 = OP-TEE 判据逻辑自测**,零 SDK 依赖;**第 12 条 = 宿主控制面端到端自测**;**第 13 条 = 会话级链路层端到端自测**;**第 14 条 = 链上层端到端自测**,见下)
|
||||
- `tools/check-optee-uuid.py`(五处 UUID 对拍,不写死期望值;已做探针回归——改一个字符即 `OPTE_UUID_FAIL` 并指出差异行)
|
||||
- `tools/ci-optee.sh`(段二独立通道。skip 分支已实测,构建分支待真 SDK;新增 `--cross-device` / `--restart` 两个互斥模式)
|
||||
- `build/optee-verdict.py`(**判据的唯一真相源**:按 mode / expect / provisioned / require-9p 判定串口日志,兼带 blob 抠取。判据散落多处 = 迟早分叉且分叉了没人知道)
|
||||
@@ -793,6 +836,7 @@ CLI `crates/mpc-cli/src/link.rs`(`mpc link plan|verdict|credential`)。
|
||||
- `bcos-executor/src/precompiled/CryptoPrecompiled.{h,cpp}`(`sm3` / `keccak256Hash` / `sm2Verify` 预编译;实现走 `sm2Recover` + `sm3Hash` 推地址)
|
||||
- `bcos-crypto/bcos-crypto/signature/sm2.{h,cpp}`
|
||||
- 官方文档:Pro 版部署(`deploy_pro_by_buildchain`、`installation_without_tars`、TARS 依赖)、`[chain] sm_crypto` 不可改、OPCODE 差异表(`KECCAK256` 国密版为 SM3、`CREATE2` 按 SM3 推导地址)
|
||||
- **gitea 镜像 `FISCO-BCOS/FISCO-BCOS` 源码核对(2026-11-07)**:下列路径均为**上游仓库**相对路径,不是 ssw-mpc 本仓库文件。`bcos-rpc/bcos-rpc/web3jsonrpc/endpoints/EthMethods.h` 的 `EthMethod` 枚举含 `eth_sendRawTransaction` / `eth_call` / `eth_getTransactionReceipt`;`EndpointsMapping.cpp` 按枚举注册;`sendTransaction` 全仓搜不到。`FISCO-BCOS/tools/BcosBuilder/pro/conf/config-build-example.toml` 有 `sm_crypto=false`(注释 "use sm-crypto or not");`bcos-tool/bcos-tool/NodeConfig.cpp:664` 从 `chain.sm_crypto` 读创世配置。`bcos-executor/src/precompiled/CryptoPrecompiled.cpp` 确认 `sm3(bytes)` / `keccak256Hash(bytes)` / `sm2Verify(bytes32,bytes,bytes32,bytes32)` 三个选择器。
|
||||
- `cmake/Options.cmake` 的 `WITH_WASM`(默认 OFF)——决策 6 后不再使用
|
||||
|
||||
**EasyTier**
|
||||
|
||||
+35
-14
@@ -32,6 +32,11 @@
|
||||
# 12. 会话级链路层必须端到端自测(三档 relay 判据、凭据只由管理节点签发、
|
||||
# argv 绝不分发 network_secret、所有 peer 取最严路径、进程真起真回收)。
|
||||
# 本机没有 EasyTier 二进制,用桩跑完整链路 —— 「没装」不等于判据可以跳过。
|
||||
# 13. 链上层形状必须端到端自测(对象规范编码 / 幂等 outbox /
|
||||
# fail-open 与 fail-closed 分开 / JSON-RPC 200+error 不当成功 /
|
||||
# 系统代理不能把这一跳的端点偷偷换掉)。
|
||||
# 本机没有 FISCO 节点与国密模组,用桩跑完整链路;
|
||||
# ★ 不宣称能上链 —— flush 发的是规范字节,不是已签名交易。
|
||||
#
|
||||
# 用法:tools/ci.sh 正常跑
|
||||
# tools/ci.sh --fast 跳过测试与示例,只编译(改完想快速确认能编过时用)
|
||||
@@ -52,19 +57,19 @@ step() { printf '\n\033[1m== %s ==\033[0m\n' "$1"; }
|
||||
ok() { printf '\033[32m ok\033[0m\n'; }
|
||||
|
||||
if [ "$FAST" -eq 0 ]; then
|
||||
step "1/13 全量测试(含 secure 特性)"
|
||||
step "1/14 全量测试(含 secure 特性)"
|
||||
cargo test --workspace --features secure
|
||||
ok
|
||||
fi
|
||||
|
||||
step "2/13 零告警构建(所有目标)"
|
||||
step "2/14 零告警构建(所有目标)"
|
||||
# -Dwarnings 同时作用于本地 crate 的 test / bench / example 目标,
|
||||
# 所以「测试代码里有 unused」也会被拦下 —— 这正是想要的。
|
||||
RUSTFLAGS="${RUSTFLAGS:+${RUSTFLAGS} }-Dwarnings" \
|
||||
cargo build --workspace --all-targets --features secure
|
||||
ok
|
||||
|
||||
step "3/13 no_std 守线 + TA 常量对拍(mpc-core + mpc-tee)"
|
||||
step "3/14 no_std 守线 + TA 常量对拍(mpc-core + mpc-tee)"
|
||||
# 两条 no_std 都要守:
|
||||
# mpc-core —— TEE / armv7 那条路的底座
|
||||
# mpc-tee —— OP-TEE 的 TA 就是 default-features = false 构建的
|
||||
@@ -93,17 +98,17 @@ ok
|
||||
# 交叉编译不依赖外部 gcc(rustc 自带 rust-lld + musl crt)。
|
||||
CROSS_TARGET=x86_64-unknown-linux-musl
|
||||
if rustup target list --installed 2>/dev/null | grep -qx "$CROSS_TARGET"; then
|
||||
step "4/13 跨目标编译(${CROSS_TARGET},guest 用的静态产物)"
|
||||
step "4/14 跨目标编译(${CROSS_TARGET},guest 用的静态产物)"
|
||||
RUSTFLAGS="${RUSTFLAGS:+${RUSTFLAGS} }-Dwarnings" \
|
||||
cargo build -p mpc-cli --target "$CROSS_TARGET" --release
|
||||
ok
|
||||
else
|
||||
step "4/13 跨目标编译(${CROSS_TARGET})—— 跳过:目标未安装"
|
||||
step "4/14 跨目标编译(${CROSS_TARGET})—— 跳过:目标未安装"
|
||||
echo " 安装该目标后本条闸门才生效: rustup target add ${CROSS_TARGET}"
|
||||
fi
|
||||
|
||||
if [ "$FAST" -eq 0 ]; then
|
||||
step "5/13 示例冒烟(12 个场景)"
|
||||
step "5/14 示例冒烟(12 个场景)"
|
||||
tools/examples.sh
|
||||
ok
|
||||
|
||||
@@ -122,14 +127,14 @@ if [ "$FAST" -eq 0 ]; then
|
||||
# bash 把逗号并进变量名 → CI 第 4 条直接 `CROSS_TARGET,: unbound variable`
|
||||
# 中途挂掉;而 lint 闸门只扫 deploy/tee,**对自己的盲区完全无感**。
|
||||
# 闸门不扫闸门自己 = 闸门有盲区 = 假安全感。
|
||||
step "6/13 shell 引号 / 变量名卫生"
|
||||
step "6/14 shell 引号 / 变量名卫生"
|
||||
python3 deploy/tee/real-machine/lint-shell-vars.py deploy/tee tools
|
||||
ok
|
||||
|
||||
# 第 6 条:OCI 运行期完整性链自测。
|
||||
# 这条链是「代码度量 → 活文件内容」的闭链,断了不会有编译错误,
|
||||
# 只会在真机上表现为篡改活文件照样通过 —— 必须有本地闸门兜住。
|
||||
step "7/13 OCI 运行期完整性链自测"
|
||||
step "7/14 OCI 运行期完整性链自测"
|
||||
python3 deploy/tee/oci/selftest-chain.py
|
||||
ok
|
||||
|
||||
@@ -140,7 +145,7 @@ if [ "$FAST" -eq 0 ]; then
|
||||
# · 判定断(判定器被顶替 / 输出不是判定结论)→ **假绿**,
|
||||
# 「通过之后真的会签发 token 并下发密钥」这条路从未被验证过。
|
||||
# 所以这里必须同时覆盖正向路径与全部拒绝路径。
|
||||
step "8/13 KBS 先验证明才下发自测"
|
||||
step "8/14 KBS 先验证明才下发自测"
|
||||
python3 deploy/tee/kbs/selftest-kbs.py
|
||||
ok
|
||||
|
||||
@@ -148,7 +153,7 @@ if [ "$FAST" -eq 0 ]; then
|
||||
# guest 的 /init 由 busybox ash 解析,`bash -n` 通过 ≠ ash 能解析。
|
||||
# 真机上这类错误要等 guest 起来才暴露,排查一轮几分钟;
|
||||
# 本地闸门用 alpine 的 busybox ash(与 guest 同款解析器)秒级拦住。
|
||||
step "9/13 guest 脚本 ash 语法"
|
||||
step "9/14 guest 脚本 ash 语法"
|
||||
deploy/tee/guest/syntax-check.sh
|
||||
ok
|
||||
|
||||
@@ -158,7 +163,7 @@ if [ "$FAST" -eq 0 ]; then
|
||||
# 不会有任何编译错误或运行时异常,只会安静地放行。
|
||||
# 用的是真机采集的真报告 + 真 KDS 证书链(公开信任材料,无私钥),
|
||||
# 所以本地无网也能验证「验签逻辑对真报告成立」。
|
||||
step "10/13 SNP 芯片验签器自测(正负向)"
|
||||
step "10/14 SNP 芯片验签器自测(正负向)"
|
||||
python3 deploy/tee/real-machine/selftest-snp-verify.py
|
||||
ok
|
||||
|
||||
@@ -179,7 +184,7 @@ if [ "$FAST" -eq 0 ]; then
|
||||
# 不需要 SDK、不需要 QEMU,秒级完成。
|
||||
# 它证明的是「给定一份日志,判定器的结论正确」,
|
||||
# **不**证明 OP-TEE 的 seal/unseal 行为正确(那要跑 QEMU)。
|
||||
step "11/13 OP-TEE 判据逻辑自测"
|
||||
step "11/14 OP-TEE 判据逻辑自测"
|
||||
python3 tools/selftest-optee-verdict.py
|
||||
ok
|
||||
|
||||
@@ -195,7 +200,7 @@ if [ "$FAST" -eq 0 ]; then
|
||||
# 跑不跑得通。实例回收那条用**心跳文件**判据(实例自己 touch 一个文件,
|
||||
# 停掉后心跳停止)—— 不依赖 ps / /proc,因为受限环境里 ps 常被禁、
|
||||
# macOS 也没有 /proc,那时这条判据会被跳过,而它恰恰是最重要的一条。
|
||||
step "12/13 宿主控制面 mpc-hostd 端到端自测"
|
||||
step "12/14 宿主控制面 mpc-hostd 端到端自测"
|
||||
python3 tools/selftest-hostd.py
|
||||
ok
|
||||
|
||||
@@ -210,9 +215,25 @@ if [ "$FAST" -eq 0 ]; then
|
||||
# 判的是框架自己的契约,不是 EasyTier 的实现。进程真起真回收由
|
||||
# LinkRuntime 单测判(持 Child + try_wait 收割),此处显式再跑一次,
|
||||
# 保证这条判据真的进了主门禁的执行路径。
|
||||
step "13/13 会话级链路层 EasyTier 端到端自测"
|
||||
step "13/14 会话级链路层 EasyTier 端到端自测"
|
||||
python3 tools/selftest-link.py
|
||||
ok
|
||||
|
||||
# 第 14 条:链上层(mpc-chain)端到端自测。
|
||||
#
|
||||
# 这一层的失效也全是静默的:outbox 不幂等,补链会写出重复账;
|
||||
# fail-open 写成 fail-closed,链一挂计算就停;反过来把成员准入写成
|
||||
# 「读不到就放过」,就是准入被绕过。最隐蔽的是 JSON-RPC:HTTP 200
|
||||
# 的响应体里带 error 字段是正常失败形态,只判 HTTP 状态会把「交易
|
||||
# 被拒」当成「已上链」。
|
||||
#
|
||||
# 本机没有 FISCO BCOS 节点,也没有国密模组 —— 用 Python 假 bcos-rpc
|
||||
# 跑完整链路,判的是框架自己的契约。★ 诚实边界:flush 发出去的
|
||||
# payload 是链上对象规范字节,不是已签名交易(SM2 / RLP / provider
|
||||
# 尚未落地),所以这条门禁不证明「能上链」。
|
||||
step "14/14 链上层 mpc-chain 端到端自测"
|
||||
python3 tools/selftest-chain.py
|
||||
ok
|
||||
fi
|
||||
|
||||
printf '\n\033[32m\033[1m全部通过\033[0m\n'
|
||||
@@ -0,0 +1,430 @@
|
||||
#!/usr/bin/env python3
|
||||
"""链上层(阶段 2 形状层)端到端桩自测 —— 主门禁第 14 条。
|
||||
|
||||
# 判的是什么
|
||||
|
||||
本机没有 FISCO BCOS 节点,也没有国密模组。这里用 Python 假 bcos-rpc
|
||||
跑完整链路,判的是**框架自己的契约**,不是 FISCO 的实现:
|
||||
|
||||
1. 链上对象规范编码:确定性、字段敏感、域分隔、SM3 摘要;
|
||||
2. 配置纪律:`sm_crypto` 必须显式 true、TLCP 已声明即拒、缺字段即拒;
|
||||
3. outbox:幂等(同键不新增不覆盖)、fail-open(链挂仍入队)、补链不重发;
|
||||
4. JSON-RPC 判定:HTTP 200 + error 字段必须判失败、缺 result / 串 id
|
||||
都不能当成成功、方法名与 3.x 源码一致;
|
||||
5. 准入:fail-closed(缓存缺失 / 过期 / 硬规则失败 / 非成员一律拒绝);
|
||||
6. 每条负向带**期望的拒绝特征**且必须匹配 —— 只判「失败」分不清
|
||||
按设计拒绝和碰巧崩了。
|
||||
|
||||
# ★ 不判什么(诚实边界)
|
||||
|
||||
`flush` 发出去的是**链上对象规范字节**,不是已签名交易:SM2 签名、
|
||||
RLP 编码、国密模组 provider 都还没落地。所以这里不宣称「能上链」,
|
||||
只宣称补链链路与幂等契约成立。真机对拍项见
|
||||
`docs/INTEGRATION_ANALYSIS.md` 第 7 节。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
BIN = os.path.join(REPO, "target", "debug", "mpc")
|
||||
|
||||
PASS = 0
|
||||
FAIL = 0
|
||||
|
||||
|
||||
def check(name, cond, detail=""):
|
||||
global PASS, FAIL
|
||||
if cond:
|
||||
print(" ok", name)
|
||||
PASS += 1
|
||||
else:
|
||||
print("FAIL", name, "--", str(detail)[:300])
|
||||
FAIL += 1
|
||||
|
||||
|
||||
def run(*args):
|
||||
p = subprocess.run(
|
||||
[BIN, *args], capture_output=True, text=True, timeout=40, cwd=REPO
|
||||
)
|
||||
return p.returncode, p.stdout.strip(), p.stderr.strip()
|
||||
|
||||
|
||||
def expect_reject(name, res, needle):
|
||||
rc, out, err = res
|
||||
all_text = out + "\n" + err
|
||||
check(name, rc != 0 and needle in all_text, f"rc={rc} needle={needle!r} got={all_text[:220]!r}")
|
||||
|
||||
|
||||
class RpcState:
|
||||
def __init__(self):
|
||||
self.mode = "ok"
|
||||
self.calls = []
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def set_mode(self, mode):
|
||||
with self.lock:
|
||||
self.mode = mode
|
||||
self.calls = []
|
||||
|
||||
|
||||
STATE = RpcState()
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("Content-Length", "0"))
|
||||
raw = self.rfile.read(n)
|
||||
try:
|
||||
req = json.loads(raw)
|
||||
except Exception:
|
||||
req = {}
|
||||
with STATE.lock:
|
||||
STATE.calls.append((req.get("method"), req.get("params"), req.get("id")))
|
||||
mode = STATE.mode
|
||||
rid = req.get("id", 1)
|
||||
body = {"jsonrpc": "2.0", "id": rid}
|
||||
if mode == "ok":
|
||||
body["result"] = "0xdeadbeef"
|
||||
elif mode == "error":
|
||||
body["error"] = {"code": -32000, "message": "invalid signature"}
|
||||
elif mode == "null":
|
||||
body["result"] = None
|
||||
elif mode == "missing_result":
|
||||
pass
|
||||
elif mode == "bad_id":
|
||||
body["id"] = rid + 1000
|
||||
body["result"] = "0xdeadbeef"
|
||||
else:
|
||||
raise ValueError(mode)
|
||||
payload = json.dumps(body).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(payload)))
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.wfile.write(payload)
|
||||
|
||||
|
||||
def write(path, obj):
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(obj, f)
|
||||
|
||||
|
||||
def config(port, **over):
|
||||
c = {
|
||||
"rpc_endpoint": f"127.0.0.1:{port}",
|
||||
"group_id": "group0",
|
||||
"chain_id": "chain0",
|
||||
"sm_crypto": True,
|
||||
"client_tlcp": False,
|
||||
}
|
||||
c.update(over)
|
||||
return c
|
||||
|
||||
|
||||
def receipt(**over):
|
||||
r = {
|
||||
"order_id": "order-1",
|
||||
"decision_id": "dec-1",
|
||||
"result_hash": "06" * 32,
|
||||
"input_hash": "07" * 32,
|
||||
"user_data": "08" * 64,
|
||||
"attest": {
|
||||
"user_data_ok": True,
|
||||
"meas_ok": True,
|
||||
"tcb_ok": True,
|
||||
"chip_sig": False,
|
||||
},
|
||||
"link": "p2p",
|
||||
"link_binding": "09" * 32,
|
||||
"signatures": [],
|
||||
}
|
||||
r.update(over)
|
||||
return r
|
||||
|
||||
|
||||
def main():
|
||||
if not os.path.exists(BIN):
|
||||
print("缺少二进制:", BIN, "先跑 cargo build -p mpc-cli")
|
||||
return 2
|
||||
|
||||
tmp = tempfile.mkdtemp(prefix="mpc-chain-selftest-")
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
||||
port = srv.server_address[1]
|
||||
t = threading.Thread(target=srv.serve_forever, daemon=True)
|
||||
t.start()
|
||||
try:
|
||||
p = lambda n: os.path.join(tmp, n)
|
||||
cfg_ok = p("config-ok.json")
|
||||
cfg_down = p("config-down.json")
|
||||
write(cfg_ok, config(port))
|
||||
# 端口 1 上不会有服务:模拟链挂,连接会立刻被拒。
|
||||
write(cfg_down, config(1))
|
||||
rec = p("receipt.json")
|
||||
write(rec, receipt())
|
||||
|
||||
# --- 1. 规范编码与摘要 ---
|
||||
rc, out, _ = run("chain", "digest", "--config", cfg_ok, "--kind", "receipt", "--file", rec)
|
||||
d = None
|
||||
try:
|
||||
d = json.loads(out)
|
||||
except Exception:
|
||||
pass
|
||||
check("digest 输出合法 JSON 且 rc=0", rc == 0 and isinstance(d, dict), (rc, out))
|
||||
check("hashSuite=sm3", bool(d) and d.get("hashSuite") == "sm3", d)
|
||||
check("digest 是 64 位 hex", bool(d) and len(d.get("digest", "")) == 64, d)
|
||||
check("canonicalBytes > 0 且 canonicalHex 长度吻合",
|
||||
bool(d) and d.get("canonicalBytes", 0) > 0
|
||||
and len(d.get("canonicalHex", "")) == 2 * d["canonicalBytes"], d)
|
||||
|
||||
rc2, out2, _ = run("chain", "digest", "--config", cfg_ok, "--kind", "receipt", "--file", rec)
|
||||
check("同一份对象两次摘要一致", rc2 == 0 and out2 == out, (rc2, out2))
|
||||
|
||||
rec2 = p("receipt-changed.json")
|
||||
write(rec2, receipt(link="relay"))
|
||||
_, out3, _ = run("chain", "digest", "--config", cfg_ok, "--kind", "receipt", "--file", rec2)
|
||||
try:
|
||||
d3 = json.loads(out3)
|
||||
except Exception:
|
||||
d3 = {}
|
||||
check("改 link 字段后摘要变化(记录实际路径不是策略)",
|
||||
d3.get("digest") != (d or {}).get("digest"), (d, d3))
|
||||
|
||||
other_kinds = {
|
||||
"member": {
|
||||
"member_id": "alice", "sign_pubkey": "0102", "platform": "hygon-csv",
|
||||
"host_pubkeys": ["aabb"], "active": True, "expires_at": 4102444800,
|
||||
},
|
||||
"order": {
|
||||
"order_id": "order-1", "participants": ["alice", "bob"],
|
||||
"catalog_id": "psi-v1", "ir_hash": "01" * 32,
|
||||
"input_hashes": ["02" * 32], "min_tcb": 7,
|
||||
"session_pubkey": "04" * 65, "policy_bundle_hash": "05" * 32,
|
||||
"deadline": 4102444800,
|
||||
},
|
||||
"bundle": {
|
||||
"bundle_hash": "03" * 32, "issuer": "site-a",
|
||||
"valid_from": 1, "valid_until": 4102444800, "revoked": False,
|
||||
},
|
||||
}
|
||||
digests = set()
|
||||
for kind, body in other_kinds.items():
|
||||
f = p(f"{kind}.json")
|
||||
write(f, body)
|
||||
rc, out, _ = run("chain", "digest", "--config", cfg_ok, "--kind", kind, "--file", f)
|
||||
try:
|
||||
v = json.loads(out)
|
||||
except Exception:
|
||||
v = {}
|
||||
check(f"{kind} 能算出摘要", rc == 0 and len(v.get("digest", "")) == 64, (rc, out))
|
||||
digests.add(v.get("digest"))
|
||||
digests.add((d or {}).get("digest"))
|
||||
check("四类对象摘要互不相同(域分隔 + 类型标签生效)", len(digests) == 4, digests)
|
||||
|
||||
# --- 2. 配置纪律:每条负向带期望特征 ---
|
||||
bad_missing = p("config-missing.json")
|
||||
c = config(port)
|
||||
c.pop("sm_crypto")
|
||||
write(bad_missing, c)
|
||||
expect_reject("配置缺 sm_crypto 即拒绝且点名字段",
|
||||
run("chain", "digest", "--config", bad_missing, "--kind", "receipt", "--file", rec),
|
||||
"sm_crypto")
|
||||
|
||||
nogm = p("config-nogm.json")
|
||||
write(nogm, config(port, sm_crypto=False))
|
||||
expect_reject("sm_crypto=false 拒绝且说明 keccak256 原因",
|
||||
run("chain", "digest", "--config", nogm, "--kind", "receipt", "--file", rec),
|
||||
"keccak256")
|
||||
|
||||
tlcp = p("config-tlcp.json")
|
||||
write(tlcp, config(port, client_tlcp=True))
|
||||
expect_reject("client_tlcp=true 拒绝且点名 TLCP 未实现",
|
||||
run("chain", "digest", "--config", tlcp, "--kind", "receipt", "--file", rec),
|
||||
"TLCP")
|
||||
|
||||
bad_ep = p("config-ep.json")
|
||||
write(bad_ep, config(port, rpc_endpoint="http://127.0.0.1:20200"))
|
||||
expect_reject("endpoint 带 scheme 被拒",
|
||||
run("chain", "digest", "--config", bad_ep, "--kind", "receipt", "--file", rec),
|
||||
"host:port")
|
||||
|
||||
expect_reject("未知参数直接报错不静默忽略",
|
||||
run("chain", "status", "--outbox", p("x.db"), "--bogus", "1"),
|
||||
"未知参数")
|
||||
|
||||
# --- 3. outbox:幂等 / fail-open / 回读 ---
|
||||
box = p("outbox.db")
|
||||
rc, out, _ = run("chain", "submit", "--config", cfg_down, "--outbox", box, "--file", rec)
|
||||
try:
|
||||
s1 = json.loads(out)
|
||||
except Exception:
|
||||
s1 = {}
|
||||
check("链挂时 submit 仍成功(fail-open,链不是执行前提)",
|
||||
rc == 0 and s1.get("outcome") == "added", (rc, out))
|
||||
|
||||
rc, out, _ = run("chain", "submit", "--config", cfg_down, "--outbox", box, "--file", rec)
|
||||
try:
|
||||
s2 = json.loads(out)
|
||||
except Exception:
|
||||
s2 = {}
|
||||
check("同 order_id+decision_id 重复提交 → already_present",
|
||||
rc == 0 and s2.get("outcome") == "already_present", (rc, out))
|
||||
|
||||
rc, out, _ = run("chain", "status", "--outbox", box)
|
||||
try:
|
||||
st = json.loads(out)
|
||||
except Exception:
|
||||
st = {}
|
||||
check("status 只回读 1 条且为 Pending(重启回读)",
|
||||
rc == 0 and len(st.get("entries", [])) == 1
|
||||
and st["entries"][0]["state"] == "Pending" and st.get("pending") == 1, (rc, out))
|
||||
|
||||
rec_b = p("receipt-dec2.json")
|
||||
write(rec_b, receipt(decision_id="dec-2"))
|
||||
run("chain", "submit", "--config", cfg_down, "--outbox", box, "--file", rec_b)
|
||||
_, out, _ = run("chain", "status", "--outbox", box)
|
||||
st = json.loads(out)
|
||||
check("不同 decision_id 是另一条(幂等键是复合的)", len(st["entries"]) == 2, st)
|
||||
|
||||
# payload 被覆盖 = 补链写出与当时承诺不一致的账,必须不发生。
|
||||
changed = p("receipt-overwrite.json")
|
||||
write(changed, receipt(link="relay"))
|
||||
run("chain", "submit", "--config", cfg_down, "--outbox", box, "--file", changed)
|
||||
_, out, _ = run("chain", "status", "--outbox", box)
|
||||
st = json.loads(out)
|
||||
e0 = [e for e in st["entries"] if e["key"] == "receipt:order-1:dec-1"][0]
|
||||
check("重复提交不覆盖已有 payload", e0["payloadBytes"] == (d or {}).get("canonicalBytes"), e0)
|
||||
|
||||
# --- 4. flush:链挂 → 失败不吞、保持 Pending ---
|
||||
rc, out, _ = run("chain", "flush", "--config", cfg_down, "--outbox", box)
|
||||
try:
|
||||
fr = json.loads(out)
|
||||
except Exception:
|
||||
fr = {}
|
||||
check("链挂时 flush 不致命(fail-open)", rc == 0, (rc, out))
|
||||
check("失败原因带出且条目仍 Pending",
|
||||
fr.get("remaining", 0) >= 2
|
||||
and any("连 bcos-rpc 失败" in why for _, why in fr.get("failed", [])),
|
||||
fr)
|
||||
# ★ 回归探针:删掉 .no_proxy() 后,回环端口会被系统代理接走并返回
|
||||
# 502,链挂原因就变成代理的错误而不是「连不上 bcos-rpc」——
|
||||
# 生产里这等于把这一跳的端点偷偷换掉了。
|
||||
check("链挂原因不是代理 502(no_proxy 生效,端点未被转走)",
|
||||
all("502" not in why for _, why in fr.get("failed", [])), fr)
|
||||
_, out, _ = run("chain", "status", "--outbox", box)
|
||||
st = json.loads(out)
|
||||
check("失败后 attempts 递增且 lastError 非空",
|
||||
all(e["attempts"] >= 1 and e["lastError"] for e in st["entries"]), st)
|
||||
|
||||
# --- 5. 假 JSON-RPC:正常补链 + 不重发 ---
|
||||
STATE.set_mode("ok")
|
||||
rc, out, _ = run("chain", "flush", "--config", cfg_ok, "--outbox", box)
|
||||
fr = json.loads(out)
|
||||
check("假链恢复后补链成功", rc == 0 and fr.get("confirmed") == 2 and fr.get("remaining") == 0, fr)
|
||||
check("方法名是 3.x 的 eth_sendRawTransaction",
|
||||
fr.get("method") == "eth_sendRawTransaction", fr)
|
||||
check("服务端只收到 2 次(每条一次)", len(STATE.calls) == 2, STATE.calls)
|
||||
check("请求参数带 0x 前缀的 payload",
|
||||
all(isinstance(c[1], list) and str(c[1][0]).startswith("0x") for c in STATE.calls),
|
||||
STATE.calls)
|
||||
|
||||
STATE.set_mode("ok")
|
||||
rc, out, _ = run("chain", "flush", "--config", cfg_ok, "--outbox", box)
|
||||
fr = json.loads(out)
|
||||
check("第二次 flush 不重复发送(attempted=0)",
|
||||
rc == 0 and fr.get("attempted") == 0 and len(STATE.calls) == 0, (fr, STATE.calls))
|
||||
|
||||
# --- 6. JSON-RPC 失败形态:每条带期望特征 ---
|
||||
for mode, needle in [
|
||||
("error", "invalid signature"),
|
||||
("null", "返回 null"),
|
||||
("missing_result", "缺少 result"),
|
||||
("bad_id", "串包"),
|
||||
]:
|
||||
# 每个场景用一个新 outbox,保证有 Pending 条目可发。
|
||||
b = p(f"outbox-{mode}.db")
|
||||
run("chain", "submit", "--config", cfg_ok, "--outbox", b, "--file", rec)
|
||||
STATE.set_mode(mode)
|
||||
rc, out, _ = run("chain", "flush", "--config", cfg_ok, "--outbox", b)
|
||||
try:
|
||||
fr = json.loads(out)
|
||||
except Exception:
|
||||
fr = {}
|
||||
failed_text = " ".join(str(x) for x in fr.get("failed", []))
|
||||
check(f"{mode} 响应不被当成成功,且带出期望特征 {needle!r}",
|
||||
rc == 0 and fr.get("confirmed", 1) == 0
|
||||
and fr.get("remaining", 0) == 1 and needle in failed_text,
|
||||
(rc, out))
|
||||
_, out, _ = run("chain", "status", "--outbox", b)
|
||||
st = json.loads(out)
|
||||
check(f"{mode} 后条目仍是 Pending(不写假绿)",
|
||||
st["entries"][0]["state"] == "Pending", st)
|
||||
|
||||
# --- 7. 准入:fail-closed ---
|
||||
cache = p("cache.json")
|
||||
write(cache, {"members": ["alice", "bob"], "hard_rules_ok": True, "expires_at": 2000})
|
||||
rc, out, _ = run("chain", "admit", "--cache", cache, "--now", "1000",
|
||||
"--site", "alice", "--participants", "alice,bob")
|
||||
check("缓存新鲜且全是成员 → allow", rc == 0 and "allow" in out, (rc, out))
|
||||
expect_reject("缓存过期即拒(含边界 now=expires_at)",
|
||||
run("chain", "admit", "--cache", cache, "--now", "2000",
|
||||
"--site", "alice", "--participants", "alice,bob"),
|
||||
"过期")
|
||||
expect_reject("非成员站点拒绝",
|
||||
run("chain", "admit", "--cache", cache, "--now", "1000",
|
||||
"--site", "eve", "--participants", "alice,bob"),
|
||||
"成员表中")
|
||||
expect_reject("参与方含非成员拒绝",
|
||||
run("chain", "admit", "--cache", cache, "--now", "1000",
|
||||
"--site", "alice", "--participants", "alice,eve"),
|
||||
"不是联盟成员")
|
||||
|
||||
hard = p("cache-hard.json")
|
||||
write(hard, {"members": ["alice", "bob"], "hard_rules_ok": False, "expires_at": 2000})
|
||||
expect_reject("硬规则未通过拒绝",
|
||||
run("chain", "admit", "--cache", hard, "--now", "1000",
|
||||
"--site", "alice", "--participants", "alice,bob"),
|
||||
"硬规则")
|
||||
|
||||
no_exp = p("cache-no-exp.json")
|
||||
write(no_exp, {"members": ["alice", "bob"], "hard_rules_ok": True})
|
||||
expect_reject("缓存缺 expires_at 拒绝(不当永不过期)",
|
||||
run("chain", "admit", "--cache", no_exp, "--now", "1000",
|
||||
"--site", "alice", "--participants", "alice,bob"),
|
||||
"永不过期")
|
||||
|
||||
# --- 8. outbox 坏行不静默跳过 ---
|
||||
broken = p("outbox-broken.db")
|
||||
with open(broken, "w", encoding="utf-8") as f:
|
||||
f.write("v1|broken|line\n")
|
||||
expect_reject("outbox 坏行整体拒绝(不悄悄丢审计记录)",
|
||||
run("chain", "status", "--outbox", broken), "格式损坏")
|
||||
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
shutil.rmtree(tmp, ignore_errors=True)
|
||||
|
||||
print()
|
||||
print(f"判据 {PASS + FAIL} 条:通过 {PASS},失败 {FAIL}")
|
||||
if FAIL:
|
||||
return 1
|
||||
print("全部通过")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user