- 钉死 InvalidSignature 根因:节点 3.17.1 走 fast_sm2_verify,验签 e=SM3(ZA||dataHash)(distid=1234567812345678);旧实现签裸摘要口径不符。 - PrehashedSm2Signer 改为带 ZA 口径;compute_za 从 OpenSSL 曲线读 a/Gx/Gy,杜绝手抄 a=p-3 错写 fc 的坑。 - chain contract deploy/call/read 子命令落地,opts 支持 --arg 多值;接真链跑通部署+recordHardRule+读回+负向矩阵。 - selftest-fisco-contract.py 接入 ci.sh 第 22 条(22 自测+22 真链批,缺环境显式 SKIPPED)。 - docs/catalog 纠正 eth_ 端点与「不二次 SM3」过时口径;合约源码与 combined.json 入仓。
1462 lines
62 KiB
Rust
1462 lines
62 KiB
Rust
//! `mpc chain` —— 链上层命令行。
|
||
//!
|
||
//! # 诚实边界(写在使用说明前面)
|
||
//!
|
||
//! 2026-11-07 用户拍板后,`mpc chain sign` 已经能用 OpenSSL **真的签出**
|
||
//! SM2 签名(raw `r||s` 64B),但它是软件签名器、私钥可导出、密评不可过。
|
||
//!
|
||
//! # flush 的两种形态(`--mode` 显式给,不猜)
|
||
//!
|
||
//! | mode | 发什么 | 走哪个方法 | 结论 |
|
||
//! |---|---|---|---|
|
||
//! | `stub` | 链上对象规范字节 | 桩方法 `eth_sendRawTransaction` | 只演练补链/幂等/传输准入契约 |
|
||
//! | `signed-tx` | **完整已签名 FISCO 交易**(TARS 字节) | `sendTransaction`(4 参) | 真国密交易上链 |
|
||
//!
|
||
//! `signed-tx` 的流程与上游 `TransactionBuilder` 一致:
|
||
//! `outbox payload` → 合约调用编码(选择子 = **SM3 前 4 字节**)→
|
||
//! `TransactionData`(V1)→ `validate()` → `dataHash`(SM3) → prehashed SM2
|
||
//! 签名 → `Transaction` TARS 编码 → `sendTransaction`。
|
||
//!
|
||
//! ★ 交易签名是 **`r||s||pub`(128 字节)**:上游
|
||
//! `signTransactionDataHash()` 传 `_signatureWithPub = true`,
|
||
//! 公钥是裸 64 字节 `X||Y`(不带 `04` 前缀)。
|
||
//! 只签 64 字节 `r||s` 的交易,节点侧解析不出公钥 ⇒ 交易被拒。
|
||
//!
|
||
//! 成功判据**三件套,缺一不可**:`status == 0`(`TransactionStatus::None`
|
||
//! = 执行成功,**与 web3 的 `0x1` 相反**)+ `transactionHash` 非空 +
|
||
//! `blockNumber > 0`(已出块,不是「刚进交易池」)。
|
||
//!
|
||
//! ★ 国密链提交方法是自有 `sendTransaction`(4 参),
|
||
//! **不是** `eth_sendRawTransaction` —— web3 端点固定
|
||
//! secp256k1 + keccak256(`Web3Transaction.cpp`),与 SM2/SM3 不兼容。
|
||
//!
|
||
//! ★ 两条路径**都必须走 outbox 状态机**(`flush_with`):成功置 Confirmed,
|
||
//! 失败保持 Pending 并累计 attempts。自己遍历 entries 而不写回状态
|
||
//! ⇒ 第二次 flush 会把同一笔再发一遍。
|
||
//!
|
||
//! 逐条上游事实见 `docs/FISCO_UPSTREAM_TRUTH.md`。
|
||
//!
|
||
//! # 仍然不宣称的
|
||
//!
|
||
//! - 签名器是 **OpenSSL 软件 SM2**,不是硬件国密模组 ⇒ 密评不可过。
|
||
//! - TLCP 传输通道的 FFI 未落地 ⇒ 生产路径仍 fail-closed。
|
||
//! - `signed-tx` 需要链上已有目标合约地址;本仓库**不含合约部署流程**。
|
||
//! - 「交易编码逐字节对齐官方 SDK」**不等于**「真链能上链」:
|
||
//! 判据用的是假 bcos-rpc,验的是框架契约。
|
||
|
||
use mpc_chain::admission::{chain_admit, MemberCache};
|
||
use mpc_chain::contract::{encode_call, ParamType, Value as ContractValue};
|
||
use mpc_chain::fisco_abi::{build_deploy_transaction_data, DeployParams};
|
||
use mpc_chain::fisco_tx::{
|
||
build_signed_transaction, random_nonce, PrehashedSm2Signer, TransactionData,
|
||
};
|
||
use mpc_chain::objects::{
|
||
object_digest, ChainObject, ComputeOrder, Member, PolicyBundleRecord, Receipt,
|
||
};
|
||
use mpc_chain::opa::{
|
||
decide, sign_bundle, DecideRequest, OpaRunner, RevocationView, RevocationViewSource,
|
||
};
|
||
use mpc_chain::outbox::{EnqueueOutcome, Outbox};
|
||
use mpc_chain::policy::{governance_boundary, HardRuleSet, OpaPolicyBundle};
|
||
use mpc_chain::rpc::{ChainClient, HttpChainClient};
|
||
use mpc_chain::signer::{
|
||
require_self_test, Signer, SignerPolicy, SignerSecurityProfile, SOFTWARE_DEV_WARNING,
|
||
};
|
||
use mpc_chain::sm2::{
|
||
aligned_distid, distid_fingerprint, raw_rs_to_der, DistidConsumer, OpenSslSoftwareSigner,
|
||
SM2_DISTID,
|
||
};
|
||
use mpc_chain::tlcp::{
|
||
probe_tlcp_environment, TlcpBackend, TlcpConfig, TlcpEndpoint, TlcpReadiness, TlcpTunnel,
|
||
};
|
||
use mpc_chain::{from_hex, to_hex, ChainConfig, ChainError, TransportMode, PLAINTEXT_STUB_WARNING};
|
||
use std::collections::HashMap;
|
||
use std::fs;
|
||
use std::path::Path;
|
||
|
||
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..]),
|
||
Some("keygen") => cmd_keygen(&args[1..]),
|
||
Some("sign") => cmd_sign(&args[1..]),
|
||
Some("align") => cmd_align(&args[1..]),
|
||
Some("tlcp") => cmd_tlcp(&args[1..]),
|
||
Some("governance") => cmd_governance(&args[1..]),
|
||
Some("opa") => cmd_opa(&args[1..]),
|
||
Some("contract") => cmd_contract(&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 --transport stub|tlcp [--tlcp-config PATH]
|
||
--mode stub|signed-tx
|
||
signed-tx 额外要: --key PATH --contract HEXADDR [--method NAME]
|
||
[--node NAME] [--gas-limit N]
|
||
mpc chain status 从 outbox 回读条目状态 --outbox PATH
|
||
mpc chain admit 链读侧准入(fail-closed)
|
||
--cache PATH --now N --site NAME --participants A,B
|
||
|
||
mpc chain keygen 生成【开发用】OpenSSL 软件 SM2 密钥(0600)
|
||
--out PATH --pub-out PATH
|
||
mpc chain sign 用 SM2 签一段字节(输出 raw r||s 与 DER)
|
||
--key PATH --file PATH --policy production-module|development-software
|
||
mpc chain align 校验 SM2 distid 三重对齐
|
||
[--chain-verifier-distid STR] [--csv-distid STR]
|
||
mpc chain tlcp 报告国密 TLCP 通道就绪状态(诊断,不发起连接)
|
||
[--file PATH] (TLCP 双证书配置)
|
||
mpc chain governance 算治理对象摘要(硬规则 / OPA bundle)
|
||
--config PATH --kind hard-rule|opa-bundle --file PATH
|
||
|
||
mpc chain opa sign 控制面签发真 OPA bundle(SM2 真签 + SM3 hash pin)
|
||
--bundle PATH --key PATH --id STR --issuer STR --expires N
|
||
--policy production-module|development-software --out PATH
|
||
mpc chain opa decide 验签 → 有效期/撤销 → 真 opa eval → decision 落 outbox
|
||
--bundle PATH --manifest PATH --input PATH --revocation PATH|chain
|
||
--query STR --now N --outbox PATH --order-id STR
|
||
mpc chain contract deploy|call|read|abi 合约部署 / 调用 / 只读调用 / ABI 转换
|
||
(详见 `mpc chain contract`)
|
||
|
||
★ opa 只在宿主/控制面 spawn 外部二进制,**不在 guest 内执行**;
|
||
撤销来源两种:--revocation PATH 给调用方本地桩,或 --revocation chain 声明
|
||
走链上撤销状态位读取(**链读后端未接入 ⇒ fail-closed 拒**,绝不默认
|
||
revoked=false 放行);
|
||
decision 只是 outbox 存证,不是已签名交易、也没有上链。
|
||
|
||
★ --transport 必须显式给:stub 只允许桩自测,tlcp 是生产路径。
|
||
★ sign 的 --policy 必须显式给;production-module 会拒绝软件签名器。
|
||
★ flush 的 --mode 必须显式给:
|
||
stub = 演练契约,发的是链上对象规范字节(走桩方法,不是国密链入口);
|
||
signed-tx = 真国密交易:TARS 编码 + prehashed SM2 签名 + sendTransaction(4 参),
|
||
成功判据三件套:status==0(TransactionStatus::None)+ txHash 非空
|
||
+ blockNumber>0(已出块,不是刚进交易池)。
|
||
★ signed-tx 用的仍是 OpenSSL 软件 SM2 签名器(私钥可导出、密评不可过);
|
||
国密链提交入口是 sendTransaction(4 参),不是 eth_sendRawTransaction。";
|
||
|
||
/// 解析 `--key value` 形式的参数。
|
||
///
|
||
/// ★ **可重复参数**(如 `--arg`)用 [`MULTI_SEP`] 分隔累积,其余参数重复给出
|
||
/// 仍然报错(避免 `--node a --node b` 这种静默取最后一个的歧义)。
|
||
fn opts(args: &[String], allowed: &[&str]) -> Result<HashMap<String, String>, String> {
|
||
let mut m: HashMap<String, String> = 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(" ")));
|
||
}
|
||
// ★ 布尔标志(`--dry-run`):下一个 token 不以 `--` 开头时它才是取值,
|
||
// 否则该标志取默认值 `1`。这样既能用 `--dry-run` 也能用 `--dry-run=0`
|
||
// 显式关掉。带值的参数(如 `--node node0`)行为不变。
|
||
let next_is_value = args
|
||
.get(i + 1)
|
||
.map(|v| !v.starts_with("--"))
|
||
.unwrap_or(false);
|
||
let v = if next_is_value {
|
||
args[i + 1].clone()
|
||
} else {
|
||
String::from("1")
|
||
};
|
||
match m.get_mut(k) {
|
||
Some(prev) if MULTI_KEYS.contains(&k.as_str()) => {
|
||
prev.push_str(MULTI_SEP);
|
||
prev.push_str(&v);
|
||
}
|
||
Some(_) => {
|
||
return Err(format!("{k} 重复给出"));
|
||
}
|
||
None => {
|
||
m.insert(k.clone(), v);
|
||
}
|
||
}
|
||
i += if next_is_value { 2 } else { 1 };
|
||
}
|
||
Ok(m)
|
||
}
|
||
|
||
/// 允许重复给出的参数键。
|
||
///
|
||
/// `--arg` 必须可重复:合约方法有多个参数,而每个参数各给一个 `--arg`。
|
||
const MULTI_KEYS: &[&str] = &["--arg"];
|
||
|
||
/// 可重复参数值的分隔符(不会出现在参数值里)。
|
||
const MULTI_SEP: &str = "\u{1}";
|
||
|
||
/// 取可重复参数的全部取值。
|
||
fn multi(m: &HashMap<String, String>, key: &str) -> Vec<String> {
|
||
m.get(key)
|
||
.map(|v| {
|
||
v.split(MULTI_SEP)
|
||
.filter(|s| !s.is_empty())
|
||
.map(str::to_owned)
|
||
.collect()
|
||
})
|
||
.unwrap_or_default()
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
/// 把 `TransactionData` 序列化成 JSON(给 `--dry-run` 用)。
|
||
///
|
||
/// ★ 目的是**对拍**:字段名与上游 `TransactionData` 的 JSON 口径一致,
|
||
/// 这样同一份数据可以同时喂给官方 JNI 和本框架,逐字节比。
|
||
/// `input` 用 hex(上游 JSON 也是 hex 串),`abi` 用字符串。
|
||
fn tx_data_json(d: &TransactionData) -> String {
|
||
format!(
|
||
"{{\"version\":{},\"chainId\":\"{}\",\"groupId\":\"{}\",\"blockLimit\":{},\
|
||
\"nonce\":\"{}\",\"to\":\"{}\",\"input\":\"0x{}\",\"abi\":\"{}\",\
|
||
\"value\":\"{}\",\"gasPrice\":\"{}\",\"gasLimit\":{},\"maxFeePerGas\":\"{}\",\
|
||
\"maxPriorityFeePerGas\":\"{}\"}}",
|
||
d.version,
|
||
esc(&d.chain_id),
|
||
esc(&d.group_id),
|
||
d.block_limit,
|
||
esc(&d.nonce),
|
||
esc(&d.to),
|
||
to_hex(&d.input),
|
||
esc(&d.abi),
|
||
esc(&d.value),
|
||
esc(&d.gas_price),
|
||
d.gas_limit,
|
||
esc(&d.max_fee_per_gas),
|
||
esc(&d.max_priority_fee_per_gas),
|
||
)
|
||
}
|
||
|
||
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 write_private(path: &str, bytes: &[u8]) -> Result<(), String> {
|
||
use std::io::Write;
|
||
let mut o = fs::OpenOptions::new();
|
||
o.write(true).create(true).truncate(true);
|
||
#[cfg(unix)]
|
||
{
|
||
use std::os::unix::fs::OpenOptionsExt;
|
||
o.mode(0o600);
|
||
}
|
||
let mut f = o.open(path).map_err(|e| format!("创建私钥文件 {path} 失败: {e}"))?;
|
||
f.write_all(bytes).map_err(|e| format!("写私钥失败: {e}"))?;
|
||
Ok(())
|
||
}
|
||
|
||
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",
|
||
"--transport",
|
||
"--tlcp-config",
|
||
"--mode",
|
||
"--key",
|
||
"--contract",
|
||
"--method",
|
||
"--node",
|
||
"--gas-limit",
|
||
],
|
||
)?;
|
||
let cfg = config(req(&o, "--config")?)?;
|
||
// ★ 传输形态必须显式给,没有默认值 —— 默认明文就是留后门。
|
||
let mode = match req(&o, "--transport")? {
|
||
"stub" => TransportMode::PlaintextStub,
|
||
"tlcp" => TransportMode::Tlcp,
|
||
other => return Err(format!("--transport 只能是 stub|tlcp,得到 {other}")),
|
||
};
|
||
let tlcp_cfg = match o.get("--tlcp-config") {
|
||
Some(p) => Some(TlcpConfig::from_json(&read(p)?).map_err(|e| e.to_string())?),
|
||
None => None,
|
||
};
|
||
mpc_chain::require_transport(&cfg, mode, tlcp_cfg.as_ref()).map_err(|e| e.to_string())?;
|
||
if mode == TransportMode::PlaintextStub {
|
||
eprintln!("{PLAINTEXT_STUB_WARNING}");
|
||
}
|
||
|
||
// ★ 提交形态也必须显式给:stub 是「演练契约」,signed-tx 才是「真交易上链」。
|
||
// 两者产出的语义完全不同,不能让调用方靠猜。
|
||
let submit_mode = match req(&o, "--mode")? {
|
||
"stub" => "stub",
|
||
"signed-tx" => "signed-tx",
|
||
other => return Err(format!("--mode 只能是 stub|signed-tx,得到 {other}")),
|
||
};
|
||
|
||
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())?;
|
||
// ★ 守卫真跑一遍并把结论写进输出:桩自测能核对「国密链确实禁用
|
||
// eth_sendRawTransaction」,而不是只靠注释声称。cfg.sm_crypto
|
||
// 在配置层已冻结为 true,所以正常路径下这里必然是 true。
|
||
let guomi_rejects_stub = mpc_chain::rpc::assert_submit_method_allowed(
|
||
mpc_chain::rpc::METHOD_SEND_RAW_TX,
|
||
cfg.sm_crypto,
|
||
)
|
||
.is_err();
|
||
|
||
if submit_mode == "stub" {
|
||
eprintln!(
|
||
"注意: stub 模式的 payload 仍是链上对象规范字节,不是已签名交易(FISCO 自有交易编码 /\
|
||
TLCP 握手 FFI 未落地);此处只验证补链、幂等与传输准入契约。\
|
||
桩方法 eth_sendRawTransaction 不是国密链入口,真链必须走 sendTransaction(4 参)。"
|
||
);
|
||
let report = boxed
|
||
.flush_with(|entry| {
|
||
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\":\"{}\",\"methodIsStub\":{},\"guomiSubmitMethod\":\"{}\",\"guomiChainRejectsStubMethod\":{},\"payload\":\"canonical-bytes-not-signed-tx\",\"transport\":\"{}\"}}",
|
||
report.attempted,
|
||
report.confirmed,
|
||
failed.join(","),
|
||
report.remaining,
|
||
esc(mpc_chain::rpc::METHOD_SEND_RAW_TX),
|
||
true,
|
||
esc(mpc_chain::rpc::METHOD_SEND_TRANSACTION),
|
||
guomi_rejects_stub,
|
||
match mode {
|
||
TransportMode::PlaintextStub => "plaintext-stub",
|
||
TransportMode::Tlcp => "tlcp",
|
||
}
|
||
);
|
||
return Ok(());
|
||
}
|
||
|
||
// ---------------- signed-tx:真国密交易上链 ----------------
|
||
//
|
||
// 流程与上游 `TransactionBuilder` 一致:
|
||
// outbox payload(链上对象规范字节)
|
||
// → 合约调用编码(选择子 = SM3 前 4 字节)
|
||
// → TransactionData(V1,四个 gas 字段必须是 hex 串)
|
||
// → validate() → dataHash(SM3) → prehashed SM2 签名
|
||
// → Transaction TARS 编码
|
||
// → sendTransaction(groupID, nodeName, data, requireProof)
|
||
// → 判据:status == 0(TransactionStatus::None)且 txHash 非空
|
||
// 且 blockNumber > 0
|
||
let key_pem = read(req(&o, "--key")?)?;
|
||
let signer = PrehashedSm2Signer::from_private_pem(key_pem.as_bytes())
|
||
.map_err(|e| e.to_string())?;
|
||
let contract_addr = req(&o, "--contract")?.to_string();
|
||
let method = o
|
||
.get("--method")
|
||
.cloned()
|
||
.unwrap_or_else(|| String::from("record"));
|
||
let node_name = o
|
||
.get("--node")
|
||
.cloned()
|
||
.unwrap_or_else(|| String::from("node0"));
|
||
let gas_limit: i64 = match o.get("--gas-limit") {
|
||
Some(v) => v
|
||
.parse()
|
||
.map_err(|_| String::from("--gas-limit 必须是整数"))?,
|
||
None => 30_000_000,
|
||
};
|
||
if gas_limit <= 0 {
|
||
return Err(String::from("--gas-limit 必须为正"));
|
||
}
|
||
|
||
// ★ 合约地址必须是 20 字节 hex,否则交易会在链上被拒,而症状是
|
||
// 「交易没上链」而不是「地址不合法」。
|
||
let addr_bytes = mpc_chain::from_hex(contract_addr.trim_start_matches("0x"))
|
||
.map_err(|e| e.to_string())?;
|
||
if addr_bytes.len() != 20 {
|
||
return Err(format!(
|
||
"--contract 必须是不带 0x 前缀的 20 字节合约地址,收到 {} 字节",
|
||
addr_bytes.len()
|
||
));
|
||
}
|
||
|
||
// ★★ 必须走 `flush_with` 状态机,不能自己遍历 entries。
|
||
// 自己遍历的话**从不写回 Confirmed 状态** ⇒ 第二次 flush 会把同一笔
|
||
// 交易再发一遍(链上 nonce 不同 ⇒ 可能真上链两次)。
|
||
// `flush_with` 负责:只取 Pending、成功置 Confirmed、失败保持 Pending
|
||
// 并累计 attempts、最后落盘。幂等性由它保证,不许另起一套。
|
||
let mut results: Vec<String> = Vec::new();
|
||
let report = boxed
|
||
.flush_with(|entry| {
|
||
let payload = mpc_chain::from_hex(&entry.payload_hex)
|
||
.map_err(|e| ChainError::BadInput(format!("payload 不是合法 hex: {e}")))?;
|
||
// ★ 链上对象规范字节 → 合约调用的 input(选择子 = SM3 前 4 字节)。
|
||
let call_data = encode_call(
|
||
&method,
|
||
&[ParamType::Bytes],
|
||
&[ContractValue::Bytes(payload)],
|
||
)
|
||
.map_err(|e| ChainError::BadInput(format!("合约调用编码失败: {e}")))?;
|
||
let data = TransactionData {
|
||
version: 1,
|
||
chain_id: cfg.chain_id.clone(),
|
||
group_id: cfg.group_id.clone(),
|
||
block_limit: 500,
|
||
nonce: random_nonce()?,
|
||
to: contract_addr.clone(),
|
||
input: call_data,
|
||
abi: String::new(),
|
||
// ★ V1 的四个字段必须全是 hex 串,节点侧 `TransactionFactoryImpl`
|
||
// 不满足就抛 `std::invalid_argument`。
|
||
value: String::from("0x0"),
|
||
gas_price: String::from("0x0"),
|
||
gas_limit,
|
||
max_fee_per_gas: String::from("0x0"),
|
||
max_priority_fee_per_gas: String::from("0x0"),
|
||
extension: Vec::new(),
|
||
};
|
||
data.validate()?;
|
||
let (_tx, tx_bytes) = build_signed_transaction(&data, &signer)?;
|
||
let tx_hex = to_hex(&tx_bytes);
|
||
// ★ 真提交:国密链自有 `sendTransaction`(4 参)。
|
||
let r = client
|
||
.send_transaction(&cfg.group_id, &node_name, &tx_hex, true)
|
||
.map_err(|e| {
|
||
let reason = format!("sendTransaction 失败: {e}");
|
||
results.push(format!(
|
||
"{{\"key\":\"{}\",\"txHash\":\"\",\"status\":null,\"blockNumber\":null,\"gasUsed\":null,\"accepted\":false,\"txBytes\":{},\"error\":\"{}\"}}",
|
||
esc(&entry.key),
|
||
tx_bytes.len(),
|
||
esc(&reason)
|
||
));
|
||
e
|
||
})?;
|
||
// ★ 成功判据三件套,缺一不可:
|
||
// status == 0(TransactionStatus::None = 执行成功)
|
||
// transactionHash 非空(链上凭据)
|
||
// blockNumber > 0(已出块,不是「刚进交易池」)
|
||
let ok = r.status_code == Some(0)
|
||
&& !r.tx_hash.is_empty()
|
||
&& r.block_number.unwrap_or(0) > 0;
|
||
let detail = format!(
|
||
"{{\"key\":\"{}\",\"txHash\":\"{}\",\"status\":{},\"blockNumber\":{},\"gasUsed\":{},\"accepted\":{},\"txBytes\":{}}}",
|
||
esc(&entry.key),
|
||
esc(&r.tx_hash),
|
||
r.status_code.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
r.block_number.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
r.gas_used.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
ok,
|
||
tx_bytes.len()
|
||
);
|
||
if !ok {
|
||
// 失败必须**带出可核对的特征**(status / txHash / blockNumber),
|
||
// 否则「失败」没法与「日志没打出来」区分开。
|
||
let reason = format!(
|
||
"交易未被链上确认为成功: status={:?} txHash={} blockNumber={:?}",
|
||
r.status_code, r.tx_hash, r.block_number
|
||
);
|
||
results.push(format!(
|
||
"{{\"key\":\"{}\",\"txHash\":\"{}\",\"status\":{},\"blockNumber\":{},\"gasUsed\":{},\"accepted\":false,\"txBytes\":{},\"error\":\"{}\"}}",
|
||
esc(&entry.key),
|
||
esc(&r.tx_hash),
|
||
r.status_code.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
r.block_number.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
r.gas_used.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
tx_bytes.len(),
|
||
esc(&reason)
|
||
));
|
||
return Err(ChainError::Rpc(reason));
|
||
}
|
||
results.push(detail);
|
||
Ok(())
|
||
})
|
||
.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\":\"{}\",\"methodIsStub\":false,\"guomiSubmitMethod\":\"{}\",\"guomiChainRejectsStubMethod\":{},\"payload\":\"signed-fisco-transaction-tars\",\"transport\":\"{}\",\"contract\":\"{}\",\"results\":[{}]}}",
|
||
report.attempted,
|
||
report.confirmed,
|
||
failed.join(","),
|
||
report.remaining,
|
||
esc(mpc_chain::rpc::METHOD_SEND_TRANSACTION),
|
||
esc(mpc_chain::rpc::METHOD_SEND_TRANSACTION),
|
||
guomi_rejects_stub,
|
||
match mode {
|
||
TransportMode::PlaintextStub => "plaintext-stub",
|
||
TransportMode::Tlcp => "tlcp",
|
||
},
|
||
esc(&contract_addr),
|
||
results.join(",")
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
// ===========================================================================
|
||
// `mpc chain contract` —— 合约部署 / 调用 / 只读调用
|
||
// ===========================================================================
|
||
//
|
||
// ★ 这一层解决的是「合约能不能被调起来」的三个真缺口(都是 2026-11-08
|
||
// 真链实测挖出来的,不是猜的):
|
||
//
|
||
// 1. **ABI JSON 必须带二元 selector 数组**(`[keccak_u32, sm3_u32]`)。
|
||
// solc 产的 ABI **没有** `selector` 字段 ⇒ executor 侧
|
||
// `FunctionAbi::deserialize()` 里 `selector` 保持 0 ⇒ 链上永远匹配不上
|
||
// ⇒ 交易「成功」但函数走 fallback 不执行(**静默失败**)。
|
||
// 国密链取 `selector[1]`(SM3),标准链取 `selector[0]`(keccak)。
|
||
//
|
||
// 2. **部署交易与调用交易的差别**(`java-sdk`
|
||
// `DefaultTransactionManager.createSignedTransaction`):
|
||
// - 部署:`to` 空串、`abi` 非空、`attribute = EVM_ABI_CODEC(0x1)`、
|
||
// `input` = 合约字节码 **+** 构造函数参数编码(构造函数**无选择子**)。
|
||
// - 调用:`to` = 合约地址、`abi` 空、`attribute = 0`、
|
||
// `input` = 选择子(SM3 前 4B) + 参数编码。
|
||
//
|
||
// 3. **FISCO 的只读调用端点是自有的 `call`(4 参
|
||
// `[groupID, nodeName, to, data]`)**,不是 web3 的 `eth_call`;
|
||
// 回执端点是 `getTransactionReceipt`,不是 `eth_getTransactionReceipt`。
|
||
// 真链实测:`eth_call` / `eth_getTransactionReceipt` 都回
|
||
// `-32601 The method does not exist/is not available.`。
|
||
//
|
||
// # 诚实边界
|
||
//
|
||
// - 签名器仍是 **OpenSSL 软件 SM2**(私钥可导出 ⇒ 密评不可过)。
|
||
// - `constant` / `view` 函数在 executor 侧被**跳过**(不参与选择子匹配),
|
||
// 所以只读函数必须走 `call` 端点,不能靠发交易去「读」。
|
||
// - 本命令**不管理**合约生命周期(不删、不升级),只做部署 + 调用 + 读。
|
||
|
||
const CONTRACT_USAGE: &str = "用法:
|
||
mpc chain contract deploy 部署合约(真交易上链,取回 contractAddress)
|
||
--config PATH --bin PATH --abi PATH --key PATH
|
||
[--node NAME] [--gas-limit N] [--block-limit N]
|
||
mpc chain contract call 调用已部署合约的写接口(真交易上链)
|
||
--config PATH --contract HEXADDR --method NAME --abi PATH --key PATH
|
||
[--node NAME] [--gas-limit N] [--arg TYPE:VALUE ...]
|
||
mpc chain contract read 只读调用合约(走 FISCO 自有 call 端点,不上链)
|
||
--config PATH --contract HEXADDR --method NAME --abi PATH
|
||
[--node NAME] [--arg TYPE:VALUE ...]
|
||
mpc chain contract abi 把 solc ABI 转成 FISCO ABI(补二元 selector 数组)
|
||
--solc-abi PATH --out PATH
|
||
|
||
★ --bin/--abi 指 solc(Gm 国密版)产物;--abi 必须是 **solc 的** ABI JSON,
|
||
本命令会自己转成 FISCO 形态(补 selector 数组)。
|
||
★ --arg 形如 `bytes:0xdeadbeef` / `bytes32:0x<64hex>` / `uint256:7`
|
||
/ `bool:true` / `address:0x<40hex>` / `string:文本`。
|
||
★ 部署交易 attribute = EVM_ABI_CODEC(0x1);调用交易 attribute = 0。
|
||
★ 成功判据三件套:status==0(TransactionStatus::None)+ transactionHash 非空
|
||
+ blockNumber>0。";
|
||
|
||
fn cmd_contract(args: &[String]) -> Result<(), String> {
|
||
match args.first().map(String::as_str) {
|
||
Some("deploy") => cmd_contract_deploy(&args[1..]),
|
||
Some("call") => cmd_contract_call(&args[1..]),
|
||
Some("read") => cmd_contract_read(&args[1..]),
|
||
Some("abi") => cmd_contract_abi(&args[1..]),
|
||
_ => Err(CONTRACT_USAGE.to_string()),
|
||
}
|
||
}
|
||
|
||
/// 从 solc 的 combined.json 之类里抽 `bin` 与 `abi`。
|
||
///
|
||
/// 解析放在 `mpc-chain::fisco_abi::load_solc_artifacts` 里 ——
|
||
/// `mpc-cli` **刻意不依赖** crates.io 的第三方 crate(`serde_json` 等等)。
|
||
fn load_solc_artifacts(path: &str) -> Result<(Vec<u8>, String), String> {
|
||
let text = read(path)?;
|
||
mpc_chain::fisco_abi::load_solc_artifacts(&text).map_err(|e| e.to_string())
|
||
}
|
||
|
||
/// 解析 `--arg TYPE:VALUE`。类型不认识**拒绝**(不猜、不降级)。
|
||
fn parse_arg(spec: &str) -> Result<(ParamType, ContractValue), String> {
|
||
let (t, v) = spec
|
||
.split_once(':')
|
||
.ok_or_else(|| format!("--arg 必须是 TYPE:VALUE 形式,得到 {spec}"))?;
|
||
let ty = ParamType::parse(t.trim()).map_err(|e| e.to_string())?;
|
||
let v = v.trim();
|
||
let val = match ty {
|
||
ParamType::Uint256 => {
|
||
let n: u64 = v
|
||
.parse()
|
||
.map_err(|_| format!("--arg uint256 的值不是整数: {v}"))?;
|
||
ContractValue::Uint(n)
|
||
}
|
||
ParamType::Uint8 => {
|
||
let n: u8 = v
|
||
.parse()
|
||
.map_err(|_| format!("--arg uint8 的值不是 0..=255 的整数: {v}"))?;
|
||
ContractValue::Uint8(n)
|
||
}
|
||
ParamType::Bool => {
|
||
let b = match v {
|
||
"true" => true,
|
||
"false" => false,
|
||
other => return Err(format!("--arg bool 只接受 true/false,得到 {other}")),
|
||
};
|
||
ContractValue::Bool(b)
|
||
}
|
||
ParamType::Address => ContractValue::Address(String::from(v)),
|
||
ParamType::Bytes32 => {
|
||
let b = mpc_chain::from_hex(v.trim_start_matches("0x"))
|
||
.map_err(|e| format!("--arg bytes32 不是合法 hex: {e}"))?;
|
||
if b.len() != 32 {
|
||
return Err(format!(
|
||
"--arg bytes32 必须 32 字节,收到 {} 字节",
|
||
b.len()
|
||
));
|
||
}
|
||
ContractValue::FixedBytes(b)
|
||
}
|
||
ParamType::Bytes => {
|
||
let b = mpc_chain::from_hex(v.trim_start_matches("0x"))
|
||
.map_err(|e| format!("--arg bytes 不是合法 hex: {e}"))?;
|
||
ContractValue::Bytes(b)
|
||
}
|
||
ParamType::String => ContractValue::String(String::from(v)),
|
||
};
|
||
Ok((ty, val))
|
||
}
|
||
|
||
/// 部署合约:真交易上链,取回 `contractAddress`。
|
||
fn cmd_contract_deploy(args: &[String]) -> Result<(), String> {
|
||
let o = opts(
|
||
args,
|
||
&[
|
||
"--config",
|
||
"--bin",
|
||
"--abi",
|
||
"--key",
|
||
"--node",
|
||
"--gas-limit",
|
||
"--block-limit",
|
||
"--dry-run",
|
||
],
|
||
)?;
|
||
let cfg = config(req(&o, "--config")?)?;
|
||
let node_name = o.get("--node").cloned().unwrap_or_else(|| String::from("node0"));
|
||
let gas_limit: i64 = match o.get("--gas-limit") {
|
||
Some(v) => v
|
||
.parse()
|
||
.map_err(|_| String::from("--gas-limit 必须是整数"))?,
|
||
None => 30_000_000,
|
||
};
|
||
let block_limit: i64 = match o.get("--block-limit") {
|
||
Some(v) => v
|
||
.parse()
|
||
.map_err(|_| String::from("--block-limit 必须是整数"))?,
|
||
None => 500,
|
||
};
|
||
if gas_limit <= 0 {
|
||
return Err(String::from("--gas-limit 必须为正"));
|
||
}
|
||
|
||
// ★ solc 产物 → FISCO ABI(补二元 selector 数组)。
|
||
let (bin, solc_abi) = load_solc_artifacts(req(&o, "--abi")?)?;
|
||
let fisco_abi = mpc_chain::fisco_abi::fisco_abi_json_from_solc(&solc_abi)
|
||
.map_err(|e| e.to_string())?;
|
||
|
||
let key_pem = read(req(&o, "--key")?)?;
|
||
let signer = PrehashedSm2Signer::from_private_pem(key_pem.as_bytes())
|
||
.map_err(|e| e.to_string())?;
|
||
|
||
let params = DeployParams {
|
||
bytecode: bin,
|
||
abi_json: fisco_abi.clone(),
|
||
chain_id: cfg.chain_id.clone(),
|
||
group_id: cfg.group_id.clone(),
|
||
block_limit,
|
||
nonce: random_nonce().map_err(|e| e.to_string())?,
|
||
gas_limit,
|
||
constructor_args: Vec::new(),
|
||
constructor_values: Vec::new(),
|
||
};
|
||
let data = build_deploy_transaction_data(¶ms).map_err(|e| e.to_string())?;
|
||
data.validate().map_err(|e| e.to_string())?;
|
||
// ★ 部署交易的 attribute = EVM_ABI_CODEC(0x1)(非 WASM 链的 Solidity 合约)。
|
||
let (tx, tx_bytes) = mpc_chain::fisco_tx::build_signed_transaction_with_attribute(
|
||
&data,
|
||
&signer,
|
||
mpc_chain::fisco_abi::ATTRIBUTE_EVM_ABI_CODEC,
|
||
)
|
||
.map_err(|e| e.to_string())?;
|
||
|
||
// ★ --dry-run:只构造、只打印,**不发交易**。
|
||
// 用途是把 dataHash / 签名 / 公钥 / 交易字段拿到手,去和官方 SDK 或独立验签器对拍。
|
||
// 「构造成功」不等于「链上会收」,所以 dry-run 绝不能被当成部署成功。
|
||
// 取值形式 `--dry-run=1`(`opts` 是通用的「键必带值」解析器,不为它破例)。
|
||
if o.get("--dry-run").map(String::as_str) == Some("1") {
|
||
println!(
|
||
"{{\"dryRun\":true,\"dataHash\":\"{}\",\"signature\":\"{}\",\"publicKey\":\"{}\",\"txBytes\":{},\"attribute\":{},\"txBytesHex\":\"{}\",\"txData\":{}}}",
|
||
to_hex(&tx.data_hash),
|
||
to_hex(&tx.signature),
|
||
to_hex(signer.public_key()),
|
||
tx_bytes.len(),
|
||
tx.attribute,
|
||
to_hex(&tx_bytes),
|
||
tx_data_json(&data),
|
||
);
|
||
return Ok(());
|
||
}
|
||
|
||
let client = HttpChainClient::new(&cfg.rpc_endpoint).map_err(|e| e.to_string())?;
|
||
let r = client
|
||
.send_transaction(&cfg.group_id, &node_name, &to_hex(&tx_bytes), true)
|
||
.map_err(|e| format!("sendTransaction 失败: {e}"))?;
|
||
|
||
// ★ 成功判据三件套,缺一不可。
|
||
let ok = r.status_code == Some(0) && !r.tx_hash.is_empty() && r.block_number.unwrap_or(0) > 0;
|
||
let contract_address = r.contract_address.clone();
|
||
if !ok {
|
||
return Err(format!(
|
||
"部署未被链上确认为成功: status={:?} txHash={} blockNumber={:?} \
|
||
contractAddress={}",
|
||
r.status_code,
|
||
r.tx_hash,
|
||
r.block_number,
|
||
contract_address
|
||
));
|
||
}
|
||
// ★ 部署成功但拿不到合约地址 ⇒ 后续没法调用,必须显式失败。
|
||
if contract_address.is_empty() {
|
||
return Err(format!(
|
||
"部署交易成功(txHash={})但回执里没有 contractAddress:\
|
||
后续无法调用,拒绝当作成功",
|
||
r.tx_hash
|
||
));
|
||
}
|
||
println!(
|
||
"{{\"deployed\":true,\"contractAddress\":\"{}\",\"txHash\":\"{}\",\"status\":{},\"blockNumber\":{},\"gasUsed\":{},\"txBytes\":{},\"attribute\":{},\"abiBytes\":{},\"binBytes\":{},\"signerProfile\":\"SoftwareDev\",\"warning\":\"{}\"}}",
|
||
esc(&contract_address),
|
||
esc(&r.tx_hash),
|
||
r.status_code.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
r.block_number.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
r.gas_used.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
tx_bytes.len(),
|
||
tx.attribute,
|
||
fisco_abi.len(),
|
||
params.bytecode.len(),
|
||
esc(SOFTWARE_DEV_WARNING)
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
/// 调用已部署合约的写接口:真交易上链。
|
||
fn cmd_contract_call(args: &[String]) -> Result<(), String> {
|
||
let o = opts(
|
||
args,
|
||
&[
|
||
"--config",
|
||
"--contract",
|
||
"--method",
|
||
"--abi",
|
||
"--key",
|
||
"--node",
|
||
"--gas-limit",
|
||
"--arg",
|
||
],
|
||
)?;
|
||
let cfg = config(req(&o, "--config")?)?;
|
||
let node_name = o.get("--node").cloned().unwrap_or_else(|| String::from("node0"));
|
||
let gas_limit: i64 = match o.get("--gas-limit") {
|
||
Some(v) => v
|
||
.parse()
|
||
.map_err(|_| String::from("--gas-limit 必须是整数"))?,
|
||
None => 30_000_000,
|
||
};
|
||
if gas_limit <= 0 {
|
||
return Err(String::from("--gas-limit 必须为正"));
|
||
}
|
||
let contract_addr = req(&o, "--contract")?.to_string();
|
||
let addr_bytes = mpc_chain::from_hex(contract_addr.trim_start_matches("0x"))
|
||
.map_err(|e| e.to_string())?;
|
||
if addr_bytes.len() != 20 {
|
||
return Err(format!(
|
||
"--contract 必须是不带 0x 前缀的 20 字节合约地址,收到 {} 字节",
|
||
addr_bytes.len()
|
||
));
|
||
}
|
||
let method = req(&o, "--method")?.to_string();
|
||
let (_, solc_abi) = load_solc_artifacts(req(&o, "--abi")?)?;
|
||
let fisco_abi = mpc_chain::fisco_abi::fisco_abi_json_from_solc(&solc_abi)
|
||
.map_err(|e| e.to_string())?;
|
||
let params_types = mpc_chain::fisco_abi::function_input_types(&fisco_abi, &method)
|
||
.map_err(|e| e.to_string())?;
|
||
let mut args_vals: Vec<ContractValue> = Vec::new();
|
||
for spec in multi(&o, "--arg") {
|
||
let (ty, val) = parse_arg(&spec)?;
|
||
args_vals.push(val);
|
||
// 类型必须与 ABI 声明一致,否则选择子/编码全错。
|
||
if let Some(expected) = params_types.get(args_vals.len() - 1) {
|
||
if *expected != ty {
|
||
return Err(format!(
|
||
"--arg 第 {} 个的类型是 {},ABI 声明的是 {}",
|
||
args_vals.len(),
|
||
ty.canonical(),
|
||
expected.canonical()
|
||
));
|
||
}
|
||
}
|
||
}
|
||
if args_vals.len() != params_types.len() {
|
||
return Err(format!(
|
||
"--arg 给了 {} 个,ABI 声明 {} 个",
|
||
args_vals.len(),
|
||
params_types.len()
|
||
));
|
||
}
|
||
|
||
let call_data = encode_call(&method, ¶ms_types, &args_vals).map_err(|e| e.to_string())?;
|
||
let key_pem = read(req(&o, "--key")?)?;
|
||
let signer = PrehashedSm2Signer::from_private_pem(key_pem.as_bytes())
|
||
.map_err(|e| e.to_string())?;
|
||
let data = TransactionData {
|
||
version: 1,
|
||
chain_id: cfg.chain_id.clone(),
|
||
group_id: cfg.group_id.clone(),
|
||
block_limit: 500,
|
||
nonce: random_nonce().map_err(|e| e.to_string())?,
|
||
to: contract_addr.clone(),
|
||
input: call_data,
|
||
// ★ 调用交易**不带** abi(abi 是部署时写进链上的)。
|
||
abi: String::new(),
|
||
value: String::from("0x0"),
|
||
gas_price: String::from("0x0"),
|
||
gas_limit,
|
||
max_fee_per_gas: String::from("0x0"),
|
||
max_priority_fee_per_gas: String::from("0x0"),
|
||
extension: Vec::new(),
|
||
};
|
||
data.validate().map_err(|e| e.to_string())?;
|
||
// ★ 调用交易 attribute = 0(java-sdk 的 createSignedTransaction 路径)。
|
||
let (_tx, tx_bytes) =
|
||
mpc_chain::fisco_tx::build_signed_transaction_with_attribute(&data, &signer, 0)
|
||
.map_err(|e| e.to_string())?;
|
||
|
||
let client = HttpChainClient::new(&cfg.rpc_endpoint).map_err(|e| e.to_string())?;
|
||
let r = client
|
||
.send_transaction(&cfg.group_id, &node_name, &to_hex(&tx_bytes), true)
|
||
.map_err(|e| format!("sendTransaction 失败: {e}"))?;
|
||
|
||
let ok = r.status_code == Some(0) && !r.tx_hash.is_empty() && r.block_number.unwrap_or(0) > 0;
|
||
if !ok {
|
||
return Err(format!(
|
||
"调用未被链上确认为成功: status={:?} txHash={} blockNumber={:?} output={}",
|
||
r.status_code,
|
||
r.tx_hash,
|
||
r.block_number,
|
||
r.output
|
||
));
|
||
}
|
||
println!(
|
||
"{{\"called\":true,\"contract\":\"{}\",\"method\":\"{}\",\"selector\":\"{}\",\"txHash\":\"{}\",\"status\":{},\"blockNumber\":{},\"gasUsed\":{},\"txBytes\":{},\"attribute\":{},\"signerProfile\":\"SoftwareDev\",\"warning\":\"{}\"}}",
|
||
esc(&contract_addr),
|
||
esc(&method),
|
||
esc(&to_hex(&mpc_chain::contract::sm3_selector(&mpc_chain::contract::function_signature(
|
||
&method,
|
||
¶ms_types
|
||
)))),
|
||
esc(&r.tx_hash),
|
||
r.status_code.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
r.block_number.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
r.gas_used.map(|v| v.to_string()).unwrap_or_else(|| "null".into()),
|
||
tx_bytes.len(),
|
||
_tx.attribute,
|
||
esc(SOFTWARE_DEV_WARNING)
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
/// 只读调用:走 FISCO 自有 `call` 端点(4 参),**不上链**。
|
||
fn cmd_contract_read(args: &[String]) -> Result<(), String> {
|
||
let o = opts(
|
||
args,
|
||
&["--config", "--contract", "--method", "--abi", "--node", "--arg"],
|
||
)?;
|
||
let cfg = config(req(&o, "--config")?)?;
|
||
let node_name = o.get("--node").cloned().unwrap_or_else(|| String::from("node0"));
|
||
let contract_addr = req(&o, "--contract")?.to_string();
|
||
let addr_bytes = mpc_chain::from_hex(contract_addr.trim_start_matches("0x"))
|
||
.map_err(|e| e.to_string())?;
|
||
if addr_bytes.len() != 20 {
|
||
return Err(format!(
|
||
"--contract 必须是不带 0x 前缀的 20 字节合约地址,收到 {} 字节",
|
||
addr_bytes.len()
|
||
));
|
||
}
|
||
let method = req(&o, "--method")?.to_string();
|
||
let (_, solc_abi) = load_solc_artifacts(req(&o, "--abi")?)?;
|
||
let fisco_abi = mpc_chain::fisco_abi::fisco_abi_json_from_solc(&solc_abi)
|
||
.map_err(|e| e.to_string())?;
|
||
let params_types = mpc_chain::fisco_abi::function_input_types(&fisco_abi, &method)
|
||
.map_err(|e| e.to_string())?;
|
||
let mut args_vals: Vec<ContractValue> = Vec::new();
|
||
for spec in multi(&o, "--arg") {
|
||
let (ty, val) = parse_arg(&spec)?;
|
||
args_vals.push(val);
|
||
if let Some(expected) = params_types.get(args_vals.len() - 1) {
|
||
if *expected != ty {
|
||
return Err(format!(
|
||
"--arg 第 {} 个的类型是 {},ABI 声明的是 {}",
|
||
args_vals.len(),
|
||
ty.canonical(),
|
||
expected.canonical()
|
||
));
|
||
}
|
||
}
|
||
}
|
||
if args_vals.len() != params_types.len() {
|
||
return Err(format!(
|
||
"--arg 给了 {} 个,ABI 声明 {} 个",
|
||
args_vals.len(),
|
||
params_types.len()
|
||
));
|
||
}
|
||
let call_data = encode_call(&method, ¶ms_types, &args_vals).map_err(|e| e.to_string())?;
|
||
|
||
let client = HttpChainClient::new(&cfg.rpc_endpoint).map_err(|e| e.to_string())?;
|
||
// ★ FISCO 自有 `call`:**4 参** `[groupID, nodeName, to, data]`。
|
||
// 第 5 参是「签名」,不是 web3 的 "latest" 块号。
|
||
let out = client
|
||
.call(&cfg.group_id, &node_name, &contract_addr, &to_hex(&call_data))
|
||
.map_err(|e| format!("call 失败: {e}"))?;
|
||
println!(
|
||
"{{\"read\":true,\"contract\":\"{}\",\"method\":\"{}\",\"selector\":\"{}\",\"output\":\"{}\",\"onChain\":false,\"note\":\"只读调用走 FISCO 自有 call 端点,不产生交易\"}}",
|
||
esc(&contract_addr),
|
||
esc(&method),
|
||
esc(&to_hex(&mpc_chain::contract::sm3_selector(&mpc_chain::contract::function_signature(
|
||
&method,
|
||
¶ms_types
|
||
)))),
|
||
esc(&out)
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
/// 把 solc ABI 转成 FISCO ABI(补二元 selector 数组)并落盘。
|
||
fn cmd_contract_abi(args: &[String]) -> Result<(), String> {
|
||
let o = opts(args, &["--solc-abi", "--out"])?;
|
||
let text = read(req(&o, "--solc-abi")?)?;
|
||
let fisco = mpc_chain::fisco_abi::fisco_abi_json_from_solc(&text)
|
||
.map_err(|e| e.to_string())?;
|
||
let out_path = req(&o, "--out")?;
|
||
fs::write(out_path, &fisco).map_err(|e| format!("写 {out_path} 失败: {e}"))?;
|
||
println!(
|
||
"{{\"converted\":true,\"out\":\"{}\",\"bytes\":{},\"selectorArray\":\"[keccak_u32,sm3_u32]\"}}",
|
||
esc(out_path),
|
||
fisco.len()
|
||
);
|
||
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(())
|
||
}
|
||
|
||
fn cmd_keygen(args: &[String]) -> Result<(), String> {
|
||
let o = opts(args, &["--out", "--pub-out"])?;
|
||
let s = OpenSslSoftwareSigner::generate_for_development().map_err(|e| e.to_string())?;
|
||
let priv_pem = s.private_pem_pkcs8().map_err(|e| e.to_string())?;
|
||
let pub_pem = s.public_pem().map_err(|e| e.to_string())?;
|
||
write_private(req(&o, "--out")?, &priv_pem)?;
|
||
fs::write(req(&o, "--pub-out")?, &pub_pem)
|
||
.map_err(|e| format!("写公钥失败: {e}"))?;
|
||
eprintln!("{SOFTWARE_DEV_WARNING}");
|
||
println!(
|
||
"{{\"algorithm\":\"SM2\",\"signerProfile\":\"SoftwareDev\",\"pubkeyHex\":\"{}\",\"distid\":\"{}\",\"distidFingerprint\":\"{}\",\"warning\":\"{}\"}}",
|
||
to_hex(s.public_key()),
|
||
String::from_utf8_lossy(SM2_DISTID),
|
||
to_hex(&distid_fingerprint()),
|
||
esc(SOFTWARE_DEV_WARNING)
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
fn cmd_sign(args: &[String]) -> Result<(), String> {
|
||
let o = opts(args, &["--key", "--file", "--policy"])?;
|
||
let policy = parse_policy(req(&o, "--policy")?)?;
|
||
let pem = fs::read(req(&o, "--key")?).map_err(|e| format!("读私钥失败: {e}"))?;
|
||
let s = OpenSslSoftwareSigner::from_private_pem(&pem).map_err(|e| e.to_string())?;
|
||
require_self_test(&s, policy).map_err(|e| e.to_string())?;
|
||
let msg = fs::read(req(&o, "--file")?).map_err(|e| format!("读待签字节失败: {e}"))?;
|
||
let raw = s.sign(&msg).map_err(|e| e.to_string())?;
|
||
let arr: [u8; 64] = raw
|
||
.as_slice()
|
||
.try_into()
|
||
.map_err(|_| String::from("签名不是 64 字节"))?;
|
||
let der = raw_rs_to_der(&arr).map_err(|e| e.to_string())?;
|
||
let st = s.self_test().map_err(|e| e.to_string())?;
|
||
if policy == SignerPolicy::DevelopmentSoftware {
|
||
eprintln!("{SOFTWARE_DEV_WARNING}");
|
||
}
|
||
println!(
|
||
"{{\"algorithm\":\"SM2\",\"signerProfile\":\"{}\",\"policy\":\"{}\",\"rawSigHex\":\"{}\",\"derSigHex\":\"{}\",\"pubkeyHex\":\"{}\",\"distid\":\"{}\",\"distidFingerprint\":\"{}\",\"selfTest\":{{\"providerLoaded\":{},\"privateKeyUnexportable\":{},\"katOk\":{}}}}}",
|
||
match s.security_profile() {
|
||
SignerSecurityProfile::HardwareModule => "HardwareModule",
|
||
SignerSecurityProfile::SoftwareDev => "SoftwareDev",
|
||
},
|
||
match policy {
|
||
SignerPolicy::ProductionModule => "production-module",
|
||
SignerPolicy::DevelopmentSoftware => "development-software",
|
||
},
|
||
to_hex(&raw),
|
||
to_hex(&der),
|
||
to_hex(s.public_key()),
|
||
String::from_utf8_lossy(SM2_DISTID),
|
||
to_hex(&distid_fingerprint()),
|
||
st.provider_loaded,
|
||
st.private_key_unexportable,
|
||
st.kat_ok
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
fn cmd_align(args: &[String]) -> Result<(), String> {
|
||
let o = opts(args, &["--chain-verifier-distid", "--csv-distid"])?;
|
||
let fallback = String::from_utf8_lossy(SM2_DISTID).to_string();
|
||
let cv = o.get("--chain-verifier-distid").map(String::as_str).unwrap_or(&fallback);
|
||
let csv = o.get("--csv-distid").map(String::as_str).unwrap_or(&fallback);
|
||
let decls: Vec<(DistidConsumer, &[u8])> = vec![
|
||
(DistidConsumer::ChainSigner, SM2_DISTID),
|
||
(DistidConsumer::ChainVerifier, cv.as_bytes()),
|
||
(DistidConsumer::AttestationCsvSm2, csv.as_bytes()),
|
||
];
|
||
let fp = aligned_distid(&decls).map_err(|e| e.to_string())?;
|
||
println!(
|
||
"{{\"aligned\":true,\"distid\":\"{}\",\"fingerprint\":\"{}\",\"consumers\":[\"chain_signer\",\"chain_verifier\",\"attestation_csv_sm2\"]}}",
|
||
esc(&fallback),
|
||
to_hex(&fp)
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
fn cmd_tlcp(args: &[String]) -> Result<(), String> {
|
||
match args.first().map(String::as_str) {
|
||
Some("send") => cmd_tlcp_send(&args[1..]),
|
||
_ => cmd_tlcp_status(args),
|
||
}
|
||
}
|
||
|
||
fn cmd_tlcp_status(_args: &[String]) -> Result<(), String> {
|
||
let o = opts(_args, &["--file"])?;
|
||
let p = probe_tlcp_environment();
|
||
let (config_ok, detail) = match o.get("--file") {
|
||
Some(path) => match TlcpConfig::from_json(&read(path)?) {
|
||
Ok(cfg) => match mpc_chain::tlcp::require_tlcp_transport(&cfg) {
|
||
Ok(r) => (true, format!("{r:?}")),
|
||
Err(e) => (false, e.to_string()),
|
||
},
|
||
Err(e) => (false, e.to_string()),
|
||
},
|
||
None => (false, String::from("未提供 TLCP 双证书配置")),
|
||
};
|
||
let readiness = if p.backend == TlcpBackend::None {
|
||
TlcpReadiness::MissingEnvironment
|
||
} else {
|
||
// ★ 环境齐备 + Rust 侧 TLCP 进程通道(TlcpTunnel)已接入 ⇒ 通道层环回可达。
|
||
// 但服务端是 gmssl 环回 echo,不是 bcos-rpc 真机;realChainVerified 恒 false。
|
||
TlcpReadiness::LoopbackReachable
|
||
};
|
||
let ready = readiness == TlcpReadiness::Ready && config_ok;
|
||
let channel_layer_reachable = readiness == TlcpReadiness::LoopbackReachable && config_ok;
|
||
let real_chain_verified = false;
|
||
let reason = match p.backend {
|
||
TlcpBackend::None => format!(
|
||
"本机既无 OpenSSL/Tongsuo TLCP 套件({}),也无可用 GmSSL;\
|
||
需要 Tongsuo ≥ 8.4 或 GmSSL ≥ 3.2;拒绝以明文/标准 TLS 冒充国密通道",
|
||
p.openssl_version
|
||
),
|
||
TlcpBackend::GmSSL => String::from(
|
||
"GmSSL TLCP 本机握手与进程通道已可用(环回 echo 实证),但服务端不是 bcos-rpc 真机,\
|
||
未验证 bcos-rpc 启用 TLCP,也无硬件国密模组;发真交易仍被拒",
|
||
),
|
||
TlcpBackend::Tongsuo => String::from(
|
||
"Tongsuo TLCP 环境齐备(通道代码已接入),但发真交易仍须 bcos-rpc 真机验证",
|
||
),
|
||
};
|
||
println!(
|
||
"{{\"ready\":{},\"readiness\":\"{:?}\",\"channelLayerReachable\":{},\"realChainVerified\":{},\"configOk\":{},\"backend\":\"{:?}\",\"opensslVersion\":\"{}\",\"tlcpCipherAvailable\":{},\"tongsuoLib\":{},\"gmsslAvailable\":{},\"gmsslVersion\":{},\"gmsslTlcpCommands\":{},\"detail\":\"{}\",\"reason\":\"{}\"}}",
|
||
ready,
|
||
readiness,
|
||
channel_layer_reachable,
|
||
real_chain_verified,
|
||
config_ok,
|
||
p.backend,
|
||
esc(&p.openssl_version),
|
||
p.tlcp_cipher_available,
|
||
p.tongsuo_lib
|
||
.as_deref()
|
||
.map(|s| format!("\"{}\"", esc(s)))
|
||
.unwrap_or_else(|| String::from("null")),
|
||
p.gmssl_version.is_some(),
|
||
p.gmssl_version
|
||
.as_deref()
|
||
.map(|s| format!("\"{}\"", esc(s)))
|
||
.unwrap_or_else(|| String::from("null")),
|
||
p.gmssl_tlcp_commands,
|
||
esc(&detail),
|
||
esc(&reason)
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
/// 经 TLCP 进程通道把一个请求体发给某 endpoint 并读回响应。
|
||
///
|
||
/// ★ 诚实边界:这只是「通道层环回实证」,把 JSON-RPC 经 TLCP 发到 endpoint
|
||
/// 并读回响应;不保证 endpoint 是 bcos-rpc。输出里 `realChainVerified`
|
||
/// 恒 false,明确标注「不等于通道已通」。
|
||
fn cmd_tlcp_send(args: &[String]) -> Result<(), String> {
|
||
let o = opts(
|
||
args,
|
||
&[
|
||
"--host",
|
||
"--port",
|
||
"--ca",
|
||
"--payload",
|
||
"--cipher-suite",
|
||
"--server-name",
|
||
"--cert",
|
||
"--key",
|
||
"--pass",
|
||
"--timeout",
|
||
],
|
||
)?;
|
||
let host = o.get("--host").cloned().ok_or_else(|| String::from("缺 --host"))?;
|
||
let port = o
|
||
.get("--port")
|
||
.cloned()
|
||
.ok_or_else(|| String::from("缺 --port"))?
|
||
.parse::<u16>()
|
||
.map_err(|e| format!("--port 不是合法端口: {e}"))?;
|
||
let ca_path = o
|
||
.get("--ca")
|
||
.cloned()
|
||
.ok_or_else(|| String::from("缺 --ca(CA 证书文件路径)"))?;
|
||
let payload_path = o
|
||
.get("--payload")
|
||
.cloned()
|
||
.ok_or_else(|| String::from("缺 --payload(请求体文件路径)"))?;
|
||
let cipher = o
|
||
.get("--cipher-suite")
|
||
.cloned()
|
||
.unwrap_or_else(|| String::from("TLS_ECC_SM4_CBC_SM3"));
|
||
let timeout = o
|
||
.get("--timeout")
|
||
.cloned()
|
||
.and_then(|s| s.parse::<u64>().ok())
|
||
.unwrap_or(0);
|
||
let ca_pem = read(&ca_path)?;
|
||
let payload = read(&payload_path)?;
|
||
let server_name = o.get("--server-name").cloned();
|
||
let client_sign_cert_pem = o.get("--cert").map(|p| read(p)).transpose()?;
|
||
let client_sign_key_pem = o.get("--key").map(|p| read(p)).transpose()?;
|
||
let client_key_pass = o.get("--pass").cloned();
|
||
let endpoint = TlcpEndpoint {
|
||
host,
|
||
port,
|
||
ca_pem: ca_pem.into_bytes(),
|
||
cipher_suite: cipher,
|
||
server_name,
|
||
client_sign_cert_pem: client_sign_cert_pem.map(|v| v.into_bytes()),
|
||
client_sign_key_pem: client_sign_key_pem.map(|v| v.into_bytes()),
|
||
client_key_pass,
|
||
};
|
||
let tun = TlcpTunnel::open(endpoint).map_err(|e| format!("开 TLCP 通道失败: {e}"))?;
|
||
let resp = tun
|
||
.send(payload.as_bytes(), timeout)
|
||
.map_err(|e| format!("经 TLCP 发送失败: {e}"))?;
|
||
let resp_text = String::from_utf8_lossy(&resp);
|
||
let resp_hex: String = resp.iter().map(|b| format!("{b:02x}")).collect();
|
||
println!(
|
||
"{{\"sentBytes\":{},\"receivedBytes\":{},\"channelLayerReachable\":true,\"realChainVerified\":false,\"responseText\":\"{}\",\"responseHexPrefix\":\"{}\",\"note\":\"环回 echo 服务端不是 bcos-rpc,本结果不等于 bcos-rpc 通道已通\"}}",
|
||
payload.len(),
|
||
resp.len(),
|
||
esc(&resp_text.chars().take(200).collect::<String>()),
|
||
resp_hex.chars().take(32).collect::<String>(),
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
fn cmd_governance(args: &[String]) -> Result<(), String> {
|
||
let o = opts(args, &["--config", "--kind", "--file"])?;
|
||
let cfg = config(req(&o, "--config")?)?;
|
||
governance_boundary().map_err(|e| e.to_string())?;
|
||
let text = read(req(&o, "--file")?)?;
|
||
let kind = req(&o, "--kind")?;
|
||
let obj: Box<dyn ChainObject> = match kind {
|
||
"hard-rule" => Box::new(HardRuleSet::from_json(&text).map_err(|e| e.to_string())?),
|
||
"opa-bundle" => Box::new(OpaPolicyBundle::from_json(&text).map_err(|e| e.to_string())?),
|
||
other => return Err(format!("--kind 只能是 hard-rule|opa-bundle,得到 {other}")),
|
||
};
|
||
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\":{},\"target\":\"{}\"}}",
|
||
esc(kind),
|
||
esc(cfg.hash_suite()),
|
||
to_hex(&digest),
|
||
to_hex(&bytes),
|
||
bytes.len(),
|
||
if kind == "hard-rule" { "合约" } else { "OPA(不上链)" }
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
const OPA_HONESTY_WARNING: &str =
|
||
"警告: OPA 在宿主/控制面执行,不在 guest 内;撤销视图是调用方提供的本地桩(链上状态位读取未落地);decision 仅入 outbox,未签名、未上链";
|
||
|
||
fn parse_policy(s: &str) -> Result<SignerPolicy, String> {
|
||
match s {
|
||
"production-module" => Ok(SignerPolicy::ProductionModule),
|
||
"development-software" => Ok(SignerPolicy::DevelopmentSoftware),
|
||
other => Err(format!(
|
||
"--policy 只能是 production-module|development-software,得到 {other}"
|
||
)),
|
||
}
|
||
}
|
||
|
||
fn cmd_opa(args: &[String]) -> Result<(), String> {
|
||
match args.first().map(String::as_str) {
|
||
Some("sign") => cmd_opa_sign(&args[1..]),
|
||
Some("decide") => cmd_opa_decide(&args[1..]),
|
||
_ => Err(String::from("用法: mpc chain opa sign|decide ...(见 mpc chain 帮助)")),
|
||
}
|
||
}
|
||
|
||
/// 控制面签发:对**真的 opa build 产物**做 SM3 hash pin + SM2 真签。
|
||
fn cmd_opa_sign(args: &[String]) -> Result<(), String> {
|
||
let o = opts(
|
||
args,
|
||
&["--bundle", "--key", "--id", "--issuer", "--expires", "--policy", "--out"],
|
||
)?;
|
||
let policy = parse_policy(req(&o, "--policy")?)?;
|
||
let bundle = fs::read(req(&o, "--bundle")?).map_err(|e| format!("读 bundle 失败: {e}"))?;
|
||
let key = fs::read(req(&o, "--key")?).map_err(|e| format!("读私钥失败: {e}"))?;
|
||
let expires: u64 = req(&o, "--expires")?
|
||
.parse()
|
||
.map_err(|e| format!("--expires 不是非负整数: {e}"))?;
|
||
let m = sign_bundle(
|
||
&bundle,
|
||
req(&o, "--id")?,
|
||
req(&o, "--issuer")?,
|
||
expires,
|
||
&key,
|
||
policy,
|
||
)
|
||
.map_err(|e| e.to_string())?;
|
||
fs::write(req(&o, "--out")?, m.to_json())
|
||
.map_err(|e| format!("写签发清单失败: {e}"))?;
|
||
|
||
// 供外部(系统 openssl CLI)独立验签:raw r||s → DER。
|
||
let raw = from_hex(&m.signature_raw_hex).map_err(|e| e.to_string())?;
|
||
let arr: [u8; 64] = raw
|
||
.as_slice()
|
||
.try_into()
|
||
.map_err(|_| String::from("SM2 签名不是 64 字节"))?;
|
||
let der = raw_rs_to_der(&arr).map_err(|e| e.to_string())?;
|
||
if policy == SignerPolicy::DevelopmentSoftware {
|
||
eprintln!("{SOFTWARE_DEV_WARNING}");
|
||
}
|
||
println!(
|
||
"{{\"manifestPath\":\"{}\",\"bundleId\":\"{}\",\"bundleHash\":\"{}\",\"canonicalHex\":\"{}\",\"derSigHex\":\"{}\",\"signerProfile\":\"SoftwareDev\",\"policy\":\"{}\",\"warning\":\"{}\"}}",
|
||
esc(req(&o, "--out")?),
|
||
esc(&m.bundle_id),
|
||
m.bundle_hash,
|
||
m.canonical_hex,
|
||
to_hex(&der),
|
||
match policy {
|
||
SignerPolicy::ProductionModule => "production-module",
|
||
SignerPolicy::DevelopmentSoftware => "development-software",
|
||
},
|
||
esc(SOFTWARE_DEV_WARNING)
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
/// 验签 → 有效期 → 撤销 → input 来源 → **真 opa eval** → decision 幂等落 outbox。
|
||
fn cmd_opa_decide(args: &[String]) -> Result<(), String> {
|
||
let o = opts(
|
||
args,
|
||
&[
|
||
"--bundle", "--manifest", "--input", "--revocation", "--query", "--now",
|
||
"--outbox", "--order-id",
|
||
],
|
||
)?;
|
||
let query = req(&o, "--query")?;
|
||
let now: u64 = req(&o, "--now")?
|
||
.parse()
|
||
.map_err(|e| format!("--now 不是非负整数: {e}"))?;
|
||
// 缺 opa 二进制必须在这里明确报错,不许降级成「默认拒绝」蒙过去。
|
||
let runner = OpaRunner::resolve().map_err(|e| e.to_string())?;
|
||
let manifest_text = read(req(&o, "--manifest")?)?;
|
||
// 撤销来源:显式 `--revocation chain` 声明走链上读取(当前后端未接入,
|
||
// decide 会 fail-closed 拒);否则必须是本地桩文件路径。缺参由 req 必填报错。
|
||
let revocation_arg = req(&o, "--revocation")?;
|
||
let revocation = if revocation_arg == "chain" {
|
||
RevocationViewSource::ChainRead
|
||
} else {
|
||
let text = read(revocation_arg)?;
|
||
RevocationViewSource::CallerSupplied(
|
||
RevocationView::from_json(&text).map_err(|e| e.to_string())?,
|
||
)
|
||
};
|
||
// 先取标注再移动(revocation 会被 move 进 DecideRequest)。
|
||
let rev_src_label = match &revocation {
|
||
RevocationViewSource::ChainRead => "chain-read",
|
||
RevocationViewSource::CallerSupplied(_) => "caller-supplied-local-view-not-chain-read",
|
||
};
|
||
let r = DecideRequest {
|
||
manifest_text: &manifest_text,
|
||
revocation,
|
||
bundle_path: Path::new(req(&o, "--bundle")?),
|
||
input_path: Path::new(req(&o, "--input")?),
|
||
query,
|
||
now,
|
||
runner: &runner,
|
||
};
|
||
let d = decide(&r).map_err(|e| e.to_string())?;
|
||
|
||
let mut box_ = Outbox::open(req(&o, "--outbox")?).map_err(|e| e.to_string())?;
|
||
let outcome = box_
|
||
.enqueue(
|
||
"decision",
|
||
req(&o, "--order-id")?,
|
||
&d.decision_id,
|
||
&d.canonical_bytes(),
|
||
)
|
||
.map_err(|e| e.to_string())?;
|
||
|
||
let mut out = d.to_json();
|
||
out.pop(); // 去掉结尾的 },补上本层的诚实标注字段
|
||
let bin = runner.binary.display().to_string();
|
||
println!(
|
||
"{},\"query\":\"{}\",\"outbox\":\"{}\",\"opaBinary\":\"{}\",\"opaInGuest\":false,\"revocationSource\":\"{}\",\"chainRecorded\":false,\"decisionStoredAs\":\"outbox-pending-not-signed-tx\",\"warning\":\"{}\"}}",
|
||
out,
|
||
esc(query),
|
||
match outcome {
|
||
EnqueueOutcome::Added => "added",
|
||
EnqueueOutcome::AlreadyPresent => "already-present",
|
||
},
|
||
esc(&bin),
|
||
rev_src_label,
|
||
esc(OPA_HONESTY_WARNING)
|
||
);
|
||
Ok(())
|
||
}
|